Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: floating points and sprintf

by Anonymous Monk
on Nov 14, 2002 at 16:34 UTC ( [id://212903]=note: print w/replies, xml ) Need Help??


in reply to floating points and sprintf

As Perl is based on c, let's look at how c handles this. In c, you can do:
float x = 147.2; printf("%20.20f", x * 100);
it gives you 14719.99969482421875000000, which is fine, unless you are working on some finance application (COBOL will not have this problem, as its decimal is fixed; In Java you will have same thing as c, as Java is also c based, just like Perl, but Java has a class called BigDecimal, which holds fixed decimal.)
However, when you try
float x = 147.2; printf("%d", x * 100);
It produces -167772160, which is garbage, but it is not a c problem, it is the programmer's problem, as c is trying to interprete that piece of memory as integer, as the programmer required.
To resolve this problem, when they develop Perl, they did this:
float x = 147.2; printf("%d", (int)(x * 100));
which prints out 14719.
So a new problem is introduced. However this would be fine to most people, most of the time. If you really care the accuracy and precision, because of the nature of your application, then try Math::BigFloat.

Replies are listed 'Best First'.
Re: Re: floating points and sprintf
by pg (Canon) on Nov 14, 2002 at 17:07 UTC
    I digged a little bit. Try this, go module Math::BigFloat, there is a function called norm, add one line at the end of this sub "print $_;". You will see how it stores the float as a string, and also its precision.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://212903]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-26 00:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found