indigoviolet has asked for the wisdom of the Perl Monks concerning the following question:

Why does this happen? Is there a workaround, apart from doing things like printf?
#!/usr/bin/perl use strict; use warnings; my $begin = 5; my $end = 7; my $step = 0.1; for (my $i = $begin ; $i <= $end; $i += $step ) { print $i, "\n"; } __END__ # -- OUTPUT -- \ 5 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 6 6.1 6.2 6.3 6.4 6.49999999999999 6.59999999999999 6.69999999999999 6.79999999999999 6.89999999999999 6.99999999999999 #------------- # Setting $begin = 6 #------------- 6 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 7 #---------------- I get this imprecise addition effect to different extents for differen +t values of $begin. $> perl -v This is perl, v5.8.2 built for i686-linux
UPDATE: Obviously this question has been answered many times, as clinton and Skeeve mention -- here's where it led me: http://perldoc.perl.org/perlfaq4.html

Replies are listed 'Best First'.
Re: Weird precision issues in float addition
by salva (Canon) on May 30, 2007 at 10:23 UTC
    Well, you are acumulating rounding errors on every iteration.

    Using a multiplication to calculate the current value from the beginning every time would probably improve the situation, though not solve it completely as 0.1 can not be represented as a floating point value.

    for(my $i = 0; ; $i++) { my $v = $begin + $step * $i; last if $v > $end; print "$v\n"; }
Re: Weird precision issues in float addition
by Skeeve (Parson) on May 30, 2007 at 09:13 UTC

    The usual rounding errors.

    if you just need 1 decimal place, why not scale it all up by 10?


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Weird precision issues in float addition
by clinton (Priest) on May 30, 2007 at 09:13 UTC
      Do a super search for 'float' and you'll find that you're not the first person with this question

      Not only is this true, but even without coming to The Monastery, it's a Perl FAQ: perldoc -q decimals.