8

I have a one dimensional numpy array for which I need to find out if any value is zero or very close to it. With this line I can check for zeros rapidly:

if 0. in my_array:
    # do something

but I also have very small elements like 1.e-22 which I would also like to treat as zeros (otherwise I get a Divide by zero warning further down the road)

Say my threshold is 1.e-6 and I want to efficiently check if any value in my array is smaller than that. How can I do this?

0

4 Answers 4

10

There's no reason to loop in Python; just broadcast the abs and the < and use np.any:

np.any(np.absolute(my_array) < eps)
Sign up to request clarification or add additional context in comments.

Comments

2

If you are using this for testing you can use numpy.testing.assert_almost_equal

As the document says it uses a method similar to @phihag suggests:

any(abs(x) < 0.5 * 10**(-decimal))

Comments

0

If you are doing this often, you should try to use searchsorted, or if you have scipy KDTree (or cKDTree depending on the version), to speed things up.

Comments

0

Consider using

math.isclose()

Absolute and relative tolerance are configurable.

Comments

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.