Array and floating point

Zentrader zentraders at gmail.com
Fri Aug 17 23:20:21 CEST 2007


On Aug 17, 2:06 pm, Jonathan Shan <jons... at winlab.rutgers.edu> 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
>
> Thanks
> Jonathan Shan

Floating point precision problems on x86 type machines is well
documented on the web if you want to know more about it.  For your
example use Python's decimal class instead of floating point.  Gmpy is
also available for scientific type apps,
http://docs.python.org/lib/module-decimal.html
http://pydoc.org/2.4.1/decimal.html
http://gmpy.sourceforge.net/
import decimal
x = decimal.Decimal( "0.1" )
print x
y = decimal.Decimal( "0.10000000000000001" )
print y
print y/x
print y*x




More information about the Python-list mailing list