In [2]:
import math
import numpy as np
def closest(pos, points):
x0, y0 = pos
dbest, ibest = None, None
for i, (x, y) in enumerate(points):
d = (x - x0) ** 2 + (y - y0) ** 2
if dbest is None or d < dbest:
dbest, ibest = d, i
return dbest, ibest
ref = .5, .5
points = np.random.rand(10 ** 6, 2)
print(points.ndim)
print(points.shape)
print(points)
%timeit closest(ref, points)
print(closest(ref, points))
In [3]:
def np_closest(pos, points):
x, y = points[:,0], points[:,1]
distances = (x - pos[0]) ** 2 + (y - pos[1]) ** 2
ibest = distances.argmin()
dbest = distances[ibest]
return dbest, ibest
%timeit np_closest(ref, points)
print(np_closest(ref, points))