Weird arithmetic in Python

John W. Baxter jwbnews at scandaroon.com
Sun Oct 29 22:40:39 EST 2000


In article <8ti8ul$7ca$1 at nnrp1.deja.com>, yminsky at cs.cornell.edu wrote:

> Can anyone explain the following behavior of Python?  I understand that
> floating point arithmetic is not identical to real arithmetic, but this
> seems a bit odd.
> 
> Python 1.5.2 (#1, Aug 25 2000, 09:33:37)  [GCC 2.96 20000731
> (experimental)] on linux-i386
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>> .1 * 2 - .2
> 0.0
> >>> .1 * 3 - .3
> 5.55111512313e-17
> >>>
> 
> Yaron Minsky

Python before 2.0 (or maybe before 1.6) lied to us.  It gave results like
>>> .1
0.1

That isn't true (it has been rounded)...on the processors you (Intel) 
and I (PowerPC and Intel) are dealing with, the truth is more like what 
Python 2.0 presents (PowerPC, since my Intel laptop isn't on at the 
moment ):

>>> .1
0.10000000000000001
>>> .3
0.29999999999999999
>>> 
>>> .1 * 3
0.30000000000000004

You can force that output representation in Python 1.5.2 (Intel):
>>> "%.17f" % .1
'0.10000000000000001'
>>> "%.17f" % .3    
'0.29999999999999999'
>>> "%.17f" % (.1*3,)
'0.30000000000000004'

(Parens required on that last one because of operator precedence:  the 
result without the () and the , may surprise.)

Now it should be fairly clear why the result of subtracting the two 
values is non-zero.

Essentially, any code which expects a zero result from arbitrary 
floating point calculations is suspect, and most of it is wrong.  
"Absolute value less than 'very small'" is the more useful test, where 
there is some art to defining 'very small.'

This differs from the 1950s, when the result of careless floating point 
calculations might well be zero, when the answer "obviously" was far 
from zero.

  --John  (not surprised to see the question, but a little surprised to 
see the question coming out of Computer Science at Cornell, from someone 
named Minsky <the Minsky I remember was Marvin>...but it probably won't 
happen again.)

-- 
John W. Baxter   Port Ludlow, WA USA  jwbnews at scandaroon.com



More information about the Python-list mailing list