I have a 1D Numpy array A of length N. For each element x in the array, I want to know what proportion of all elements in the array are within the range [x-eps; x+eps], where eps is a constant. N is in the order of 15,000.
At present I do it as follows (minimal example):
import numpy as np
N = 15000
eps = 0.01
A = np.random.rand(N, 1)
prop = np.array([np.mean((A >= x - eps) & (A <= x + eps)) for x in A])
.. which takes around 1 sec on my computer.
My question: is there a more efficient way of doing this?
Edit: I think @jdehesa suggestion in the comments would work as follows:
prop = np.isclose(A, A.T, atol=eps, rtol=0).mean(axis=1)
It's a nice concise solution, but without a speed advantage (on my computer).