in reply to Floating Point Looping In Perl

A good habit to get into (i think) is not to use equality operator at all for numerical condition testing, especially so for floating point numbers. instead test for $i<1.7
only use equality sparingly in conditionals altogether, and program defensively. Perl is not a strongly typed language, which gives flexibility, but you do need to be a bit careful sometimes. And floating point math is what it is, an approximation of decimal numbers.
the hardest line to type correctly is: stty erase ^H

Replies are listed 'Best First'.
Re^2: Floating Point Looping In Perl
by pemungkah (Priest) on Aug 13, 2010 at 22:43 UTC
    The recommendation from my numerical analysis course was to use a "delta" value when comparing, depending on "how close" the values needed to be for you to decide they were equal.

    Something like

    while ($i - $j < $delta) { ... }
    The trick is selecting a delta that works. For instance if $i was 2E40 and $j was 1E40, selecting a delta of 1E-40 probably wouldn't work - it's going to depend on how many significant figures your platform's floating point numbers can represent (the example above would require 80 significant figures, if I'm remembering all this right: 40 in front of the decimal point and 40 after it). You should carefully check out your platform's floating point representation and precision before embarking on adventures in floating point computations.

    This is why many financial calculations in which it was necessary to be precise about exact cents used to be (and probably are still) done in cents rather than in fractional dollars - you can precisely add and subtract integers as long as you have enough digits to represent the amounts you care about.

      Most accounting and telecommunications charging tables that I've worked with were to the fourth decimal place. This wasn't in perl but same applied, we ended up using a math library which used BCD or similar, which produces much better results and rounding functions than floating point. But that's probably beside the point. You can also create an "artificial" loop variable that counts in integers instead of decimals..since you know the number of steps.
      the hardest line to type correctly is: stty erase ^H
Re^2: Floating Point Looping In Perl
by ikegami (Patriarch) on Aug 16, 2010 at 07:06 UTC
    That will only help if the rounding error make the number slightly larger. It doesn't help if the rounding error makes the number slightly smaller, and that does happen. It's not a good solution.