develooper Front page | perl.beginners | Postings from December 2002

Floating point errors in Perl

Thread Next
From:
Ed Christian
Date:
December 3, 2002 12:45
Subject:
Floating point errors in Perl
Message ID:
E989917C9FF25240A201E888E83DF32F020294@EXCHANGE5.corp.ptd.net
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*

TIA,
- Ed

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About