Search code examples
pythonmathgeometrycomputational-geometry

Compare 2 lines direction


I have points of line as

line1 = (13.010815620422363, 6.765378475189209), (-9.916780471801758, 12.464008331298828)
line2 = (-28.914321899414062, 2.4057865142822266),(13.973191261291504, -8.306382179260254)

Is there is a way to get the line direction from some formula or code(python)?


Solution

  • First calculate the vectors of the two lines. Then you can calculate the cosine of the angle between the two vectors using the dot product. If the result is close to 1, both lines point in the same direction. If the result is close to -1, the second line points in the opposite direction.

    import math
    
    line1 = (13.010815620422363, 6.765378475189209), (-9.916780471801758, 12.464008331298828)
    line2 = (-28.914321899414062, 2.4057865142822266),(13.973191261291504, -8.306382179260254)
    
    vec1 = (line1[1][0] - line1[0][0], line1[1][1] - line1[0][1])
    vec2 = (line2[1][0] - line2[0][0], line2[1][1] - line2[0][1])
    
    cos_angle = (vec1[0] * vec2[0] + vec1[1] * vec2[1]) / math.sqrt((vec1[0]**2 + vec1[1]**2) * (vec2[0]**2 + vec2[1]**2))
    

    In this case the result is -0.9999993352122917