# Atan2

In computing and mathematics, the function atan2 is the 2-argument arctangent. By definition, $\theta =\operatorname {atan2} (y,x)$ is the angle measure (in radians, with $-\pi <\theta \leq \pi$) between the positive $x$-axis and the ray from the origin to the point $(x,\,y)$ in the Cartesian plane. Equivalently, $\operatorname {atan2} (y,x)$ is the argument (also called phase or angle) of the complex number $x+iy.$ (The argument of a function and the argument of a complex number, each mentioned above, should not be confused.)
The $\operatorname {atan2}$ function first appeared in the programming language Fortran in 1961. It was originally intended to return a correct and unambiguous value for the angle ⁠$\theta$⁠ in converting from Cartesian coordinates ⁠$(x,\,y)$⁠ to polar coordinates ⁠$(r,\,\theta )$⁠. If $\theta =\operatorname {atan2} (y,x)$ and r=√(x$^2$+y$^2$){\textstyle r={\sqrt {x^{2}+y^{2}}}}, then $x=r\cos \theta$ and $y=r\sin \theta .$
If ⁠$x>0$⁠, the desired angle measure is θ=atan2⁡(y, x)=arctan⁡(y/x).{\textstyle \theta =\operatorname {atan2} (y, x)=\arctan \left(y/x\right).} However, when x < 0, the angle $\arctan(y/x)$ is diametrically opposite the desired angle, and ⁠$\pm \pi$⁠ (a half turn) must be added to place the point in the correct quadrant. Using the $\operatorname {atan2}$ function does away with this correction, simplifying code and mathematical formulas.

## Motivation

The ordinary single-argument arctangent function only returns angle measures in the interval ⁠${\bigl{-{\tfrac {1}{2}}\pi },{\tfrac {1}{2}}\pi )$⁠, and when invoking it to find the direction angle from the origin to an arbitrary point ⁠$(x,\,y)$⁠ in the Cartesian plane, it will yield incorrect results when the point is in the left half-plane ⁠$x<0$⁠. Diametrically opposite angle measures have the same tangent because $y/x=(-y)/(-x).$
To fully determine the direction angle from the origin given a point ⁠$(x,\,y)$⁠ using the arctangent function, mathematical formulas or computer code must handle multiple cases; at least one for positive values of $x$ and one for negative values of ⁠$x$⁠, and sometimes additional cases when ⁠$y$⁠ is negative or one coordinate is zero. Finding angle measures and converting Cartesian to polar coordinates are common in scientific computing, and this code is redundant and error-prone.
To save programmers the trouble, computer programming languages introduced the atan2 function, at least as early as the Fortran IV language of the 1960s. The quantity ⁠$\operatorname {atan2} (y,x)$⁠ is the angle measure between the ⁠$x$⁠-axis and a ray from the origin to a point ⁠$(x,\,y)$⁠ anywhere in the Cartesian plane. The signs of ⁠$x$⁠ and ⁠$y$⁠ are used to determine the quadrant of the result and select the correct branch of the multivalued function ⁠$\operatorname {Arctan} (y/x)$⁠.
The atan2 function is useful in many applications involving Euclidean vectors such as finding the direction from one point to another or converting a rotation matrix to Euler angles.
The atan2 function is now included in many other programming languages, and is also commonly found in mathematical formulas throughout science and engineering.

### Argument order

In 1961, Fortran introduced the atan2 function with argument order ⁠$(y,x)$⁠ so that the argument (phase angle) of a complex number is $\operatorname {arg} z=\operatorname {atan2} (\operatorname {Im} z,\operatorname {Re} z).$ This follows the left-to-right order of a fraction written $y/x,$ so that $\operatorname {atan2} (y,x)=\operatorname {atan} (y/x)$ for positive values of $x.$ However, this is the opposite of the conventional component order for complex numbers, $z=x+iy,$ or as coordinates $(\operatorname {Re} z,\operatorname {Im} z).$ See section Definition and computation.
Some other programming languages (see § Realizations of the function in common computer languages) picked the opposite order instead. For example Microsoft Excel uses $\operatorname {Atan2} (x,\,y),$ OpenOffice Calc uses $\operatorname {arctan2} (x,\,y),$ and Mathematica uses $\operatorname {ArcTan} [x,y],$ defaulting to one-argument arctangent if called with one argument.

## Definition and computation

