Python:(x,y)平面中一堆点之间的平均距离 | 您所在的位置:网站首页 › combination算法 › Python:(x,y)平面中一堆点之间的平均距离 |
计算(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()距离简单地呈现为: import math dist=math.sqrt((x2-x1)**2+(y2-y1)**2)但这是一个不允许重复组合的问题.怎么接近它? 1> Steven Rumba..: 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) |
CopyRight 2018-2019 实验室设备网 版权所有 |