Atan2

atan2(y, x) returns the angle θ between the positive x-axis and the ray from the origin to the point (x, y), confined to (−π, π].
Graph of atan2⁡(y,x) over y/x

In computing and mathematics, the function atan2 is the 2-argument arctangent. By definition, θ=atan2⁡(y,x) is the angle measure between the positive x-axis and the ray from the origin to the point (x,y) in the Cartesian plane, measured in radians with −π<θ≤π. Equivalently, 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.)

If the ⁠x⁠ coordinate is a positive number, the desired angle measure can be found using the ordinary (1-argument) arctangent function, ⁠θ=atan2⁡(y,x)=arctan⁡(y/x)⁠. However, when ⁠x⁠ is negative, the angle arctan⁡(y/x) is diametrically opposite the desired angle, and ⁠±π⁠ (a half turn) must be added to place the point in the correct quadrant. Using the atan2 function does away with this correction, simplifying code and mathematical formulas.

The 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 ⁠θ⁠ in converting from Cartesian coordinates ⁠(x,y)⁠ to polar coordinates ⁠(r,θ)⁠. If θ=atan2⁡(y,x) and r=x2+y2, then x=rcos⁡θ and ⁠y=rsin⁡θ⁠.

Motivation

It is common in practical applications of geometry to convert between rectangular coordinates ⁠(x,y)⁠ and polar coordinates ⁠(r,θ)⁠ for representing points in the Euclidean plane, for example to find the signed angle representing the orientation of a vector or to calculate the argument of a complex number. The relationships between rectangular and polar coordinates can be summarized by the equations: x=rcos⁡θ,r=x2+y2,y=rsin⁡θ,tan⁡θ=yx, where ⁠sin⁠, ⁠cos⁠, and ⁠tan⁠ are trigonometric functions and ⁠x2+y2⁠ is the Pythagorean sum of ⁠x⁠ and ⁠y⁠, i.e. the hypotenuse of a right triangle with legs ⁠x⁠ and ⁠y⁠.

Graph of the tangent function from −π to +π with the corresponding signs of y/x. The green arrows point to the results of atan2(−1, −1) and atan2(1, 1).

Computing ⁠x⁠ and ⁠y⁠ from ⁠r⁠ and ⁠θ⁠ directly from these formulas is straightforward. In the other direction, though, it is helpful to provide special functions to implement the conversions. The formula to compute ⁠r⁠ from ⁠x⁠ and ⁠y⁠ can lead to numerical overflows and underflows, avoided by the hypot function of many standard libraries. The computation of ⁠θ⁠ from ⁠x⁠ and ⁠y⁠ is more complicated, for two reasons: (1) because it could involve a division by zero and (2) because the quotient ⁠y/x⁠ is equal to ⁠(−y)/(−x)⁠, and therefore does not distinguish between point ⁠(x,y)⁠ and the opposite point ⁠(−x,−y)⁠. The ordinary single-argument arctangent function only returns angle measures in the interval ⁠(−12π,12π)⁠, so a naïve implementation of a conversion from rectangular to polar coordinates, ⁠θ=arctan⁡(y/x)⁠, will yield incorrect results whenever ⁠x≤0⁠.

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.

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 ⁠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 ⁠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 ⁠arg⁡z=atan2⁡(Im⁡z,Re⁡z)⁠. This follows the left-to-right order of a fraction written ⁠y/x⁠, so that atan2⁡(y,x)=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 ⁠(Re⁡z,Im⁡z)⁠. Some other programming languages and environments, especially spreadsheet software, picked the opposite argument order ⁠atan2⁡(x,y)⁠. See § Availability in common computer languages below.

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, atan2⁡(y,x)=arg⁡(x+iy)=Im⁡log⁡(x+iy).

