Nearest point to a set of points

Python

Nearest neighbor search

 1|  import numpy as np
 2|  
 3|  POINTS = [[0.4878536768447066,
 4|    0.869456188424337,
 5|    0.5011068612999854,
 6|    1.0133445679243316,
 7|    0.8148628393772428],
 8|   [-1.9546441319243815,
 9|    4.203616681164113,
10|    -1.2296409861901172,
11|    -0.7524776363348679,
12|    0.7636937144300029],
13|   [-0.8312390019196739,
14|    -1.7188556451950765,
15|    1.296113631342589,
16|    -0.1920154915288227,
17|    -0.23289363410028704],
18|   [0.0812036270933463,
19|    0.3691611770903292,
20|    -0.25254671963123604,
21|    -0.698690361395649,
22|    0.7184178853051904],
23|   [1.0719775045458273,
24|    -0.9585189675423648,
25|    -0.6868941871154016,
26|    0.2951448085864521,
27|    -0.40818130509087],
28|   [0.6189255807478202,
29|    -1.628248909022074,
30|    -0.3870923080270297,
31|    1.0238007396805155,
32|    -0.43619087044715915],
33|   [0.6469704980278533,
34|    -0.5510403453068279,
35|    0.57974527600909,
36|    -0.18227673639249417,
37|    2.431419898529448],
38|   [-1.2527653438077144,
39|    -0.04096672475177045,
40|    0.6979648406646776,
41|    -0.06805987269966886,
42|    -0.38933102408171466],
43|   [-0.8047882379332667,
44|    0.3906445194669081,
45|    -0.15367552112839183,
46|    0.8627565512188639,
47|    -0.5468546042030066],
48|   [0.6579256363881655,
49|    0.08540398264794942,
50|    -0.3685160479312876,
51|    -2.2590117617618795,
52|    -1.0637405525056955]]
53|  
54|  
55|  QUERY =[0.6784155, 0.21687017, 1.01940089, 3.07288809, -1.16329905]
56|  
57|  
58|  
59|  
60|  def closest_point):
61|  """
62|  :param query: An n-dimensional point represented as a list of floats.
63|  :param points: A list of n-dimensional points where each point is a list of floats.
64|  :return: The index of the closest point in the `points` list.
65|  """
66|  
67|  
68|  p = np.array(POINTS)
69|  q = np.array(QUERY)
70|  
71|  arr = np.array(np.linalg.norm(p-q, axis=1))
72|  return np.argmin(arr))
73|  
74|  
75|  """
76|  3 additional slightly different ways:
77|  
78|  dist_2 = np.sum((p-q)**2, axis=1)
79|  return np.argmin(dist_2)
80|  
81|  return np.argmin(np.sqrt(np.square(p - q).sum(axis=1)))
82|  
83|  
84|  return np.array(np.linalg.norm(p-q, axis=-1)).argmin()
85|  
86|  """
Did you find this snippet useful?

Sign up for free to to add this to your code library