问题
想象一下我站在机场。给定一对地理坐标,如何有效地确定我站在哪个机场?
输入
- 坐标对
(x,y)
代表我所站的位置。 - 一组坐标对
[(a1,b1), (a2,b2)...]
其中每个坐标对代表一个机场。
期望的输出
一个坐标对 (a,b)
来自代表最近机场的机场坐标对 (x,y)
。
低效的解决方案
这是我解决这个问题的低效尝试。它在机场集的长度上显然是线性的。
shortest_distance = None
shortest_distance_coordinates = None
point = (50.776435, -0.146834)
for airport in airports:
distance = compute_distance(point, airport)
if distance < shortest_distance or shortest_distance is None:
shortest_distance = distance
shortest_distance_coordinates = airport
问题
如何改进这个解决方案?这可能涉及根据我们当前所在位置的坐标预先过滤机场列表的某种方式,或者预先按特定顺序对它们进行排序。
原文由 Kieran 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 k 维树:
其中 1.41421356 是查询点与最近邻居之间的距离,1 是邻居的索引。
请参阅: http ://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.query.html#scipy.spatial.KDTree.query