给出一组点,对于该集中2个点的所有排列,我想计算从其他点到该对点所定义的线的总平方距离。
这是我到目前为止所拥有的:
import numpy as np
import itertools
def dist_point2line(a, b, c):
return np.linalg.norm(np.cross(a-b, c-b))/np.linalg.norm(c-b)
points = np.array([(1,2), (2,3), (3,2), (0,4), (4,1), (3,3)])
pairs = itertools.permutations(points, 2)
distances = []
for (p2, p3) in pairs:
total = 0
for p1 in points:
distance = dist_point2line(p1, p2, p3)
total += distance*distance
distances.append(total)
问题是,这目前还计算到p2和p3的距离,它们显然为零。如何提高效率?
答案 0 :(得分:0)
代替排列点,而是排列点的索引。然后,最内部的循环可以遍历每个点索引,并排除与该对中的任何点匹配的索引。
类似的东西:
for pair in itertools.permutations(range(0, len(points)), 2):
p1, p2 = points[pair, :]
total = 0
for other in range(0, len(points)):
if other in pair:
continue
p3 = points[other]
distance = dist_point2line(p1, p2, p3)
total += distance**2
distances.append(total)
为了提高性能,您可以将distances
变量初始化为numpy数组而不是列表:
n = len(points)
distances = np.zeros([n * (n-1)], dtype=np.float32)
您需要将代码修复一下:
for k, pair in enumerate(itertools.permutations(range(0, len(points)), 2)):
total = 0
...
distances[k] = total