[Numpy-discussion] floating point arithmetic issue

David david@silveregg.co...
Fri Jul 30 05:52:37 CDT 2010


Hi Guillaume,

On 07/30/2010 07:45 PM, Guillaume Chérel wrote:
>    Hello,
>
> I ran into a difficulty with floating point arithmetic in python.

This is not python specific, but true in any language which uses the 
floating point unit of your hardware, assuming you have "conventional" 
hardware.

> 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...

Indeed, it is not, and that's expected. There are various pitfalls using 
floating point. Rational and explanations:

http://docs.sun.com/source/806-3568/ncg_goldberg.html

> Is there any way to solve this?

Using % with float is generally a wrong idea IMO. You have not said what 
you are trying to do. The solution may be to use integers, or to do it 
differently, but we need more info,

cheers,

David


More information about the NumPy-Discussion mailing list