123.3 + 0.1 is 123.4 if using a variable

Erik Max Francis max at alcyone.com
Mon Jun 2 23:27:06 EDT 2003


"D.W." wrote:

> Evidently, python has different rules for numbers entered in
> interactive mode.  Try this little snippet or just using a float
> variable.  It works both as a program and in interactive mode.

It's because the interactive interpreter displays the repr of the value,
whereas print displays the str of it:

>>> x = 123.3
>>> y = x + 0.1
>>> str(y)
'123.4'
>>> repr(y)
'123.39999999999999'
>>> print y # this does the str
123.4
>>> y # this does the repr
123.39999999999999

It's not that Python handles the arithmetic differently, it's just that
it has trivially different ways of converting the numbers to strings for
display.  Unfortunately, this difference causes a great deal of
confusion.

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Success and failure are equally disastrous.
\__/  Tennessee Williams




More information about the Python-list mailing list