Keep in mind that floating-point numbers are not the same as the real numbers you learned
about in math class. There are infinitely many real numbers between, say 0 and 1, but Perl
doesn't have an infinite number of bits to store those real numbers. Corners must be cut.
Don't believe us? In April 1997, someone submitted this to the perlbug mailing list:
Hi,
I'd appreciate if this is a known bug and if a patch is available.
int of (2.4/0.2) returns 11 instead of the expected 12.
It would seem that this poor fellow is correct: perl -e 'print int(2.4/0.2)'
indeed prints 11. You might expect it to print 12, because two-point-four divided by
oh-point-two is twelve, and the integer part of 12 is 12. Must be a bug in Perl, right?
Wrong. Floating-point numbers are not real numbers. When you divide 2.4 by 0.2, what you're
really doing is dividing Perl's binary floating-point representation of 2.4 by Perl's binary
floating-point representation of 0.2. In all computer languages that use IEEE floating-point
representations (not just Perl!) the result will be a smidgen less than 12, which is why
int(2.4/0.2) is 11. Beware.
这是PERL算法里的一段话,是不是有异曲同工之处?
> 1.2-0.3==0.9<br />
[1] FALSE<br />
> 1.0-0.1==0.9<br />
[1] TRUE<br />
> 2.3-0.2==2.1<br />
[1] FALSE<br />