Array and floating point

Peter Otten __peter__ at web.de
Fri Aug 17 17:21:43 EDT 2007


Jonathan Shan wrote:

> Hello,
> 
> I'm experiencing a problem where the float being appended to the array
> is not the same as the result of the appending.
> 
>>>> from array import *
>>>> x = array('f')
>>>> x.append(float("0.1"))
>>>> x[0]
> 0.10000000149011612
>>>> float("0.1")
> 0.10000000000000001
> 
> I'm expecting x[0] = 0.10000000000000001

array("f") is an array of C floats while Python's float type is a double in
C terms. That's why you lose some precision. Try array("d") instead:

>>> from array import array
>>> x = array("d")
>>> x.append(0.1)
>>> x[0]
0.10000000000000001


Peter



More information about the Python-list mailing list