首页 > 解决方案 > 对于每条可能的线,两点形成的线与其他点之间的距离

问题描述

给定一组点,对于该组中 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 的距离,这显然是零。我怎样才能使它更有效率?

标签: pythoniteratorpermutation

解决方案


而不是置换你的点,置换点的索引。然后,最内部的循环可以遍历每个点索引并排除与该对中的任何匹配的那些。

就像是:

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


推荐阅读