http://www.perlmonks.org?node_id=989020

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

Hi, I want to create a simple output ranging from 0 to zmax in distinct steps. Those steps shall get larger towards the end. Here's my simple script:
my $zmax = 60; # Maximum depth in your model my $dz = 0.05; # Grid spacing in z-direction for (my $i=0; $i <= $zmax; $i = $i+$dz) { print $i."\n"; }
And here's the output at a later stage:
3.6 3.65 3.69999999999999 3.74999999999999
That's not the correct value !! This prevents me from making a direct comparison with an integer number (which I can find ways around), but the result is simply wrong!! What's happening there?

Replies are listed 'Best First'.
Re: Wrong calculations in for loop
by toolic (Bishop) on Aug 22, 2012 at 13:02 UTC
Re: Wrong calculations in for loop
by MidLifeXis (Monsignor) on Aug 22, 2012 at 13:01 UTC
Re: Wrong calculations in for loop
by BrowserUk (Patriarch) on Aug 22, 2012 at 13:50 UTC

    Simple solution:

    for( my $i = 0; $i < 6000; $i += 5 ) { say $i / 100 };; 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 ... 3.5 3.55 3.6 3.65 3.7 3.75 3.8 3.85 3.9 3.95 4 ...

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

Re: Wrong calculations in for loop
by moritz (Cardinal) on Aug 22, 2012 at 13:10 UTC

    Luckily you can run the script with only very small changes under Perl 6, and it produces the output you expect:

    use v6; my $zmax = 60; # Maximum depth in your model my $dz = 0.05; # Grid spacing in z-direction loop (my $i=0; $i <= $zmax; $i = $i+$dz) { say $i; }

    produces

    ... 3.6 3.65 3.7 3.75 ... 59.9 59.95 60

    It accomplishes that magic by doing math with rationals (stored as integer numerator and denominator) by default.

      OK, but getting the same result in Perl 5 is almost as easy:

      #! perl use strict; use warnings; my $zmax = 60; # Maximum depth in your model my $dz = 0.05; # Grid spacing in z-direction print +($_ * $dz), "\n" for (0 .. int(($zmax / 0.05) + 0.5));

      :-)

      Athanasius <°(((><contra mundum

        Or even simpler, just change the print to printf

        my $zmax = 60; # Maximum depth in your model my $dz = 0.05; # Grid spacing in z-direction for (my $i=0; $i <= $zmax; $i = $i+$dz) { printf("%.2f\n", $i); }

Re: Wrong calculations in for loop
by Anonymous Monk on Aug 22, 2012 at 13:08 UTC