Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://881789]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2018-07-22 13:12 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (454 votes). Check out past polls.