python - 对于每条可能的线,两点形成的线与其他点之间的距离
问题描述
给定一组点,对于该组中 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 的距离,这显然是零。我怎样才能使它更有效率?
解决方案
而不是置换你的点,置换点的索引。然后,最内部的循环可以遍历每个点索引并排除与该对中的任何匹配的那些。
就像是:
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
推荐阅读
- python - 程序跳过while-else
- j2ssh - 网络故障上的 J2SSH Maverick 行为
- c# - 将字符串数组列表复制到 excel 文件时的奇怪行为
- c++ - 如何在不使用 append 函数的情况下追加到 C++ 字符串?
- javascript - 为什么我的箭头函数错误为“不是函数”?
- mongodb - MongoDB 数据在 docker 容器上下移动之间不持久 [MacOSX]
- python - Python find.all [BeautifulSoup] 突然返回空
- c# - 从当前在 android 设备上播放的任何声音中获取数据?
- api - 在 SPFx 上的 MS Graph API 中转换文件返回未定义
- autodesk-forge - Forge 身份验证:如何在刷新时处理 GatewayTimeout