123.4+2=125.40000000000001

Adam DePrince deprince at sprynet.com
Sat Jul 8 21:53:00 EDT 2000


Konrad Hinsen wrote:
> 
> 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.


Python uses C's "double" type, which on almost all modern machines uses
the IEEE format.  Omiting tons of neat details, IEEE double expresses
values as:

2^n * m/2^53

where m is unsigned between 0 and 2^53-1.

.4 cannot be expressed precisely in the above fraction; in base two .4
is a "repeating becimal"

-- 
Adam DePrince - firstname at lastname dot net, all in lowercase



More information about the Python-list mailing list