Weird arithmetic in Python

Peter Hansen peter at engcorp.com
Sun Oct 29 20:20:00 EST 2000


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

Actually, both of the above values *are* zero.  But then, I'm an
engineer...  ;-)

"Squeezing infinitely many real numbers into a finite number of bits
requires an approximate representation. Although there are infinitely
many integers, in most programs the result of integer computations can
be stored in 32 bits. In contrast, given any fixed number of bits, most
calculations with real numbers will produce quantities that cannot be
exactly represented using that many bits. Therefore the result of a
floating-point calculation must often be rounded in order to fit back
into its finite representation. This rounding error is the
characteristic feature of floating-point computation." 
--http://docs.sun.com/htmlcoll/coll.648.2/iso-8859-1/NUMCOMPGD/ncg_goldberg.html

-- 
Peter Hansen



More information about the Python-list mailing list