123.3 + 0.1 is 123.3999999999 ?

Erik Max Francis max at alcyone.com
Fri May 16 02:14:14 EDT 2003


A Puzzled User wrote:

> I suppose there is no situation that the inaccuracy
> can cause such obvious bugs?  I just wonder why the
> interactive command line gives us 12.949999999 while
> print [12.95]    will give us 12.95.... why doesn't the
> command line lie also?

It's str vs. repr:

>>> x = 0.1
>>> str(x)
'0.1'
>>> repr(x)
'0.10000000000000001'
>>> x
0.10000000000000001

In the interactive interpreter, it prints the repr of the value of an
expression.  In this case, str gives a reasonable string representation
of the value, but repr is tasked to give the most accurate
representation possible.

Regrettably, both the str and repr of containers include the repr of
their contents, resulting in the somewhat confusing:

>>> l = [0.1, 0.2, 0.3] # these can't be expressed exactly
>>> str(l)
'[0.10000000000000001, 0.20000000000000001, 0.29999999999999999]'
>>> repr(l)
'[0.10000000000000001, 0.20000000000000001, 0.29999999999999999]'
>>> '[%s]' % ', '.join(map(str, l))
'[0.1, 0.2, 0.3]'

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Behind an able man there are always other able men.
\__/  (a Chinese proverb)




More information about the Python-list mailing list