Recipe 2.2 in the Perl Cookbook, Second Edition is excellent reading on this subject.

Basically, when you use a floating point number, such as 36.6, the computer doesn't store that exact value. Remember, computers are binary. When you get down to it, there's nothing more than transistors. The memory storage only really works well for integers. So the computer has to figure out some way to store approximations of the number.

To paraphrase the cookbook, the only numbers well-representable in binary are those involving powers of two. For example, .125 is 1/8. That's exactly representable in binary notation of floating point numbers.

However, take a number like 36.6. In fractional form, it would be 183/5, nothing to do with powers of two. The way the computer really stores the number can be seen:

my $a = 36.6; printf "%s is %.30g\n", ($_) x 3 for $a;
(Code shamelessly copied from the Perl Cookbook.)

That gives us 36.600000000000001. Similarly, 36.8 is given as 36.799999999999997.

So now you see why the comparisons failed. You weren't working with exact values.

Perl's (and indeed, the C library's) rounding function are not exactly ``round up at five,'' but actually ``round towards even.'' So that way, sprintf will round 36.6 to an even 36.6 for calculating. So now, numerical comparisons work with nice and even numbers.

Take a look at the Perl Cookbook on this one. It's a very good read. I've just summarised what it has written very well.


In reply to Re^3: float values and operators by mpeg4codec
in thread float values and operators by soulchild

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.