代码之家  ›  专栏  ›  技术社区  ›  Matthew Mitchell

求两个向量方程的交集

  •  1
  • Matthew Mitchell  · 技术社区  · 16 年前

    我一直在试图解决这个问题,我发现了一个方程,给出了零除法误差的可能性。不是最好的事情:

    v1 = (a,b)
    v2 = (c,d)
    d1 = (e,f)
    d2 = (h,i)
    
    l1: v1 + λd1
    l2: v2 + µd2
    
    Equation to find vector intersection of l1 and l2 programatically by re-arranging for lambda.
    
    (a,b) + λ(e,f) = (c,d) + µ(h,i)
    a + λe = c + µh
    b +λf = d + µi
    µh = a + λe - c
    µi = b +λf - d
    µ = (a + λe - c)/h
    µ = (b +λf - d)/i
    (a + λe - c)/h = (b +λf - d)/i
    a/h + λe/h - c/h = b/i +λf/i - d/i
    λe/h - λf/i =  (b/i - d/i) - (a/h - c/h)
    λ(e/h - f/i) = (b - d)/i - (a - c)/h
    λ = ((b - d)/i - (a - c)/h)/(e/h - f/i)
    
    Intersection vector = (a + λe,b + λf)
    

    不确定它在某些情况下是否有效。我没试过。

    我需要知道如何对a-I中的值进行处理。

    非常感谢。

    3 回复  |  直到 16 年前
        1
  •  1
  •   Neil Mayhew    16 年前

    intersection of lines 你会发现很多公式,不涉及除以一个坐标。来自维基百科的sputsoft对算法有很好的解释。

    关于你的数学,你太快了 小时 和 我 . 一个解决方案可以通过推迟划分来达成。例如,乘以 小时 通过 我 那个是给我的 我 通过 小时 . 这就给出了 这与你的相当,但没有潜在的非法划分:

    通过 你好 .

        2
  •  0
  •   aeflash    16 年前

    使用你的VAR,如果(e h) 等于或接近0,直线平行。

        3
  •  0
  •   Matthew Mitchell    16 年前

    下面是使用python函数的解决方案。v1和v2是位置向量。d1和d2是方向向量。

    def vector_intersection(v1,v2,d1,d2):
        '''
        v1 and v2 - Vector points
        d1 and d2 - Direction vectors
        returns the intersection point for the two vector line equations.
        '''
        if d1[0] == 0 and d2[0] != 0 or d1[1] == 0 and d2[1] != 0:
            if d1[0] == 0 and d2[0] != 0:
                mu = float(v1[0] - v2[0])/d2[0]
            elif d1[1] == 0 and d2[1] != 0:
                mu = float(v1[1] - v2[1])/d2[1]
            return (v2[0] + mu* d2[0],v2[1] + mu * d2[1])
        else:
            if d1[0] != 0 and d1[1] != 0 and d2[0] != 0 and d2[1] != 0:
                if d1[1]*d2[0] - d1[0]*d2[1] == 0:
                    raise ValueError('Direction vectors are invalid. (Parallel)')
                lmbda = float(v1[0]*d2[1] - v1[1]*d2[0] - v2[0]*d2[1] + v2[1]*d2[0])/(d1[1]*d2[0] - d1[0]*d2[1])
            elif d2[0] == 0 and d1[0] != 0:
                lmbda = float(v2[0] - v1[0])/d1[0]
            elif d2[1] == 0 and d1[1] != 0:
                lmbda = float(v2[1] - v1[1])/d1[1]
            else:
                raise ValueError('Direction vectors are invalid.')
            return (v1[0] + lmbda* d1[0],v1[1] + lmbda * d1[1])