$ cat a.c #include <stdio.h> int main() { printf("%s\n", 5056.45 + 10112.92 == 15169.37 ? "granted" : "Stop b +laming Perl for your own mistakes!"); return 0; } $ gcc -o a a.c && a Stop blaming Perl for your own mistakes!

45/100, 92/100 and 37/100 are all periodic numbers in binary just like 1/3 is in decimal. It would take infinite storage to store it accurately as a floating point number (regardless of the language). As such, there are tiny differences between the number you specify any the number you actually have

$ perl -e'printf "%.20e\n", $_ for @ARGV' 0.45 0.92 0.37 4.50000000000000011102e-01 9.20000000000000039968e-01 3.69999999999999995559e-01

That's why you must include a tolerance for error when dealing with floating points numbers.

$ perl -le 'print abs(5056.45 + 10112.92 - 15169.37) < 0.0001 ? "as ex +pected" : "perl math sucks!"' as expected $ perl -le 'print sprintf("%.4f", 5056.45 + 10112.92) eq sprintf("%.4f +", 15169.37) ? "as expected" : "perl math sucks!"' as expected

That's 9 digits of precision, and you can even go higher.


In reply to Re: Why does perl math suck? by ikegami
in thread Why does perl math suck? by sharkey

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.