Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Strictly, it's not because it's floating point, it's because it's binary floating point.

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.

As you say, most decimal fractions are like this... so before any errors can be introduced by rounding and what not, most decimal fractions have a built-in "representation" error.

Most 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^4: How can I calculate the right combination of postage stamps? by gone2015
in thread How can I calculate the right combination of postage stamps? by brian_d_foy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-20 05:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found