Adding any integer multiple of ⁠2π⁠ (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 ⁠(−π,π]⁠.

In terms of the standard arctangent function, whose image is ⁠(−12π,12π)⁠, atan2 can be expressed piecewise: atan2⁡(y,x)={arctan⁡(yx)if x>0,arctan⁡(yx)+πif x<0 and y≥0,arctan⁡(yx)−πif x<0 and y<0,+π2if x=0 and y>0,−π2if x=0 and y<0,undefinedif x=0 and y=0.

The tangent of half an angle can be computed in terms of coordinates x and y and radius r.

In some contexts, a nonnegative angle ⁠θ⁠ in the interval ⁠[0,2π)⁠ is needed instead of a signed angle in the interval ⁠(−π,π]⁠. It can be obtained from atan2 by use of the formula θ=π−atan2⁡(y,−x).

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, ∂∂xatan2⁡(y,x)=∂∂xarctan⁡(yx)=−yx2+y2,∂∂yatan2⁡(y,x)=∂∂yarctan⁡(yx)=xx2+y2. These two partial derivatives are the coordinates of the gradient.

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: dθ=∂∂xatan2⁡(y,x)dx+∂∂yatan2⁡(y,x)dy=−yx2+y2dx+xx2+y2dy.

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

atan2 for selected rays

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).

Comparison of arctan and atan2 functions

This figure shows the values of arctan⁡(tan⁡(θ)) along with atan2⁡(sin⁡(θ),cos⁡(θ)) for 0≤θ≤2π. Both functions are odd and periodic with periods π and 2π, respectively, and thus can easily be supplemented to any region of real values of θ. One can clearly see the branch cuts of the atan2-function at θ=π, and of the arctan-function at θ∈{π2,3π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 ⁠atan2⁠ can alternately be computed by composing them as complex numbers. Given two coordinate pairs ⁠(x1,y1)⁠ and ⁠(x2,y2)⁠, their angles from the positive ⁠x⁠ axis will be composed (and lengths multiplied) if they are treated as complex numbers and then multiplied together, ⁠(x1+iy1)(x2+iy2)=⁠⁠(x1x2−y1y2)+i(y1x2+x1y2)⁠. The resulting angle can be found using a single ⁠atan2⁠ operation, so long as the resulting angle lies in ⁠(−π,π]⁠: atan2⁡(y1,x1)±atan2⁡(y2,x2)=atan2⁡(y1x2±x1y2,x1x2∓y1y2), and likewise for more than two coordinate pairs. If the composed angle crosses the negative ⁠x⁠-axis (i.e. exceeds the range ⁠(−π,π]⁠), then the crossings can be counted and the appropriate integer multiple of ⁠2π⁠ 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 ⁠(−π,π]⁠.

North-clockwise and south-clockwise conventions

The atan2 function gives an angle starting from the ⁠x⁠-axis as zero, with positive angles in the direction of the ⁠y⁠-axis, measured in radians. Conventionally in mathematics the ⁠x⁠-axis is drawn pointing to the right and the ⁠y⁠-axis is drawn pointing upwards. If such a coordinate system is applied to a map where north faces upward, this can be called the east-counterclockwise convention: an angle of ⁠0⁠ represents due east and an angle of ⁠π2⁠ or ⁠90∘⁠ represents due north.

However, in many practical applications angles are conventionally measured starting from a different reference direction or in the opposite sense. In navigation, astronomy, geodesy, meteorology, and related fields, the azimuth (horizontal angle) is commonly measured as a clockwise angle relative to due north (the north-clockwise convention) or sometimes as a clockwise angle relative to due south (the south-clockwise convention). These alternative angles can be computed from Cartesian coordinates using the atan2 function by exchanging the function arguments or flipping their signs. If the east–west component of a vector is denoted ⁠x⁠ and the north–south component is denoted ⁠y⁠, then its clockwise azimuth angle relative to north is ⁠atan2⁡(x,y)⁠, and its clockwise azimuth angle relative to south is ⁠atan2⁡(−x,−y)⁠.

If the angle should be measured in degrees instead of radians, the radian angle can be multiplied by ⁠180∘/π⁠. If a nonnegative angle in the interval ⁠[0,2π)⁠ or ⁠[0∘,360∘)⁠ is needed, instead of a signed angle, it can be calculated by replacing ⁠atan2⁡(y,x)⁠ with ⁠π−atan2⁡(y,−x)⁠.

Availability in common computer languages

The realization of the function differs from one computer language to another.

Argument order

There are two main choices for the argument order. The atan2(y, x) order, as used in the article, is most common. It originated in Fortran and was later adopted by the IEEE 754 floating-point standard. This convention is found in C mathematical functions, Mathcad, and most programming languages. Some programming languages support functions with optional arguments. In some of these an atan function behaves as either the ordinary single-argument arctangent or as the two-argument arctangent, depending on how it is called. This is the case in Common Lisp and Julia.

The opposite argument order, atan2(x, y) is used by Microsoft Excel and most other spreadsheet software. In Mathematica, the ArcTan function operates as either a 1-argument or 2-argument arctangent, using the order ArcTan[x,y] for the latter; ArcTan[0,0] is classified as an indeterminate expression.

On scientific calculators, the function can often be calculated as the angle given when (x, y) is converted from rectangular coordinates to polar coordinates. On HP calculators, the ARG function returns the argument of a complex number. On TI graphing calculators, the equivalent function is called R►Pθ or angle, and can take a vector (x, y) or a complex number input.

In written mathematical sources, the notations Arctan(y, x) and Tan−1(y, x) have occasionally been used: capitalized variants of the usual notations for arctangent.

Boundary handling

In the arithmetic of real numbers, zero has no sign and is its own additive inverse, ⁠0=−0⁠, and the ratio ⁠0:0⁠ is not well defined. The origin ⁠(0,0)⁠ is a singularity of a polar coordinate system which can be considered to have any angle or no angle. The zero vector does not have a meaningful direction, and the complex number ⁠0+0i⁠ does not have a well-defined argument. Symbolic arithmetic systems typically implement ⁠atan2⁡(y,x)⁠ to be undefined when ⁠x=y=0⁠.

However, in common approximate computer arithmetic systems there are two distinct zeros, ⁠+0⁠ and ⁠−0⁠, which are used not only to represent zero per se but also unrepresentably small numbers (arithmetic underflow). In most programming languages, which use IEEE 754 floating-point arithmetic, ⁠atan2⁡(y,x)⁠ is given a value even at the origin. IEEE 754 arithmetic also includes NaN ("not a number") values and signed infinity (which is used for unrepresentably large numbers). A summary of the behavior required by the IEEE 754 standard for the atan2 function is as follows, where the values ⁠X⁠ and ⁠Y⁠ are finite and nonnegative (⁠+0≤X<∞⁠ and ⁠+0≤Y<∞⁠), and where ⁠π⁠ is the closest representable floating point number to the real number ⁠π⁠: atan2⁡(±0,+X)=atan2⁡(±Y,+∞)=±0,atan2⁡(±0,−X)=atan2⁡(±Y,−∞)=±π,atan2⁡(±∞,+Y)=atan2⁡(±∞,−Y)=±π/2,atan2⁡(±∞,+∞)=±π/4,atan2⁡(±∞,−∞)=±3π/4. If either argument is NaN, the result is NaN. Most computer floating-point implementations of atan2 follow this standard.

Implementation

The free math library FDLIBM (Freely Distributable LIBM) available from netlib has source code showing how it implements atan2: it first handles exceptional values, then delegates the calculation to atan(|y/x|) (with appropriate post-processing for sign and range). Newer open-source libm implementations are also available online.

In cases where the atan2 function is unavailable or inconvenient to use, and where reducing the number of cases that must be considered is important (e.g. for vectorized computations on a GPU), it can be useful to compute atan2 through a tangent half-angle formula:

atan2⁡(y,x)=2arctan⁡(yx2+y2+x), except in the case that ⁠x<0⁠ and ⁠y=0⁠, when by convention atan2 is equal to ⁠π⁠. (This option proved not as fast as using direct branching on the microcontroller tested, however. Most GPUs have a dedicated instruction for atan2, making this approach useless.)

For systems without a hardware multiplier, the function atan2 can be implemented in a numerically reliable manner by the CORDIC method.

See also

References

  1. ↑ "The argument of a complex number" (PDF). Santa Cruz Institute for Particle Physics. Winter 2011.
  2. ↑ Organick, Elliott I. (1966). A FORTRAN IV Primer. Addison-Wesley. p. 42. Some processors also offer the library function called ATAN2, a function of two arguments (opposite and adjacent).
  3. ↑ "Wolf Jung: Mandel, software for complex dynamics". www.mndynamics.com. Retrieved 20 April 2018.
  4. ↑ "Wind Direction Quick Reference". NCAR UCAR Earth Observing Laboratory.
  5. ↑ Zhang, Taiping; Stackhouse, Paul W.; MacPherson, Bradley; Mikovitz, J. Colleen (2021). "A solar azimuth formula that renders circumstantial treatment unnecessary without compromising mathematical rigor: Mathematical setup, application and extension of a formula based on the subsolar point and atan2 function". Renewable Energy. 172: 1333–1340. Bibcode:2021REne..172.1333Z. doi:10.1016/j.renene.2021.03.047. S2CID 233631040.
  6. ↑ "Mathcad help - Polar Angles". PTC.
  7. ↑ "CLHS: Function ASIN, ACOS, ATAN". LispWorks.
  8. ↑ "Microsoft Excel Atan2 Method". Microsoft. 14 June 2014.
  9. ↑ Burger, Wilhelm; Burge, Mark J. (7 July 2010). Principles of Digital Image Processing: Fundamental Techniques. Springer Science & Business Media. ISBN 978-1-84800-191-6. Retrieved 20 April 2018 – via Google Books.
  10. ↑ Glisson, Tildon H. (18 February 2011). Introduction to Circuit Analysis and Design. Springer Science & Business Media. ISBN 978-90-481-9443-8. Retrieved 20 April 2018 – via Google Books.
  11. ↑ Sun Microsystems (1993). "fdlibm/e_atan2.c". netlib.org.
  12. 1 2 Kusaka, Takashi; Tanaka, Takayuki (2022-07-22). "Fast and Accurate Approximation Methods for Trigonometric and Arctangent Calculations for Low-Performance Computers". Electronics. 11 (15): 2285. doi:10.3390/electronics11152285. hdl:2115/86726. ISSN 2079-9292.
  13. ↑ "Magnitude, and the Angle Nobody Mentions". GPU.js. atan2 is a hardware instruction's worth of work on every GPU: CUDA has atan2f (and __fdividef for the cheap path), WGSL and Metal both spell it atan2, and gpu.js compiles Math.atan2 straight to GLSL's atan(y, x). OpenCV's cv::Canny famously avoids it altogether — it compares |gy| against tan(22.5°)·|gx| with integer arithmetic — which is the same quantisation you are about to write, with the trigonometry folded away.

Other implementations/code for atan2

Notes