[Numpy-discussion] floating point arithmetic issue

Ken Watford kwatford+scipy@gmail....
Fri Jul 30 10:42:14 CDT 2010


2010/7/30 Guillaume Chérel <guillaume.c.cherel@gmail.com>:
>  Hello,
>
> I ran into a difficulty with floating point arithmetic in python. Namely
> that:
>
>  >>> 0.001 + 1 - 1
> 0.00099999999999988987
>
> And, as a consequence, in python:
>
>  >>> 0.001 + 1 - 1 == 0.001
> False
>
> In more details, my problem is that I have a fonction which needs to
> compute (a + b - c) % a. And for b == c, you would expect the result to
> be 0 whatever the value of a. But it isn't...
>
>  >>> (0.001 + 1 - 1) % 0.001
> 0.00099999999999988987
>
> Is there any way to solve this?

You can do slightly better than normal floating point arithmetic using
some special algorithms that compensate in one way or another for the
error. See math.fsum:
http://docs.python.org/library/math.html#math.fsum

>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
>>> fsum([0.001, +1, -1])
0.001

It won't be as fast, and naturally it won't always work, but it's something.


More information about the NumPy-Discussion mailing list