What is the difference between atan
and atan2
in C++?
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.