What is the difference between atan and atan2 in C++?
Solution 1:
From school mathematics we know that the tangent has the definition
tan(α) = sin(α) / cos(α)
and we differentiate between four quadrants based on the angle that we supply to the functions. The sign of the sin
, cos
and tan
have the following relationship (where we neglect the exact multiples of π/2
):
Quadrant Angle sin cos tan
-------------------------------------------------
I 0 < α < π/2 + + +
II π/2 < α < π + - -
III π < α < 3π/2 - - +
IV 3π/2 < α < 2π - + -
Given that the value of tan(α)
is positive, we cannot distinguish, whether the angle was from the first or third quadrant and if it is negative, it could come from the second or fourth quadrant. So by convention, atan()
returns an angle from the first or fourth quadrant (i.e. -π/2 <= atan() <= π/2
), regardless of the original input to the tangent.
In order to get back the full information, we must not use the result of the division sin(α) / cos(α)
but we have to look at the values of the sine and cosine separately. And this is what atan2()
does. It takes both, the sin(α)
and cos(α)
and resolves all four quadrants by adding π
to the result of atan()
whenever the cosine is negative.
Remark: The atan2(y, x)
function actually takes a y
and a x
argument, which is the projection of a vector with length v
and angle α
on the y- and x-axis, i.e.
y = v * sin(α)
x = v * cos(α)
which gives the relation
y/x = tan(α)
Conclusion:
atan(y/x)
is held back some information and can only assume that the input came from quadrants I or IV. In contrast, atan2(y,x)
gets all the data and thus can resolve the correct angle.
Solution 2:
std::atan2
allows calculating the arctangent of all four quadrants. std::atan
only allows calculating from quadrants 1 and 4.
Solution 3:
The actual values are in radians but to interpret them in degrees it will be:
-
atan
= gives angle value between -90 and 90 -
atan2
= gives angle value between -180 and 180
For my work which involves computation of various angles such as heading and bearing in navigation, atan2
in most cases does the job.
Solution 4:
Another thing to mention is that atan2
is more stable when computing tangents using an expression like atan(y / x)
and x
is 0 or close to 0.
Solution 5:
atan(x) Returns the principal value of the arc tangent of x, expressed in radians.
atan2(y,x) Returns the principal value of the arc tangent of y/x, expressed in radians.
Notice that because of the sign ambiguity, a function cannot determine with certainty in which quadrant the angle falls only by its tangent value (atan alone). You can use atan2 if you need to determine the quadrant.