2017-02-28 86 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 运行。

相关问题