![](/img/trans.png)
[英]How to find closest point of LineString to a coordinate in python
[英]Python: closest coordinate?
我需要一個函數的幫助,該函數從坐標列表中返回坐標,該坐標列表最接近某個點。 例如: closest((9, 2), {(0, 0), (10, 0), (10, 10)}) returns (10, 0)
。
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def closest(self,*points):
return min(points,key=lambda x:abs(x-self))
def __sub__(self,other):
return Point((self.x-other.x) , (self.y - other.y))
def __pow__(self,powTo):
return Point(self.x**powTo,self.y**powTo)
def __iter__(self):
yield self.x
yield self.y
def __abs__(self):
return sum(self**2)**0.5
def __str__(self):
return "(%s,%s)"%(self.x,self.y)
pt0 = Point(9,2)
print pt0.closest(Point(0,0),Point(10,0),Point(10,10))
是你可以做到的一種方式;)
一種稍微簡單的方法(假設你已經編寫了你的dist方法)
def closest(p0,otherPoints):
def distTo(p):
def _inner(other):
return dist(p,other)
return inner
return min(otherPoints,key=distTo(p0))
甚至更簡單
def closest(p0,otherPoints):
return min(otherPoints,key=lambda x:dist(p0,x))
from math import sqrt
def euqli_dist(p, q, squared=False):
# Calculates the euclidean distance, the "ordinary" distance between two
# points
#
# The standard Euclidean distance can be squared in order to place
# progressively greater weight on objects that are farther apart. This
# frequently used in optimization problems in which distances only have
# to be compared.
if squared:
return ((p[0] - q[0]) ** 2) + ((p[1] - q[1]) ** 2)
else:
return sqrt(((p[0] - q[0]) ** 2) + ((p[1] - q[1]) ** 2))
def closest(cur_pos, positions):
low_dist = float('inf')
closest_pos = None
for pos in positions:
dist = euqli_dist(cur_pos,pos)
if dist < low_dist:
low_dist = dist
closest_pos = pos
return closest_pos
print closest((9, 2), {(0, 0), (10, 0), (10, 10)})
輸出:
(10, 0)
如果我的數學沒有錯。 ;)
我正在使用這個公式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.