Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare `float` and `float64` in python

Tags:

python

numpy

I have to compare two numbers. One of them comes from regulat python code and comes other from numpy. Debugger shows they have same value '29.0', but type of first is float and type of second is float64, so a == b and a - b == 0 is False. How can I deal with it? Is there any way to force a regular python variable to be float64 or numpy use float by default?

Update: In the end of all these values comes from the same file where 29.0 is written, so I don't think there are differences in numeric values.

like image 499
xander27 Avatar asked Aug 07 '13 15:08

xander27


2 Answers

You should not compare floats with equality, in any programming language, because you can never know that they are exactly equal. Instead, you should test whether their difference is smaller than a tolerance:

if abs(a - b) < 1e-10

So this problem doesn't have to do with the difference between float and float64 (Python converts them automatically), but with the fundamental problem of comparing floats for equality.

See also What's wrong with using == to compare floats in Java?

like image 79
Antonis Christofides Avatar answered Oct 22 '22 22:10

Antonis Christofides


If you are using numpy, the best way to do what Antonis has suggested is to use the function np.allclose(a, b). You can also specify the tolerance (1e-10 from above).

like image 37
spencerlyon2 Avatar answered Oct 22 '22 20:10

spencerlyon2