Reputation: 42
I can't figure out why (b in a) is returning as False in the following code. When I print a and b, it is clear that a is, in fact, in b.
import numpy as np
a=np.arange(-.5,.5,0.04)
b = 0.46
print 'a=',a
print 'b=',b
print 'b in a:',(b in a)
Can anyone suggest a way to do this check successfully?
Upvotes: 0
Views: 56
Reputation: 15953
Welcome to floats... Look at this:
import numpy as np
a=np.arange(-.5,.5,0.04)
b = 0.46
print('a in b:',(b in a))
False
print('a in b:',(-0.5 in a))
True
print('a in b:',(-0.46 in a))
True
print('a in b:',(-0.42 in a))
False
As you slowly move away from the start of the array the floats no longer are the same at long significant figures, but the computer will still only show up to 2 decimal points.
It's same as saying 0.4400000000000001 == 0.44
, if you round to 2 decimal points it looks like it is, but the computer doesn't recognize it as one of course.
Upvotes: 1
Reputation: 309861
Floating point numbers are very rarely that precise... In other words, you're probably different by a very small number (On the order of 1e-16
) -- but numpy
chooses to represent the numbers the same as strings because most of the time, the extra precision is just noise that obscures the data you actually want to see.
One possible solution to your problem would be to use numpy.isclose
in conjunction with ndarray.any
:
np.isclose(a, b).any()
Upvotes: 4