[Doc-SIG] RE: [Python-Dev] Feedback on new floating point info in tutorial

Tim Peters tim.one@home.com
Mon, 11 Jun 2001 22:17:24 -0400


[Skip Montanaro, on the in-progess 2.2 Tutorial appendix]
> I took a quick look at that appendix.  One thing that confused me
> a bit was that if 0.1 is approximated by something ever-so-slightly
> larger than 0.1, how is it that if you add ten of them together you
> wind up with a result that is ever-so-slightly less than 1.0?

Good for you, Skip!  In all the years I've been explaining this stuff, I
only recall one other picking up on that immediately.  I'm not writing a
book here, though <wink>, and any intro numeric programming text emphasizes
that n*x is a better bet than adding x together n times.

>>> .1 * 10
1.0
>>>

Greg Ewing put you on the right track, if you want to figure it out yourself
(as Deep Throat said, "follow the bits, Skip -- follow the bits").

> I didn't expect it to be exactly 1.0.  Other floating point naifs
> may be confused in the same way:
>
>     >>> "%.55f" % 0.5
>     '0.5000000000000000000000000000000000000000000000000000000'
>     >>> "%.55f" % 0.1
>     '0.1000000000000000055511151231257827021181583404541015625'
>     >>> "%.55f" % (0.5+0.1)
>     '0.5999999999999999777955395074968691915273666381835937500'

Note that this output is platform-dependent.  For example, the last on
Windows is

>>> "%.55f" % (0.5+0.1)
'0.5999999999999999800000000000000000000000000000000000000'

> ...
> IEEE-754-is-full-of-traps-for-the-unwary-ly y'rs,

All computer arithmetic is; and among binary fp systems, 754 has got to be
the best-behaved there is.  Know how many irksome bugs I've fixed in Python
mucking with different sizes of integers across platforms, and what C does
and doesn't guarantee about them?  About 20x more than fp bugs.  Of course
there's 10000x as much integer code in Python too <wink>.

god-created-the-integers-from-1-through-3-inclusive-and-that's-it-ly
    y'rs  - tim