简体   繁体   English

使用python中的内置函数查找3d距离

[英]Finding 3d distances using an inbuilt function in python

I have 6 lists storing x,y,z coordinates of two sets of positions (3 lists each).我有 6 个列表存储两组位置的 x、y、z 坐标(每组 3 个列表)。 I want to calculate the distance between each point in both sets.我想计算两组中每个点之间的距离。 I have written my own distance function but it is slow.我已经编写了自己的距离函数,但速度很慢。 One of my lists has about 1 million entries.我的一个列表有大约 100 万个条目。 I have tried cdist, but it produces a distance matrix and I do not understand what it means.我试过 cdist,但它会产生一个距离矩阵,我不明白它是什么意思。 Is there another inbuilt function that can do this?是否有另一个内置函数可以做到这一点?

If possible, use the numpy module to handle this kind of things.如果可能,请使用numpy模块来处理此类事情。 It is a lot more efficient than using regular python lists.它比使用常规的 python 列表要高效得多。

I am interpreting your problem like this我正在这样解释你的问题

  1. You have two sets of points你有两组点
  2. Both sets have the same number of points ( N )两组的点数相同( N
  3. Point k in set 1 is related to point k in set 2. If each point is the coordinate of some object, I am interpreting it as set 1 containing the initial point and set 2 the point at some other time t.集合 1 中的点k与集合 2 中的点k相关。如果每个点都是某个对象的坐标,我将其解释为包含初始点的集合 1,并在其他时间 t 设置点 2。
  4. You want to find the distance d(k) = dist(p1(k), p2(k)) where p1(k) is point number k in set 1 and p2(k) is point number k in set 2.您想找到距离d(k) = dist(p1(k), p2(k)) ,其中p1(k)是集合 1 中的点号k ,而p2(k)是集合 2 中的点号k

Assuming that your 6 lists are x1_coords , y1_coords , z1_coords and x2_coords , y2_coords , z2_coords respectively, then you can calculate the distances like this假设您的 6 个列表分别是x1_coordsy1_coordsz1_coordsx2_coordsy2_coordsz2_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)

The distance between p1(k) and p2(k) is now stored in the numpy array as dist[k] . p1(k)p2(k)之间的距离现在作为dist[k]存储在 numpy 数组中。

As for speed: On my laptop with a "Intel(R) Core(TM) i7-3517U CPU @ 1.90GHz" the time to calculate the distance between two sets of points with N=1E6 is 45 ms.至于速度:在我的带有“Intel(R) Core(TM) i7-3517U CPU @ 1.90GHz”的笔记本电脑上,计算 N=1E6 的两组点之间的距离的时间是 45 毫秒。

Although this solution uses numpy , np.linalg.norm could be another solution.尽管此解决方案使用numpynp.linalg.norm可能是另一种解决方案。

Say you have one point p0 = np.array([1,2,3]) and a second point p1 = np.array([4,5,6]) .假设您有一个点p0 = np.array([1,2,3])和第二个点p1 = np.array([4,5,6]) Then the quickest way to find the distance between the two would be:那么找到两者之间距离的最快方法是:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM