The problem is that 0.001 cannot be exactly stored as a floating-point number, just as you cannot store 1/3 exactly as a decimal number. See What Every Computer Scientist Should Know About Floating-Point Arithmetic for details, or search for floating point here on perlmonks.

A way around is to start $a as 22400, add 1 to it at each iteration, and remember to divide by 1000 in the end before using the result (or never divide by 1000, but use the result in a way that accounts for the additional factor)

Note that Perl 6 solves the problem by storing 0.001 as a rational number by default.

use v6; my $a = 22.400; for (1..43) { $a = $a + 0.001; } print "$a\n";

produces 22.443 as output with Rakudo and Niecza.


In reply to Re: limit of for loop!! by moritz
in thread limit of for loop!! by sagar123

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.