Python 两条线之间的最近距离

Python 两条线之间的最近距离,python,geometry,distance,vectormath,Python,Geometry,Distance,Vectormath,我想做一个函数来获取任意两条直线之间的最近/最短距离(假设它们不相交)。我知道有好几条关于点和线之间最短距离的帖子,但我找不到两条线的帖子 我咨询了几个数学和向量学习网站,并设法破解了下面的算法。它给出了一个答案,但不是正确的答案。例如,在查找以下各项之间的最短距离时: l1 = [(5,6),(5,10)] l2 = [(0,0),(10,10)] print _line2line(l1,l2) …它给出的答案是 5.75223741636 从两条线的图表中可以看出(它显示了一个10x1

我想做一个函数来获取任意两条直线之间的最近/最短距离(假设它们不相交)。我知道有好几条关于点和线之间最短距离的帖子,但我找不到两条线的帖子

我咨询了几个数学和向量学习网站,并设法破解了下面的算法。它给出了一个答案,但不是正确的答案。例如,在查找以下各项之间的最短距离时:

l1 = [(5,6),(5,10)]
l2 = [(0,0),(10,10)]
print _line2line(l1,l2)
…它给出的答案是

5.75223741636 
从两条线的图表中可以看出(它显示了一个10x10帧,每1个单元有一个记号标记),从理论上讲,点(6,5)和(5,5)之间的距离应该小得多,大约为1

所以我想知道是否有人能在我的代码中发现我做错了什么?(如果可能,我还想知道如何获得两条直线最接近的实际点…)

下面代码的注释:L1和L2分别表示第1行和第2行,x/y1和x/y2分别表示每行的起点和终点。后缀dx和dy表示delta或x和y,即向量原点为0,0时的向量


事实上,可能是重复的。再解释一下:上面的代码是关于直线距离的,您有两条线段。(直线距离在2D中是愚蠢的——任何两条非平行直线的距离都为零。)(至于为什么当前函数不返回零,顺便说一句,这是因为您使用2D垂直公式计算的垂直度不正确。两条非平行2D直线不能有一个公共垂直线,只有一条离开平地。)@Sneftel和David Heffernan,谢谢你的链接,它基本上解决了我的问题,并教会了我它是如何工作的:)我在发帖前尝试过搜索,但找不到那个特定的帖子。至于我的代码,我想一定是误读了数学来源,我想主要是我忘了区分直线段和无限直线。考虑到你给出的链接中有一个更好的问题和答案,你们认为我应该删除这个问题,还是可以帮助其他人找到你给出的链接?我什么都可以。。。
def _line2line(line1, line2):

    """
    - line1 is a list of two xy tuples
    - line2 is a list of two xy tuples
    References consulted:
    http://mathforum.org/library/drmath/view/51980.html
    and http://mathforum.org/library/drmath/view/51926.html
    and https://answers.yahoo.com/question/index?qid=20110507163534AAgvfQF
    """

    import math
    #step1: cross prod the two lines to find common perp vector
    (L1x1,L1y1),(L1x2,L1y2) = line1
    (L2x1,L2y1),(L2x2,L2y2) = line2
    L1dx,L1dy = L1x2-L1x1,L1y2-L1y1
    L2dx,L2dy = L2x2-L2x1,L2y2-L2y1
    commonperp_dx,commonperp_dy = (L1dy - L2dy, L2dx-L1dx)

    #step2: normalized_perp = perp vector / distance of common perp
    commonperp_length = math.hypot(commonperp_dx,commonperp_dy)
    commonperp_normalized_dx = commonperp_dx/float(commonperp_length)
    commonperp_normalized_dy = commonperp_dy/float(commonperp_length)

    #step3: length of (pointonline1-pointonline2 dotprod normalized_perp).
    # Note: According to the first link above, it's sufficient to
    #    "Take any point m on line 1 and any point n on line 2."
    #    Here I chose the startpoint of both lines
    shortestvector_dx = (L1x1-L2x1)*commonperp_normalized_dx
    shortestvector_dy = (L1y1-L2y1)*commonperp_normalized_dy
    mindist = math.hypot(shortestvector_dx,shortestvector_dy)

    #return results
    result = mindist
    return result