Observe the output of the following code:

printf "%2.15f", 44123.200/959.2;

The output, due to rounding errors inherent in any system where base 10 floating point numbers are converted to base 2 for arithmetic work, and then converted back to base 10 for display, is "45.999999999999993".

Unless you tell it to do otherwise (as I have done with printf, Perl, like most languages rounds that to 46 for display purposes (I can't remember the number of decimal digits Perl will display before rounding). But int does something entirely different from rounding; it simply drops everything after the decimal point. So 45.9999999999999993 gets truncated by int to 45, while printing 45.99999999999993 gets rounded up to 46.

I first encountered this fact of life back in my first high school Computer Science course in 1983 or so, taught on Apple II+ computers with some sort of Apple floating point BASIC. But it existed long before 1983, and will continue to exist as long as we use a finite number of base-2 digits to internally represent (and perform operations on) floating point base-10 numbers.


Dave


In reply to Re: Why do these produce different values? by davido
in thread Why do these produce different values? by mr.nick

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.