[英]Finding a power spectrum in Python, without using the inbuilt FFT function
[英]Finding 3d distances using an inbuilt function in python
我有 6 个列表存储两组位置的 x、y、z 坐标(每组 3 个列表)。 我想计算两组中每个点之间的距离。 我已经编写了自己的距离函数,但速度很慢。 我的一个列表有大约 100 万个条目。 我试过 cdist,但它会产生一个距离矩阵,我不明白它是什么意思。 是否有另一个内置函数可以做到这一点?
如果可能,请使用numpy
模块来处理此类事情。 它比使用常规的 python 列表要高效得多。
我正在这样解释你的问题
N
)k
与集合 2 中的点k
相关。如果每个点都是某个对象的坐标,我将其解释为包含初始点的集合 1,并在其他时间 t 设置点 2。d(k) = dist(p1(k), p2(k))
,其中p1(k)
是集合 1 中的点号k
,而p2(k)
是集合 2 中的点号k
。 假设您的 6 个列表分别是x1_coords
、 y1_coords
、 z1_coords
和x2_coords
、 y2_coords
、 z2_coords
,那么您可以像这样计算距离
import numpy as np
p1 = np.array([x1_coords, y1_coords, z1_coords])
p2 = np.array([x2_coords, y2_coords, z2_coords])
squared_dist = np.sum((p1-p2)**2, axis=0)
dist = np.sqrt(squared_dist)
p1(k)
和p2(k)
之间的距离现在作为dist[k]
存储在 numpy 数组中。
至于速度:在我的带有“Intel(R) Core(TM) i7-3517U CPU @ 1.90GHz”的笔记本电脑上,计算 N=1E6 的两组点之间的距离的时间是 45 毫秒。
尽管此解决方案使用numpy
, np.linalg.norm
可能是另一种解决方案。
假设您有一个点p0 = np.array([1,2,3])
和第二个点p1 = np.array([4,5,6])
。 那么找到两者之间距离的最快方法是:
dist = np.linalg.norm(p0 - p1)
# Use the distance function in Cartesian 3D space:
# Example
import math
def distance(x1, y1, z1, x2, y2, z2):
d = 0.0
d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
return d
您可以使用math.dist(A, B)
,其中 A 和 B 是坐标数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.