[Numpy-discussion] Find n closest values

Benjamin Root ben.root at ou.edu
Sun Jun 22 12:35:51 EDT 2014


I would echo KDTree, but one way I think you can simplify the existing code
you have is to shift the values of L by half the spacing, then you
shouldn't need the check for left and right values.

Cheers!
Ben Root


On Sun, Jun 22, 2014 at 4:22 AM, Nicolas P. Rougier <
Nicolas.Rougier at inria.fr> wrote:

>
>
> Hi,
>
> I have an array L with regular spaced values between 0 and width.
> I have a (sorted) array I with irregular spaced values between 0 and width.
>
> I would like to find the closest value in I for any value in L.
>
> Currently, I'm using the following script but I wonder if I missed an
> obvious (and faster) solution:
>
>
> import numpy as np
>
> def find_closest(A, target):
>     idx = A.searchsorted(target)
>     idx = np.clip(idx, 1, len(A) - 1)
>     left = A[idx - 1]
>     right = A[idx]
>     idx -= target - left < right - target
>     return idx
>
> n, width = 256, 100.0
>
> # 10 random sorted values in [0,width]
> I = np.sort(np.random.randint(0,width,10))
>
> # n regular spaced values in [0,width]
> L = np.linspace(0, width, n)
>
> print I[find_closest(I,L)]
>
>
>
> Nicolas
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140622/43fac5a7/attachment.html>


More information about the NumPy-Discussion mailing list