Ah. The old decimal fraction in binary floating point malarkey.

The reason for prefering to hold currency as, say, pennies or cents is that it ensures that the value is exact. If you hold the pennies or cents as a fraction in binary floating point, it is unlikely to be exact.

For example, when decimal 1.51 is converted to a binary fraction the result is:

  1.1000_0010_1000_1111_0101_1100_0010_1000_1111_0101_1100_0010_1000_1111_0101_1100_0010_1000_1111_0101...
which you can see is a repeating binary fraction, some part of which will be rounded off.

Most decimal fractions are like this... so before any errors can be introduced by rounding and what not in any arithmetic you go on to do, most decimal fractions have a built-in "representation" error.

Much of the time you won't see the "representation" error, because conversion back to decimal rounds it off. This can lead to bafflement when two values look the same when printed out, but fail  $x == $y.

Addition and subtraction are the more difficult floating point operations, so you're more likely to see the problems there. Consider:

print 1.09 - 1, "\n" ; print "0.84 - 0.34 == ", 0.84 - 0.34, ( 0.84 - 0.34 == 0.5 ? " ==" : " but !=" ), " 0.5\n" ;
which gives:
  0.0900000000000001
  0.84 - 0.34 == 0.5 but != 0.5
it really makes me wonder why we persist in using binary floating point for decimal arithmetic !


In reply to Re^3: Getting different results with $var++ and $var += 1 by gone2015
in thread Getting different results with $var++ and $var += 1 by splicer

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.