123.4+2=125.40000000000001

Konrad Hinsen hinsen at cnrs-orleans.fr
Wed Jun 21 09:12:12 EDT 2000


Peter Koppatz <pkop at brb.midat.de> writes:

> >>> 123.4+2
> 125.40000000000001   # is this OK?
> >>> print 123.4+2
> 125.4
> >>>
> 
> On my calculator: 123.4+2 = 125.4 !?

Because your calculator works with a decimal representation of
numbers, whereas Python (and the vast majority of other programming
languages) uses a binary representation. In binary, the result of your
calculation has an infinite number of digits (like 1./3. has in
decimal) and cannot be represented exactly in a computer. That causes
the effect you observe.
-- 
-------------------------------------------------------------------------------
Konrad Hinsen                            | E-Mail: hinsen at cnrs-orleans.fr
Centre de Biophysique Moleculaire (CNRS) | Tel.: +33-2.38.25.55.69
Rue Charles Sadron                       | Fax:  +33-2.38.63.15.17
45071 Orleans Cedex 2                    | Deutsch/Esperanto/English/
France                                   | Nederlands/Francais
-------------------------------------------------------------------------------



More information about the Python-list mailing list