Gabriel
Gabriel

Reputation: 42389

Check array for values equal or very close to zero

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?

Upvotes: 8

Views: 13480

Answers (3)

seberg
seberg

Reputation: 8975

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.

Upvotes: 0

abarnert
abarnert

Reputation: 365925

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)

Upvotes: 10

fabmilo
fabmilo

Reputation: 48330

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

Upvotes: 2

Related Questions