$ 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. |