Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Why do floating point numeric equality/inequality tests fail mysteriously?

( #403957=categorized question: print w/ replies, xml ) Need Help??
Contributed by itub on Oct 30, 2004 at 02:49 UTC
Q&A  > numbers


Rule #1 of floating-point computing in any language, not just Perl: Never compare two floating-point numbers with == or != (or expect >= et al. to work in the edge cases). Use a tolerance range instead.

The reason for this is that floating-point numbers are represented internally as a binary approximation. A consequence of that is that calculations that would be exact in decimal notation are not exact in binary. For example, a simple test like 36.6 + 0.2 == 36.8 may be return false! The same test could be done safely like this:

$TOL = 1E-8; # or a sufficiently small number if (abs((36.6 + 0.2) - 38.2) < $TOL) { print "They are (almost) equal!\n"; }

This topic is covered in greater depth in the Q&A math section, under the title of : My floating point comparison does not work. Why ?. Please post any further answers there.

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others imbibing at the Monastery: (16)
    As of 2014-08-27 16:23 GMT
    Find Nodes?
      Voting Booth?

      The best computer themed movie is:

      Results (244 votes), past polls