Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: VB
Expertise: Advanced
Nov 15, 2006



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Calculate the Angle Between Two Lines

This code shows you how to calculate the angle between two lines using vectors and an inverse cosine function:

Public Function getAngleBetweenLinesVect(commonX As Single, commonY As Single, X1 As Single, 
Y1 As Single, Y2 As Single, X2 As Single) As Double
'check if both the lines are the same, if they are exit the function
If (commonY = Y1 And commonX = X1) Or (commonY = Y2 And commonX = X2) Or 
(Y1 = Y2 And X1 = X2) Then

Dim differenceX1 As Double, differenceX2 As Double, differenceY1 As Double, differenceY2 As Double
'set the variables 
differenceX1 = commonX - X1
differenceY1 = commonY - Y1
differenceX2 = commonX - X2
differenceY2 = commonY - Y2

'applying the angle between two lines vector rule, calculate the angle
'in radians
getAngleBetweenLinesVect = invCos(((differenceX1 * differenceX2) + (differenceY1 * differenceY2)) / _
(Sqr(CDbl(differenceX1) ^ 2 + CDbl(differenceY1) ^ 2) * Sqr(CDbl(differenceX2) ^ 2 + 
CDbl(differenceY2) ^ 2)))

End If

End Function

'the inverse cos function. Returns and angle.
Public Function invCos(X As Double) As Double

If X > 1 Or X < -1 Then
'if the ratio supplies is outside the acceptable range.    
ElseIf X = 1 Then
    invCos = 0
ElseIf X = -1 Then
    invCos = Pi
    invCos = (Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1))
End If

End Function
Richard Bunt
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date