Ed

A classic problem with a classic solution. Change things to use integer
arithmetic:

    my $increment = 0.01;

    for (0 .. 100 / $increment)
    {
        $percentile = $_ * $increment;
        print "$percentile\n";
    }

HTH,

Rob

----- Original Message -----
From: "Ed Christian" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Sent: Tuesday, December 03, 2002 8:45 PM
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*
>
> TIA,
> - Ed
>
> --
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
>
>


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to