The function atan2 computes the principal argument of the complex number ⁠$x+iy$⁠, which is also the imaginary part of the principal value of the complex logarithm. That is, $\operatorname {atan2} (y,x)=\operatorname {arg} (x+iy)=\operatorname {Im} \operatorname {log} (x+iy).$
Adding any integer multiple of ⁠$2\pi$⁠ (corresponding to complete turns around the origin) gives another argument of the same complex number, but the principal argument is defined as the unique representative angle in the interval ⁠$(-\pi ,\pi ]$⁠.
In terms of the standard arctangent function, whose image is ⁠${\bigl{-{\tfrac {1}{2}}\pi },{\tfrac {1}{2}}\pi {\bigr )}$⁠, atan2 can be expressed piecewise:
$\operatorname {atan2} (y,x)={\begin{cases}\arctan \left({\frac {y}{x}}\right)&{\text{if }}x>0,\\[5mu]\arctan \left({\frac {y}{x}}\right)+\pi &{\text{if }}x<0{\text{ and }}y\geq 0,\\[5mu]\arctan \left({\frac {y}{x}}\right)-\pi &{\text{if }}x<0{\text{ and }}y<0,\\[5mu]+{\frac {\pi }{2}}&{\text{if }}x=0{\text{ and }}y>0,\\[5mu]-{\frac {\pi }{2}}&{\text{if }}x=0{\text{ and }}y<0,\\[5mu]{\text{undefined}}&{\text{if }}x=0{\text{ and }}y=0.\end{cases}}$
Instead of the tangent, it can be convenient to use the half-tangent ⁠$t=\tan {\tfrac {1}{2}}\theta$⁠ as a representation of an angle, partly because the angle ⁠$\theta =\operatorname {atan2} (y,\,x)$⁠ has a unique half-tangent, $\tan {\tfrac {1}{2}}\theta ={\frac {y}{\textstyle {\sqrt {x^{2}+y^{2}}}+x}}={\frac {\textstyle {\sqrt {x^{2}+y^{2}}}-x}{y}}.$
(See tangent half-angle formula.) The expression with ⁠$y$⁠ in the denominator should be used when ⁠$x<0$⁠ and ⁠$y\neq 0$⁠ to avoid possible loss of significance in computing ⁠$\textstyle {\sqrt {x^{2}+y^{2}}}+x$⁠. When an atan2 function is unavailable, it can be computed as twice the arctangent of the half-tangent ⁠$t$⁠. That is, $\operatorname {atan2} (y,x)=2\arctan \left({\frac {y}{\textstyle {\sqrt {x^{2}+y^{2}}}+x}}\right)=2\arctan \left({\frac {\textstyle {\sqrt {x^{2}+y^{2}}}-x}{y}}\right)\,.$

## Derivative

As the function atan2 is a function of two variables, it has two partial derivatives. At points where these derivatives exist, atan2 is, except for a constant, equal to arctan(y/x). Hence,
    ${\begin{aligned}&{\frac {\partial }{\partial x}}\operatorname {atan2} (y,\,x)={\frac {\partial }{\partial x}}\arctan \left({\frac {y}{x}}\right)=-{\frac {y}{x^{2}+y^{2}}},\\[5pt]&{\frac {\partial }{\partial y}}\operatorname {atan2} (y,\,x)={\frac {\partial }{\partial y}}\arctan \left({\frac {y}{x}}\right)={\frac {x}{x^{2}+y^{2}}}.\end{aligned}}$
Thus the gradient of atan2 is given by
    $\nabla {\text{atan2}}(y,x)=\left({-y \over x^{2}+y^{2}},\ {x \over x^{2}+y^{2}}\right).$
Informally representing the function atan2 as the angle function θ(x, y) = atan2(y, x) (which is only defined up to a constant) yields the following formula for the total differential:
    ${\begin{aligned}\mathrm {d} \theta &={\frac {\partial }{\partial x}}\operatorname {atan2} (y,\,x)\,\mathrm {d} x+{\frac {\partial }{\partial y}}\operatorname {atan2} (y,\,x)\,\mathrm {d} y\\[5pt]&=-{\frac {y}{x^{2}+y^{2}}}\,\mathrm {d} x+{\frac {x}{x^{2}+y^{2}}}\,\mathrm {d} y.\end{aligned}}$
