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.
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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With