Rounding Bug in Python 2.0! - ugh

Tim Peters tim_one at email.msn.com
Tue Oct 31 21:48:01 EST 2000


[Gordon Williams]
> When I switched from python 1.5.2 to 2.0 final I had a surprise
> in some code that was working previously.
>
> It comes down to:
> >>> x=3.8999999999999999
> >>> round(x,3)
> 3.8999999999999999
> >>>
>
> >>> x=3.123456
> >>> round(x,3)
> 3.1230000000000002
>
> Someone is going to start talking about machine round off
> errors, but this is a BIG UGH!!

As Thomas said, nothing changed here except the precision to which the
interactive prompt *displays* floats.  Note also:

>>> 3.123
3.1230000000000002
>>> 3.9
3.8999999999999999
>>>

That is, these numbers aren't exactly representable in binary
floating-point, and never were, and "round" has nothing to do with it (well,
not with *these* examples; the builtin "round" is sloppier than it should
be, but these examples don't show that).

If your machine had 5-bit floating-point, the best approximation to 3.123
would be 3.125 (3 + 1/8); if 4-bit floating-point, 3.0; that "the junk"
shows up "so far to the right" is just a consequence of your machine having
53-bit floating-point.  If it had 1000000-bit floating-point, these numbers
still wouldn't be exactly representable (to be exactly representable in
binary floating-point, it's necessary that a number be of the form I/2**n
for some integers I and n; but "most" decimal fractions cannot be put in
that form).

[Thomas Wouters]
> Gosh-now-I-know-what-Tim-must-feel-like-when-people-ask-him-about-FP-ly
> 	y'rs, ;)

You may yet achieve those depths of depression, but not for about 20 years
<0.75 wink>.

still-if-god-had-meant-us-to-use-integers-he-wouldn't-have-given-us-
    irrational-brains-ly y'rs  - tim






More information about the Python-list mailing list