[Numpy-discussion] Find n closest values

Sebastian Berg sebastian at sipsolutions.net
Sun Jun 22 12:24:55 EDT 2014


On So, 2014-06-22 at 17:16 +0200, Nicolas P. Rougier wrote:
> Thanks for the answer. 
> I was secretly hoping for some kind of hardly-known numpy function that would make things faster auto-magically...
> 

I doubt it is faster, but if you got scipy anyway, using KDTree may be
pretty idiomatic. 

- Sebastian

> 
> Nicolas
> 
> 
> On 22 Jun 2014, at 10:30, Eelco Hoogendoorn <hoogendoorn.eelco at gmail.com> wrote:
> 
> > Perhaps you could simplify some statements, but at least the algorithmic complexity is fine, and everything is vectorized, so I doubt you will get huge gains.
> > 
> > You could take a look at the functions in scipy.spatial, and see how they perform for your problem parameters.
> > 
> > 
> > On Sun, Jun 22, 2014 at 10: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
> > 
> > _______________________________________________
> > NumPy-Discussion mailing list
> > NumPy-Discussion at scipy.org
> > http://mail.scipy.org/mailman/listinfo/numpy-discussion
> 
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
> 

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140622/db2afe04/attachment.sig>


More information about the NumPy-Discussion mailing list