Floating point multiplication in python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Sep 6 03:11:10 EDT 2011


On Tue, 6 Sep 2011 03:57 pm xyz wrote:

> hi all:
> 
> As we know ,  1.1 * 1.1 is 1.21 .
> But in python ,I got following :
> 
>>>> 1.1 * 1.1
> 1.2100000000000002


The problem is that 1.1 is a *decimal* number, but computers use *binary*,
and it is impossible to express 1.1 exactly as a binary number. So when you
type 1.1 into nearly all computer languages, what you are actually getting
is a tiny bit more than 1.1:

>>> repr(1.1)
'1.1000000000000001'


which is the closest number to 1.1 that is possible using a C double
floating point number.

Normally you don't see it, because Python truncates the result when
printing:

>>> str(1.1)
'1.1'

but the difference is there.


-- 
Steven




More information about the Python-list mailing list