Here's an important fact about "floating point" numbers as stored in a computer: they are not true decimal numbers, because computers can only store binary values. That means floats can only accurately represent a number that is an inverse power of two, eg, 1/2, 1/4, 1/8, 1/16 and so on. Notice that does not include 1/10, aka 0.1. You can observe this on your system using perl:

for (my $i = 0; $i<30; $i += 0.1) { print "$i "; }

If you run that, you will notice frequently the numbers ARE NOT an even multiple of 0.1, eg, with 32 bit floats you get "5.9 5.99999999999999 6.09999999999999 6.19999999999999" "22.5 22.6000000000001 22.7000000000001 22.8000000000001", etc. In fact, they are NEVER an even multiple of 0.1, but this is not always clear since there is also a limit to the number of "decimal" places when the number is rendered in non-binary form.

This is not just a perl issue, and there are notorious legends of accounting software disasters because of it; it's why when you are programming applications involving dollars and cents and division, always:

use integer;

Then use cents, not dollars, and remember, this is rounded down -- if you want to include fractions of a cent, decide how many decimal places you need and use that fraction as a base unit. Money is not a floating point measure. It is of fixed precision.


In reply to Re: Numeric Comparisons Randomly Giving the Wrong Result by halfcountplus
in thread Numeric Comparisons Randomly Giving the Wrong Result by Likeless

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.