Search code examples
mathgeometrylinepseudocodeangle

Angle between two lines beginning at one side of the line


I have two lines specified by two points with x and y coordinate each. The first point (where the lines begin) is equal meaning that I have 3 points A, B and C where one line is from A to B and the other one from A to C. I would then want to calculate the angle between the two lines starting at the right side of the first line. The result needn't be accurate I actually only need to know if this angle is greater or less than 180° (π rad). Thanks for any help - you needn't write any code, pseudocode and/or explanation would be great.


Solution

  • Let's define some notation:

    A := (a1, a1).
    B := (b1, b2).
    C := (c1, c2).
    

    Then the determinant D of the matrix

    1 a1 a2
    1 b1 b2
    1 c1 c2
    

    determines whether C lies left or right of the directed line AB [cf. Computational Geometry - Berg, van Kreveld, Overmars, Schwarzkopf - Chapter 1, Exercise 1.4 a)]

    Now, you can subtract row 1 from rows 2 and 3:

    1 a1     a2
    0 b1-a1 b2-a2
    0 c1-a1 c2-a2
    

    and calculate D from the first column to get:

    (b1-a1)*(c2-a2) > (c1-a1)*(b2-a2)
    

    as the condition representing whether Clies on the left of AC or not. Of course, lying on the right (resp. left) means that the angle is < 180 (resp. > 180)

    Example

    A = (0, 0)
    B = (0, 1)
    C = (1, 0)
    

    Then AB is the vertical segment (y axis) and C is clearly on its right side. The condition

    (b1-a1)*(c2-a2) > (c1-a1)*(b2-a2)           ineq(1)
    

    becomes:

    0 > 1
    

    which is false, meaning that C is not on the left of AB (as expected)

    Visualization

    To visualize the condition we can translate the three points A, B and C until A becomes (0,0). This is an innocuous transformation because the condition in ineq(1) subtracts a1 and a2 from the coordinates of B and C. With this translation ineq(1) becomes:

    b1*c2 > c1*b2                              ineq(2)
    

    Now, lets visualize the three points (ignore for now the brown lines relative to C' = (c'1, c'2)):

    enter image description here

    The product b1*c2 is the area of the RED rectangle. The product c1*b2 is the area of the GREEN rectangle. The picture shows that RED < GREEN meaning that C is on the right.

    Now, mentally move C around, say to C' and visualize the new RED and GREEN rectangles. The inequality remains valid as long as C is on the right.

    Not convinced yet? Well, write a program that dynamically reproduces this picture while you change the position of C and voila! (Or study some more Mathematics and solve the book's exercise ;)

    Note: Be aware that these rectangles have a sign. In the picture they both have a positive area, however, in general, the products b1*c2 and b2*c1 will have a sign.