Python 计算两个三维点之间距离的快速方法
我有4个长度为160000的列表,如s、x、y、z。 我列出了一个x,y,z的3d阵列(点)。 我需要找到标准的所有点组合之间的距离,并将点的索引与列表s的索引相匹配,以便得到满足它的2个点的s值。 我正在使用下面的代码。 有没有更快的办法Python 计算两个三维点之间距离的快速方法,python,numpy,Python,Numpy,我有4个长度为160000的列表,如s、x、y、z。 我列出了一个x,y,z的3d阵列(点)。 我需要找到标准的所有点组合之间的距离,并将点的索引与列表s的索引相匹配,以便得到满足它的2个点的s值。 我正在使用下面的代码。 有没有更快的办法 import numpy as np points = [] for i in range(len(xnew)): a = np.array((xnew[i],ynew[i],znew[i])) points.append(a) for i
import numpy as np
points = []
for i in range(len(xnew)):
a = np.array((xnew[i],ynew[i],znew[i]))
points.append(a)
for i in range(len(points)):
for j in range(len(points)):
d = np.sqrt(np.sum((points[i] - points[j]) ** 2))
if d <= 4 and d >=3:
print(s[i],s[j],d)
将numpy导入为np
点数=[]
对于范围内的i(len(xnew)):
a=np.array((xnew[i],ynew[i],znew[i]))
点。附加(a)
对于范围内的i(len(点)):
对于范围内的j(len(点)):
d=np.sqrt(np.sum((点[i]-点[j])**2))
如果d=3:
打印(s[i],s[j],d)
想法是使用
和
将处理矢量化
代码
import numpy as np
import scipy.spatial.distance
# Distance between all pairs of points
d = scipy.spatial.distance.cdist(points, points)
# Pairs within threshold
indexes = np.where(np.logical_and(d>=3, d<=4))
for i, j in indexes:
if i < j: # since distance is symmetric, not reporting j, i
print(s[i],s[j],d[i][j])
输出(两种方法)
想法是使用
和
将处理矢量化
代码
import numpy as np
import scipy.spatial.distance
# Distance between all pairs of points
d = scipy.spatial.distance.cdist(points, points)
# Pairs within threshold
indexes = np.where(np.logical_and(d>=3, d<=4))
for i, j in indexes:
if i < j: # since distance is symmetric, not reporting j, i
print(s[i],s[j],d[i][j])
输出(两种方法)
试运行:
n = 10
x = np.random.randint(10, size= [n]) # dummy data
y = np.random.randint(10, size= [n])
z = np.random.randint(10, size= [n])
s = np.random.randint(10, size= [n])
运行上述代码之后
points
>>> array([
[9, 3, 5],
[7, 8, 1],
[0, 0, 2],
[6, 7, 2],
[4, 4, 3],
[8, 0, 9],
[5, 2, 6],
[0, 8, 9],
[2, 6, 9],
[4, 8, 4]])
试运行:
n = 10
x = np.random.randint(10, size= [n]) # dummy data
y = np.random.randint(10, size= [n])
z = np.random.randint(10, size= [n])
s = np.random.randint(10, size= [n])
运行上述代码之后
points
>>> array([
[9, 3, 5],
[7, 8, 1],
[0, 0, 2],
[6, 7, 2],
[4, 4, 3],
[8, 0, 9],
[5, 2, 6],
[0, 8, 9],
[2, 6, 9],
[4, 8, 4]])
您可以做的第一个改进是使用sqrt的对称性,即
d(i,j)=d(j,i)
,这样内部循环可以只迭代j>i您想检查一下,我不知道您的标准,但如果它类似于“找到彼此最接近的两点”你可以做的第一个改进是使用sqrt的对称性,即d(i,j)=d(j,i)
,这样内部循环可以只迭代j>i你想检查一下,我不知道你的标准,但如果是“找到彼此最接近的两点”而这正是你想要的方法。
n = 10
x = np.random.randint(10, size= [n]) # dummy data
y = np.random.randint(10, size= [n])
z = np.random.randint(10, size= [n])
s = np.random.randint(10, size= [n])
points
>>> array([
[9, 3, 5],
[7, 8, 1],
[0, 0, 2],
[6, 7, 2],
[4, 4, 3],
[8, 0, 9],
[5, 2, 6],
[0, 8, 9],
[2, 6, 9],
[4, 8, 4]])
s
>>> array([4, 2, 9, 9, 8, 2, 7, 6, 0, 5])
for e in ans:
print(*e)
>>> 9.0 8.0 3.7416573867739413
9.0 5.0 3.0
8.0 7.0 3.7416573867739413