pythonarraysperformancenumpy

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?


Solution

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