0

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?

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Can you suggest a way to avoid running into this problem?
1

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.

1 Comment

Cool, thanks for the demo. I see now that I can use (b in np.round(a,2)) to get what I need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.