2012-05-12 55 views
0
def findDistance((x1,y1),p) # finds Euclidean distance 

比方說,p是[(0, 0), (1, 0), (0, 1), (1, 1), (0, -1), (-1, 1)]如何計算Python中點和點列表之間的歐幾里德距離?

x1 = 0 

y1 = 0 

可選,您可以定義一個半徑。 默認情況下,半徑爲1。 結果應該只包括那些與radius(x1, y1)的位於點:

findDistance((0, 0), punten) 

[(0,0),(1,0),(0,1),(0,-1)]

+0

當半徑爲1時,你會得到這個結果。 –

+2

[當你嘗試解決這個問題](http://mattgemmell.com/2008/12/08/what-have-you-tried/),解決方案的哪一部分卡住了? – Johnsyweb

回答

8

下面將找到(歐式)(x1, y1)之間的每一個點在p距離:

In [6]: [math.sqrt((x1-x2)**2+(y1-y2)**2) for x2,y2 in p] 
Out[6]: [0.0, 1.0, 1.0, 1.4142135623730951, 1.0, 1.4142135623730951] 

如果你只想躺在從(x1, y1)一定距離內的點,你可以寫:

In [8]: [(x2,y2) for x2,y2 in p if math.sqrt((x1-x2)**2+(y1-y2)**2) <= 1.0] 
Out[8]: [(0, 0), (1, 0), (0, 1), (0, -1)] 

這裏,1.0是所需的半徑。

爲了把它放在一起:

import math 

def filter_points(points, origin, radius=1.0): 
    x1, y1 = origin 
    return [(x2,y2) for x2,y2 in points if math.sqrt((x1-x2)**2+(y1-y2)**2) <= radius] 

p = [(0, 0), (1, 0), (0, 1), (1, 1), (0, -1), (-1, 1)] 
print(filter_points(p, (0, 0), 1.0)) 

注:值得記住四捨五入的問題:非常接近邊界的點可能最終會被誤分類。是否重要,以及如何最好地處理這取決於你打算如何處理結果。

+1

用'(x1-x2)** 2+(y1-y2)** 2 <='替換'math.sqrt((x1-x2)** 2+(y1-y2)** 2)半徑** 2',你不需要'輸入數學',你的代碼會更快。 – eumiro

+0

@eumiro:它會,但如果調用者指定負半徑,它也會產生不正確的結果。我知道這可以專門處理,但我的觀點是,在提出這種優化時應該小心。 – NPE

1
>>> p = [(0, 0), (1, 0), (0, 1), (1, 1), (0, -1), (-1, 1)] 
>>> orig = (0, 0) 
>>> map(lambda point: ((point[0]-orig[0])**2 + (point[1]-orig[1])**2)**(0.5), p) 
[0.0, 1.0, 1.0, 1.4142135623730951, 1.0, 1.4142135623730951] 
相關問題