While the function atan2 is discontinuous along the negative x-axis, reflecting the fact that angle cannot be continuously defined, this derivative is continuously defined except at the origin, reflecting the fact that infinitesimal (and indeed local) changes in angle can be defined everywhere except the origin. Integrating this derivative along a path gives the total change in angle over the path, and integrating over a closed loop gives the winding number.
In the language of differential geometry, this derivative is a one-form, and it is closed (its derivative is zero) but not exact (it is not the derivative of a 0-form, i.e., a function), and in fact it generates the first de Rham cohomology of the punctured plane. This is the most basic example of such a form, and it is fundamental in differential geometry.
The partial derivatives of atan2 do not contain trigonometric functions, making it particularly useful in many applications (e.g. embedded systems) where trigonometric functions can be expensive to evaluate.

## Illustrations

This figure shows values of atan2 along selected rays from the origin, labelled at the unit circle. The values, in radians, are shown inside the circle. The diagram uses the standard mathematical convention that angles increase counterclockwise from zero along the ray to the right. Note that the order of arguments is reversed; the function atan2(y, x) computes the angle corresponding to the point (x, y).
This figure shows the values of $\arctan(\tan(\theta ))$ along with $\operatorname {atan2} (\sin(\theta ),\cos(\theta ))$ for $0\leq \theta \leq 2\pi$. Both functions are odd and periodic with periods $\pi$ and $2\pi$, respectively, and thus can easily be supplemented to any region of real values of $\theta$. One can clearly see the branch cuts of the $\operatorname {atan2}$-function at $\theta =\pi$, and of the $\arctan$-function at $\theta \in \{{\tfrac {\pi }{2}},\;{\tfrac {3\pi }{2}}\}$.
The two figures below show 3D views of respectively atan2(y, x) and arctan(⁠y/x⁠) over a region of the plane. Note that for atan2(y, x), rays in the X/Y-plane emanating from the origin have constant values, but for arctan(⁠y/x⁠) lines in the X/Y-plane passing through the origin have constant values. For x > 0, the two diagrams give identical values.

## Angle sum and difference identity

The sum or difference of multiple angles to be computed by ⁠$\operatorname {atan2}$⁠ can alternately be computed by composing them as complex numbers. Given two coordinate pairs ⁠$(x_{1},y_{1})$⁠ and ⁠$(x_{2},y_{2})$⁠, their angles from the positive ⁠$x$⁠ axis will be composed (and lengths multiplied) if they are treated as complex numbers and then multiplied together, ⁠$(x_{1}+iy_{1})(x_{2}+iy_{2})=$⁠⁠$(x_{1}x_{2}-y_{1}y_{2})+i(y_{1}x_{2}+x_{1}y_{2})$⁠. The resulting angle can be found using a single ⁠$\operatorname {atan2}$⁠ operation, so long as the as long as the resulting angle lies in ⁠$(-\pi ,\pi ]$⁠:
    $\operatorname {atan2} (y_{1},x_{1})\pm \operatorname {atan2} (y_{2},x_{2})=\operatorname {atan2} (y_{1}x_{2}\pm x_{1}y_{2},x_{1}x_{2}\mp y_{1}y_{2}),$
and likewise for more than two coordinate pairs. If the composed angle crosses the negative ⁠$x$⁠-axis (i.e. exceeds the range ⁠$(-\pi ,\pi ]$⁠), then the crossings can be counted and the appropriate integer multiple of ⁠$2\pi$⁠ added to the final result to correct it.
This difference formula is frequently used in practice to compute the angle between two planar vectors, since the resulting angle is always in the range ⁠$(-\pi ,\pi ]$⁠.

## East-counterclockwise, north-clockwise and south-clockwise conventions, etc.

