> -----Original Message----- > From: Ed Christian [mailto:[EMAIL PROTECTED]] > Sent: Tuesday, December 03, 2002 3:46 PM > To: [EMAIL PROTECTED] > Subject: Floating point errors in Perl > > > Question for the masses: > > I have a script which iterates through percentiles, > ostensibly starting > at the 0th percentile and working up to the 100th percentile. I'd like > the script to basically go as follows: > > my $increment = 0.01; > my $percentile = 0.01; > > while ($percentile < 1.00) { > print "$percentile\n"; # In the script, there's more math > involved... > $percentile += increment; > } > > Just using the above example, though, I get the following as output: > > 0.01 > 0.02 > 0.03 > <snip> > ... > </snip> > 0.8 > 0.81 > 0.820000000000001 > 0.830000000000001 > 0.840000000000001 > <snip> > ... > </snip> > 0.970000000000001 > 0.980000000000001 > 0.990000000000001 > > Granted, this is a very small margin of error, and there are many ways > to work around this (ie. iterating over integers and dividing each > integer by 100, multiplying the percentile by 100 and taking > an "int" of > it, etc...) but I was curious to see if this were a known FP error, or > if it has to do with the version of Perl (5.6.1) or OS (Red > Hat 7.3) or > hardware (dual PIII 733mhz). It took quite a bit of testing > to find that > small margin of error... *chuckle*
It's just an artifact of the way floating point numbers are represented on computers in general. A decimal number like 0.1 cannot be exactly represented in binary notation, just like the number 1/3 cannot be exactly represented in decimal notation. The general Perl solution is to use printf() or sprintf() to round to the desired precision. See the FAQ article: perldoc -q 'Why am I getting long decimals' -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]