crazunggoy47 crazunggoy47 -4 years ago 154
Python Question

element in array in numpy

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

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download