Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Why does perl math suck?

by ikegami (Pope)
on Jan 12, 2011 at 00:27 UTC ( #881789=note: print w/replies, xml ) Need Help??


in reply to Why does perl math suck?

$ cat a.c #include <stdio.h> int main() { printf("%s\n", 5056.45 + 10112.92 == 15169.37 ? "granted" : "Stop b +laming Perl for your own mistakes!"); return 0; } $ gcc -o a a.c && a Stop blaming Perl for your own mistakes!

45/100, 92/100 and 37/100 are all periodic numbers in binary just like 1/3 is in decimal. It would take infinite storage to store it accurately as a floating point number (regardless of the language). As such, there are tiny differences between the number you specify any the number you actually have

$ perl -e'printf "%.20e\n", $_ for @ARGV' 0.45 0.92 0.37 4.50000000000000011102e-01 9.20000000000000039968e-01 3.69999999999999995559e-01

That's why you must include a tolerance for error when dealing with floating points numbers.

$ perl -le 'print abs(5056.45 + 10112.92 - 15169.37) < 0.0001 ? "as ex +pected" : "perl math sucks!"' as expected $ perl -le 'print sprintf("%.4f", 5056.45 + 10112.92) eq sprintf("%.4f +", 15169.37) ? "as expected" : "perl math sucks!"' as expected

That's 9 digits of precision, and you can even go higher.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://881789]
help
Chatterbox?
[Discipulus]: śledzie!! the only sweet my father in law eat

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (6)
As of 2017-11-21 11:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (297 votes). Check out past polls.

    Notices?