The $\mathrm {atan2}$ function was originally designed for the convention in pure mathematics that can be termed east-counterclockwise. In practical applications, however, the north-clockwise and south-clockwise conventions are often the norm. In atmospheric sciences, for instance, the wind direction can be calculated using the $\mathrm {atan2}$ function with the east- and north-components of the wind vector as its arguments; the solar azimuth angle can be calculated similarly with the east- and north-components of the solar vector as its arguments. The wind direction is normally defined in the north-clockwise sense, and the solar azimuth angle uses both the north-clockwise and south-clockwise conventions widely. These different conventions can be realized by swapping the positions and changing the signs of the x- and y-arguments as follows:
* $\mathrm {atan2} (y,\,x),\;\;\;\;\;$ (East-Counterclockwise Convention)
* $\mathrm {atan2} (x,\,y),\;\;\;\;\;$ (North-Clockwise Convention)
* $\mathrm {atan2} ({-x},\,{-y})$. (South-Clockwise Convention)
As an example, let $x_{0}={\frac {\sqrt {3}}{2}}$ and $y_{0}={\frac {1}{2}}$, then the east-counterclockwise format gives $\mathrm {atan2} (y_{0},x_{0})\cdot {\frac {180}{\pi }}=30^{\circ }$, the north-clockwise format gives $\mathrm {atan2} (x_{0},y_{0})\cdot {\frac {180}{\pi }}=60^{\circ }$, and the south-clockwise format gives $\mathrm {atan2} (-x_{0},-y_{0})\cdot {\frac {180}{\pi }}=-120^{\circ }$.
Changing the sign of the x- and/or y-arguments and/or swapping their positions can create 8 possible variations of the $\mathrm {atan2}$ function and they, interestingly, correspond to 8 possible definitions of the angle, namely, clockwise or counterclockwise starting from each of the 4 cardinal directions, north, east, south and west.

## Realizations of the function in common computer languages

The realization of the function differs from one computer language to another:
* In Microsoft Excel, OpenOffice.org Calc, LibreOffice Calc, Google Spreadsheets, and iWork Numbers, the 2-argument arctangent function has the two arguments in the standard sequence $(\operatorname {Re} ,\operatorname {Im} )$ (reversed relative to the convention used in the discussion above).
* In Mathematica, the form ArcTan[x, y] is used where the one parameter form supplies the normal arctangent. Mathematica classifies ArcTan[0, 0] as an indeterminate expression.
* On most TI graphing calculators (excluding the TI-85 and TI-86), the equivalent function is called R►Pθ and has the arguments $(\operatorname {Re} ,\operatorname {Im} )$.
* On TI-85 the arg function is called angle(x,y) and although it appears to take two arguments, it really only has one complex argument which is denoted by a pair of numbers: x + i y = (x, y).
The $(\operatorname {Im} ,\operatorname {Re} )$ convention is used by:
* The C function atan2, and most other computer implementations, are designed to reduce the effort of transforming cartesian to polar coordinates and so always define atan2(0, 0). On implementations without signed zero, or when given positive zero arguments, it is normally defined as 0. It will always return a value in the range [−π, π] rather than raising an error or returning a NaN (Not a Number).
* In Common Lisp, where optional arguments exist, the atan function allows one to optionally supply the x coordinate: (atan y x).
* In Julia, the situation is similar to Common Lisp: instead of atan2, the language has a one-parameter and a two-parameter form for atan. However, it has many more than two methods, to allow for aggressive optimisation at compile time.
* For systems implementing signed zero, infinities, or Not a Number (for example, IEEE floating point), it is common to implement reasonable extensions which may extend the range of values produced to include −π and −0 when y = −0. These also may return NaN or raise an exception when given a NaN argument.
* In the Intel x86 Architecture assembler code, atan2 is known as the FPATAN (floating-point partial arctangent) instruction. It can deal with infinities and results lie in the closed interval [−π, π], e.g. atan2(∞, x) = +π/2 for finite x. Particularly, FPATAN is defined when both arguments are zero:
    atan2(+0, +0) = +0;
    atan2(+0, −0) = +π;
    atan2(−0, +0) = −0;
    atan2(−0, −0) = −π.
    This definition is related to the concept of signed zero.
* In mathematical writings other than source code, such as in books and articles, the notations Arctan and Tan$^{−1}$ have been utilized; these are capitalized variants of the regular arctan and tan$^{−1}$. This usage is consistent with the complex argument notation, such that Atan(y, x) = Arg(x + i y).
* On HP calculators, treat the coordinates as a complex number and then take the ARG. Or << C->R ARG >> 'ATAN2' STO.
* On scientific calculators the function can often be calculated as the angle given when (x, y) is converted from rectangular coordinates to polar coordinates.
* Systems supporting symbolic mathematics normally return an undefined value for atan2(0, 0) or otherwise signal that an abnormal condition has arisen.
* The free math library FDLIBM (Freely Distributable LIBM) available from netlib has source code showing how it implements atan2 including handling the various IEEE exceptional values.
* For systems without a hardware multiplier the function atan2 can be implemented in a numerically reliable manner by the CORDIC method. Thus implementations of atan(y) will probably choose to compute atan2(y, 1).