What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleFind the angle between two line segments using the Law of Cosines
Keywordsangle, line segments, law of cosines, arccosine, Acos
CategoriesAlgorithms, Graphics
Michael Ahlers suggested using the Law of Cosines to find the angle between two line segments. The Law of Cosines states for a triangle that:

    c^2 = a^2 + b^2 - 2 * a * b * Cos(C)

Where a, b, and c are the lengths of the sides of the triangle and A, B, and C are the angles opposite the corresponding sides. For example, A is the angle opposite side a.

Solving for C gives:

    C = Arccosine((c^2 - a^2 - b^2) / -2 * a * b)

Microsoft's Derived Math Formula Web page gives this formula for Arccosine:

    Arccosine(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)

Putting all this together lets us find the angle between two line segments. The GetAngle function calculates the triangle side lengths. It uses the formula above and the Acos function to calculate the angle.

Public Function GetAngle(ByVal Ax As Single, ByVal Ay As _
    Single, ByVal Bx As Single, ByVal By As Single, ByVal _
    Cx As Single, ByVal Cy As Single) As Single
Dim side_a As Single
Dim side_b As Single
Dim side_c As Single

    ' Get the lengths of the triangle's sides.
    side_a = Sqr((Bx - Cx) ^ 2 + (By - Cy) ^ 2)
    side_b = Sqr((Ax - Cx) ^ 2 + (Ay - Cy) ^ 2)
    side_c = Sqr((Ax - Bx) ^ 2 + (Ay - By) ^ 2)

    ' Calculate angle B between sides ab and bc.
    GetAngle = Acos((side_b ^ 2 - side_a ^ 2 - side_c ^ 2) _
        / (-2 * side_a * side_c))
End Function

' Return the arccosine of X.
Function Acos(ByVal X As Single) As Single
    Acos = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)
End Function
Note that the Acos function has trouble if X = 1. You could make the function test for that case and return 0.

Note also that this function always returns a positive angle. If you need to know the angle's sign, you'll need to do a little more work.

Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.