[Numpy-discussion] floating point arithmetic issue

Peter numpy-discussion at maubp.freeserve.co.uk
Fri Jul 30 06:55:45 EDT 2010


2010/7/30 Guillaume Chérel <guillaume.c.cherel at 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?

One simple way is to put brackets round the integer subtraction,

>>> 0.001 + 1 - 1 == 0.001
False
>>> 0.001 + (1 - 1) == 0.001
True

However, in general comparing floating point numbers is tricky
and a complex issue in numerical computing. This is not a
Python or NumPy specific problem ;)

Peter



More information about the NumPy-Discussion mailing list