Why don't I get zero when I subtract the same floating point number from Perl?

Possible duplicates:
Why is floating point arithmetic in C # inaccurate?
Why does ghci say 1.1 + 1.1 + 1.1> 3.3 is true?

#!/usr/bin/perl
$l1 = "0+0.590580+0.583742+0.579787+0.564928+0.504538+0.459805+0.433273+0.384211+0.3035810";
$l2 = "0+0.590580+0.583742+0.579788+0.564928+0.504538+0.459805+0.433272+0.384211+0.3035810";
$val1 = eval ($l1);
$val2 = eval ($l2);
$diff = (($val1 - $val2)/$val1)*100;
print " (($val1 - $val2)/$val1)*100 ==> $diff\n";

Surprisingly, the result is over.

((4.404445 - 4.404445)/4.404445)*100 ==> -2.01655014354845e-14.

Is this supposed to be ZERO? Can anyone explain this please ...

0
source share
4 answers

This is pretty close to zero, which I expect.

? 0,579787!= 0,579788 0,433273!= 0,433272. , , .

+7

perlfaq4 (, 19.9499999999999) , (, 19.95)?:


, . ( ) . . , , Perl.

perlnumber .

, printf sprintf. . " ".

printf "%.2f", 10/3;

my $number = sprintf "%.2f", 10/3;
+4

( $l1 $l2) , .

What it demonstrates is the fact that you can create two different floating-point numbers ( $val1and $val2) that look the same when printed, but internally have a slight difference. These differences may be increased if you are not careful.

Vinko Vrsalovic has posted some good links to explain why.

+3
source

All Articles