Weird result returned from adding floats depending on order I add them

Miki miki.tebeka at gmail.com
Wed Feb 21 12:52:11 EST 2007


Hello Joanne,

> ... [float problem] ...
> I get True returned. Can anyone tell me whats going on and how I can
> avoid the problem. Thanks

If you want to be truly accurate, you can use gmpy.mpq (http://
gmpy.sourceforge.net/).
>>> a = [0.2, 0.2, 0.2, 0.1, 0.2, 0.1]
>>> b = [0.2, 0.2, 0.2, 0.2, 0.1, 0.1]
>>> qa = [gmpy.mpq(int(i * 10), 10) for i in a]
>>> qb = [gmpy.mpq(int(i * 10), 10) for i in b]
>>> sum(qa)
mpq(1)
>>> sum(qb)
mpq(1)
>>> sum(qa) == sum(qb)
True

HTH,
--
Miki <miki.tebeka at gmail.com>
http://pythonwise.blogspot.com




More information about the Python-list mailing list