2017-02-28 84 views
1

用於計算(x, y)平面中兩點之間距離的公式爲fairly known and straightforwardPython:(x,y)平面中一堆點之間的平均距離

但是,處理n問題的最佳方法是什麼?要計算平均距離?

實施例:

import matplotlib.pyplot as plt 
x=[89.86, 23.0, 9.29, 55.47, 4.5, 59.0, 1.65, 56.2, 18.53, 40.0] 
y=[78.65, 28.0, 63.43, 66.47, 68.0, 69.5, 86.26, 84.2, 88.0, 111.0] 
plt.scatter(x, y,color='k') 
plt.show() 

enter image description here

的距離被簡單地呈現爲:

import math 
dist=math.sqrt((x2-x1)**2+(y2-y1)**2) 

但是這是不允許的重複組合的問題。如何處理它?

+1

要循環的前一個。 –

+0

如果循環前一個,則最終重複計算:10選擇2,這會得到45個組合。 – FaCoffee

+0

時間複雜性會很有趣 –

回答

6

itertools.combinations使組合,而無需重複:

您的問題
>>> for combo in itertools.combinations([(1,1), (2,2), (3,3), (4,4)], 2): 
...  print(combo) 
... 
((1, 1), (2, 2)) 
((1, 1), (3, 3)) 
((1, 1), (4, 4)) 
((2, 2), (3, 3)) 
((2, 2), (4, 4)) 
((3, 3), (4, 4)) 

代碼:

import math 
from itertools import combinations 

def dist(p1, p2): 
    (x1, y1), (x2, y2) = p1, p2 
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) 

x = [89.86, 23.0, 9.29, 55.47, 4.5, 59.0, 1.65, 56.2, 18.53, 40.0] 
y = [78.65, 28.0, 63.43, 66.47, 68.0, 69.5, 86.26, 84.2, 88.0, 111.0] 

points = list(zip(x,y)) 
distances = [dist(p1, p2) for p1, p2 in combinations(points, 2)] 
avg_distance = sum(distances)/len(distances) 
4

在需要以上的點列這種情況下:

from math import sqrt 

def avg_distance(x,y): 
    n = len(x) 
    dist = 0 
    for i in range(n): 
     xi = x[i] 
     yi = y[i] 
     for j in range(i+1,n): 
      dx = x[j]-xi 
      dy = y[j]-yi 
      dist += sqrt(dx*dx+dy*dy) 
    return 2.0*dist/(n*(n-1)) 

在最後的步驟中,我們通過Ñ×(N-1)/ 2其是分割的總距離的結果:

n-1 
--- 
\  n (n-1) 
/ i = ------- 
---  2 
i=1 

其因此總距離我們計算。

這裏我們不測量點與自身之間的距離(當然這總是爲0)。請注意,這當然會對平均值產生影響,因爲您不會對它們進行計數。

鑑於有Ñ分,該算法在爲O(n 2 運行。

相關問題