The function first appeared in the programming language Fortran (in IBM's implementation FORTRAN-IV) 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, θ).
returns a single value such that and, for ,
If x > 0, the angle is given by:
However, when x < 0, the angle given by points in the direction opposite to the correct angle, and a value of ±π (or ±180°) must be added to θ to place the point in the correct quadrant of the Euclidean plane. This requires knowledge of the signs of x and y separately, which is lost when y is divided by x, hence the need for the two-variable arctangent.
Since any integer multiple of 2π can be added to the angle θ without changing either x or y, implying an ambiguous value for the returned value, the principal value of the angle, in the (left open, right closed) interval (−π, π] is returned. θ is signed, with counterclockwise angles being positive, and clockwise being negative. In other words, is in the closed interval [0, π] when y ≥ 0, and in the open interval (−π, 0) when y < 0.
History and motivationEdit
The atan2 function was first introduced in computer programming languages, but now it is also common in other fields of science and engineering. It dates back at least as far as the FORTRAN programming language
and is currently found in many modern programming languages. Among these languages are: C's math.h standard library, the Java Math library, .NET's System.Math (usable from C#, VB.NET, etc.), the Python math module, the Ruby Math module, the Go math package and elsewhere. In addition, many scripting languages, such as Perl, include the C-style
atan2(y, x) function.
The single-argument arctangent function cannot distinguish between diametrically opposite directions. For example, the anticlockwise angle from the x axis to the vector (1, 1), calculated in the usual way as arctan(1/1), is π/4 (radians), or 45°. However, the angle between the x axis and the vector (−1, −1) appears, by the same method, to be arctan(−1/−1), again π/4, even though one might expect the answers −3π/4 (−135°) or 5π/4 (225°). In addition, an attempt to find the angle between the x axis and the vectors (0, y), y ≠ 0 requires evaluation of arctan(y/0), which fails on division by zero.
The atan2 function calculates one unique arc tangent value from two variables y and x, where the signs of both arguments are used to determine the quadrant of the result, thereby selecting the desired branch of the arc tangent of y/x, e.g., atan2(1, 1) = π/4 and atan2(−1, −1) = −3π/4. Similarly, e.g., atan2(1, 0) = π/2.
When calculations are performed manually, the necessary quadrant corrections and exception handling can be done by inspection, but it is more useful to have a single function that always gives an unambiguous correct result. The atan2 function is useful in many applications involving vectors in Euclidean space, such as finding the direction from one point to another. A principal use is in computer graphics rotations, for converting rotation matrix representations into Euler angles.
- Historical remark
In 1961 the FORTRAN people have chosen the sequence of arguments although there is no doubt that the complex -plane resp. the -Cartesian plane is to be addressed and although the axis of positive reals resp. the -axis of this plane plays the prominent role of the so-called polar axis on whose points (characterized by and ) the so-called polar angle is 0 (see section Definition and computation).
But there are also programming languages (see § Realizations of the function in common computer languages) which preserve the standard sequence of arguments , e.g. Excel with and OpenOffice Calc with . In Mathematica there is a function defaulting the first argument to 1 if omitted.
Definition and computationEdit
The function atan2 computes the principal value of the argument function applied to the complex number x + i y. That is, atan2(y, x) = Pr arg(x + i y) = Arg(x + i y). The argument could be changed by an arbitrary multiple of 2π (corresponding to a complete turn around the origin) without making any difference to the angle, but to define atan2 uniquely one uses the principal value in the range , that is, −π < atan2(y, x) ≤ π.
In terms of the standard arctan function, whose range is (−π/2, π/2], it can be expressed as follows:
A compact expression with four overlapping half-planes is
The Iverson bracket notation allows for an even more compact expression:
Formula without apparent conditional construct:
The following expression derived from the tangent half-angle formula can also be used to define atan2:
A variant of the last formula that avoids these inflated rounding errors:
- This produces results in the range (−π, π].[note 2]
- As mentioned above, the principal value of the argument atan2(y, x) can be related to arctan(y/x) by trigonometry. The derivation goes as follows: If (x, y) = (r cos θ, r sin θ), then tan(θ/2) = y / (r + x). It follows that
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 for x > 0 or y ≠ 0,
Thus the gradient of atan2 is given by
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:
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.
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 along with for . Both functions are odd and periodic with periods and , respectively, and thus can easily be supplemented to any region of real values of . One can clearly see the branch cuts of the -function at , and of the -function at .
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 identityEdit
Sums of may be collapsed into a single operation according to the following identity
...provided that .
The proof involves considering two cases, one where or and one where and .
We only consider the case where or . To start, we make the following observations:
- provided that or .
- , where is the complex argument function.
- whenever , a consequence of Euler's formula.
To see (4), we have the identity where , hence . Furthermore, since for any positive real value , then if we let and then we have .
From these observations have following equivalences:
Corollary: if and are 2-dimensional vectors, the difference formula is frequently used in practice to compute the angle between those vectors with the help of , since the resulting computation behaves benign in the range and can thus be used without range checks in many practical situations.
East-counterclockwise, north-clockwise and south-clockwise conventions, etc.Edit
The 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 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:
- (East-Counterclockwise Convention)
- (North-Clockwise Convention)
- . (South-Clockwise Convention)
As an example, let and , then the east-counterclockwise format gives , the north-clockwise format gives , and the south-clockwise format gives .
Apparently, changing the sign of the x- and/or y-arguments and swapping their positions can create 8 possible variations of the 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 languagesEdit
The realization of the function differs from one computer language to another:
- In Microsoft Excel, OpenOffice.org Calc, LibreOffice Calc, Google Spreadsheets, iWork Numbers, and ANSI SQL:2008 standard, the 2-argument arctangent function has the two arguments in the standard sequence (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 .
- 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 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
atanfunction 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 (see the section "Why don't you compile Matlab/Python/R/… code to Julia?" ).
- 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 Architecture assembler code,
atan2is 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,
FPATANis 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
<< 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
atan2including 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).
- http://scipp.ucsc.edu/~haber/ph116A/arg_11.pdf[bare URL PDF]
- 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).
- "src/math/atan2.go". The Go Programming Language. Retrieved 20 April 2018.
- "Wolf Jung: Mandel, software for complex dynamics". www.mndynamics.com. Retrieved 20 April 2018.
- Wind Direction Quick Reference, NCAR UCAR Earth Observing Laboratory. https://www.eol.ucar.edu/content/wind-direction-quick-reference
- 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. doi:10.1016/j.renene.2021.03.047. S2CID 233631040.
- "Microsoft Excel Atan2 Method". Microsoft.
- "LibreOffice Calc ATAN2". Libreoffice.org.
- "Functions and formulas – Docs Editors Help". support.google.com.
- "Numbers' Trigonometric Function List". Apple.
- "ANSI SQL:2008 standard". Teradata. Archived from the original on 2015-08-20.
- "CLHS: Function ASIN, ACOS, ATAN". LispWorks.
- "Mathematics · The Julia Language". docs.julialang.org.
- "Frequently Asked Questions · The Julia Language". docs.julialang.org.
- IA-32 Intel Architecture Software Developer’s Manual. Volume 2A: Instruction Set Reference, A-M, 2004.
- 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.
- Glisson, Tildon H. (18 February 2011). Introduction to Circuit Analysis and Design. Springer Science & Business Media. ISBN 9789048194438. Retrieved 20 April 2018 – via Google Books.
- ATAN2 Online calculator
- Java 1.6 SE JavaDoc
- atan2 at Everything2
- PicBasic Pro solution atan2 for a PIC18F
- Other implementations/code for atan2
- "Bearing Between Two Points". Archived from the original on 18 November 2020. Retrieved 21 February 2022.
- "Arctan and Polar Coordinates". Archived from the original on 18 October 2018. Retrieved 21 February 2022.
- for every
- One can apply the periodicity of the result to map to another desired range, e.g. mapping to [0, 2π) by adding 2π to the negative results.