Hi all,

I was debugging a script with which I was having a calculation issue, and traced the problem to some code that does some simple arithmetic. I boiled down the problem to a short test script:
#!/usr/bin/perl use strict; my @a; $a[0] = (0.1 - 0.1) * 10; #Should be 0 $a[1] = (0.2 - 0.1) * 10; #Should be 1 $a[2] = (0.3 - 0.1) * 10; #Should be 2 $a[3] = (0.4 - 0.1) * 10; #Should be 3 $a[4] = (0.5 - 0.1) * 10; #Should be 4 my $i; for( $i = 0; $i < 5; $i++ ) { print "$i: ", $a[$i], " ", int($a[$i]), "\n"; } print "\n"; for( $i = 0; $i < 5; $i++ ) { printf "%d: %s %d %f\n", $i, $a[$i], $a[$i], $a[$i]; }
And here is the output:
0: 0 0 1: 1 1 2: 2 1 * 3: 3 3 4: 4 4 0: 0 0 0.000000 1: 1 1 1.000000 2: 2 1 2.000000 * 3: 3 3 3.000000 4: 4 4 4.000000
On the lines with *s you would expect it to print '2 2' & '2 2 2.000000', but instead it prints '1's. I tested both 'print' & 'printf' here to see if it was an issue with one of those functions alone, or perhaps the data type the $a[]'s were assumed to be. This only seems to happen for the calculation of
$a[2] = (0.3 - 0.1) * 10;
(perhaps there are other instances). So it seems like $a[2] is not equal to int($a[2]), though they should be the same.

Does anyone know why this happens?

Please forgive if this is a known phenomenon. I'm not sure how to do a search for this type of problem.

BTW, I tested in Windows XP (Perl 5.8.7), OS X 10.4 (Perl 5.8.6), AIX (Perl 5.6.1), & Ubuntu (Perl 5.10.0) -- all the same result.

TIA

In reply to An arithmetic oddity by jxb

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.