Home Search   What's New Index Books Links Q & A Newsletter Banners   Feedback Tip Jar MSDN Visual Basic Community

Title Calculate arctangents in all four quadrants This example shows how to calculate arctangents in all four quadrants in Visual Basic 6. Visual Basic's Atn function only returns values between Pi and -Pi. This routine shows how to find correct angles in the other two quadrants. arctan, Atn, atan, arc tangent, math Algorithms, Miscellany

Thanks to Charlie Rose.

Visual Basic's Atn function only returns values between Pi and -Pi. This routine shows how to find correct angles in the other two quadrants.

You pass the Atan2 function the X and Y offsets in the direction of interest. The function uses the signs of the offsets to figure out which quadrant to return. It looks for very small X offsets which would produce an undefined error in calculating Atn(y / x) and uses Atn to calculate other values.

```Public Function Atan2(ByVal y As Double, ByVal x As Double) _
As Double
Dim theta As Double

If (Abs(x) < 0.0000001) Then
If (Abs(y) < 0.0000001) Then
theta = 0#
ElseIf (y > 0#) Then
theta = 1.5707963267949
Else
theta = -1.5707963267949
End If
Else
theta = Atn(y / x)

If (x < 0) Then
If (y >= 0#) Then
theta = 3.14159265358979 + theta
Else
theta = theta - 3.14159265358979
End If
End If
End If

Atan2 = theta
End Function```