views:

95

answers:

3

What is the fastes way of determening which point q out of n points in 2D space is the closest (smallest euclidian distance) to point p, see attached imgage.

alt text

My current method of doing this in Python is storing all the distances in a list and then running

numpy.argmin(list_of_distances)

This is however a bit slow when calculating this for m number of points p. Or is it?

+2  A: 

This falls under closest point query -problems.

How many points are expected? Are your points static or do they change? One naive but powerful approach for static points would be to pre-compute every known distance, which would result in O(1) lookup.

randomguy
@randomguy - Ah. Thank you. n is normaly only around 10 but m can range in the thousands. However, the distrubution of q i liklely to change with every iteration. "Precompute every known distance", does this apply to floating point numbers?
Theodor
+3  A: 

Instead of calculating the distances, you could calculate the squared distances. That way you don't need to perform n * m square roots.

Jackson Pope
@Jackson - Good point, you still keep the relative order of distances.
Theodor
Old games programmer's cheat :)
Jackson Pope
+1  A: 

Put everything as soon as possible into numpy and do calculations there. If you have many points, it is much faster than calculating distances in lists:

import numpy as np

px, py
x = np.fromiter(point.x for point in points, dtype = np.float)
y = np.fromiter(point.y for point in points, dtype = np.float)

i_closest = np.argmin((x - px) ** 2 + (y - py) ** 2)
eumiro