检查两条线段之间的最短三维距离,其中直线表示同时的轨迹

2024-09-30 16:34:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我要解决的问题如下。我有两个线段,在三维空间中,希望找到它们之间的最短距离(如果有的话)。在

我已经看到了找到最近点的解决方案,但是在这种情况下,需要注意的是,直线表示由一个属性给定的两个对象的位置。这两条线都有一个起点,代表两个空间物体。两条线都有一个端点,表示空间中相同的两个对象。一条线的中途通过与另一条线的中途直接相关。等等。 目标是找到表示两个对象最接近的属性值(如果有意义的话?)。在

到目前为止,我一直在做的是递归地在百分位块中运行并检查距离。然后在找到最接近的点之后进行优化搜索,以此类推。很多检查。。。当我决定停止检查时,最终结果通常是“足够接近”。在

我想要的是一个简单的公式,如果有一个可以避免暴力强迫它的存在,或者一个寻找的方向,以便找到所说的公式。如果可能的话,最好是python代码中的一个示例。在

先谢谢你们!:)

编辑:

因为我8个小时都不能回答。。。 我已经设法通过谷歌找到了这个解决方案。我不确定是否有更优雅的解决方案(我打赌有!:P),但似乎有效。在

def VectorMath(method,p1,p2=None): #perform math on vector
    new = []
    for i in range(3):
        try:
            new.append( method(p1[i],p2[i]) )
        except TypeError:
            new.append( method(p1[i],p2) )
    return new
def ClosestPoint(p1, p2): #get closest point between two lines
    dv = VectorMath(lambda x,y: y-x, p1['v'],p2['v'])
    dv2 = sum(p*q for p,q in zip(dv,dv))
    if dv2 < 0.00001: #tracks are parallel
        return 0.0
    orig = VectorMath(lambda x,y: x-y, p1['p'], p2['p'])
    return sum(p*q for p,q in zip(orig,dv)) / dv2
def Distance(p1, p2):
    return m.sqrt(sum(VectorMath(lambda x,y: (y-x)**2, p1,p2)))

a = {'p':[1.0,0.0,-2.0] } #just establishing a test case of points
a['v'] = VectorMath(lambda x,y:y-x,a['p'],[4.0,0.0,6.0])
b = {'p':[0.0,0.0,0.0] } #second line test case
b['v'] = VectorMath(lambda x,y:y-x,b['p'],[3.0,0.0,0.0])

point = ClosestPoint(a,b) #location on lines where two objects reach nearest location
a1 = VectorMath(lambda x,y: x+y, a['p'],VectorMath(lambda x,y: x*point, a['v'])) #points at closest location
b1 = VectorMath(lambda x,y: x+y, b['p'],VectorMath(lambda x,y: x*point, b['v']))
dist = Distance(a1,b1) #distance between points

Tags: 对象lambdainnewforreturndef解决方案