Perl: How to compare floating numbers

floating-point, perl

Solution

All computations that use floating point numbers may have precision errors, and if you reuse the results, those precision erros stack up. One thing to learn from that is to never use a float as a loop control variable.

Use something like

for (my $tmp=2; $tmp<=20; tmp++) {
    print $tmp/20.0, "\n";
}

whereever you can. If you really really need to compare two floats `($a, $b)` something like

if (abs($a - $b) < 0.000001)

is the only thing that really works -- however, this might have issues as well depending on how small the difference can be to count as a real difference.

Problem

I wrote the following Perl script. However, it does not print "1". I did some research and it seems it is because of the IEEE representation of floating-point number. So, is there a better way to compare floating-point numbers in Perl? ``` for (my $tmp = 0.1; $tmp <= 1; $tmp+=0.05){print $tmp."\n"} ``` Output: ``` 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95 ```

Original source