123.3 + 0.1 is 123.3999999999 ?

Fredrik Lundh fredrik at pythonware.com
Thu May 15 12:38:10 EDT 2003


"An Anonymous Coward" wrote:

> In Python 2.2.2
>
>  >>> float("123.4")+0.1
> 123.5
>
>  >>> float("123.3")+0.1
> 123.39999999999999
>
>  >>> float("123.1") + 1
> 124.09999999999999
>
> how come there are these inaccuracies?

It's the way binary floating point numbers work (if you're going
to squeeze an infinite range of numbers into a limited number of
bits, you have to cheat).

The Python tutorial has the full story:

http://www.python.org/doc/current/tut/node14.html

> I just tried in Perl
>
>    print eval("123.3") + 0.1;
>
> and it gives
> 123.4

Perl lies.  So does Python, if you ask it to:

>>> print eval("123.3") + 0.1
123.4
>>> print float("123.3") + 0.1
123.4

</F>








More information about the Python-list mailing list