Atan2
   HOME

TheInfoList



OR:

In
computing Computing is any goal-oriented activity requiring, benefiting from, or creating computer, computing machinery. It includes the study and experimentation of algorithmic processes, and the development of both computer hardware, hardware and softw ...
and
mathematics Mathematics is a field of study that discovers and organizes methods, Mathematical theory, theories and theorems that are developed and Mathematical proof, proved for the needs of empirical sciences and mathematics itself. There are many ar ...
, the function atan2 is the 2-
argument An argument is a series of sentences, statements, or propositions some of which are called premises and one is the conclusion. The purpose of an argument is to give reasons for one's conclusion via justification, explanation, and/or persu ...
arctangent In mathematics, the inverse trigonometric functions (occasionally also called ''antitrigonometric'', ''cyclometric'', or ''arcus'' functions) are the inverse functions of the trigonometric functions, under suitably restricted domains. Specific ...
. By definition, \theta = \operatorname(y, x) is the
angle measure In Euclidean geometry, an angle can refer to a number of concepts relating to the intersection of two straight lines at a point. Formally, an angle is a figure lying in a plane formed by two rays, called the '' sides'' of the angle, sharing ...
(in
radian The radian, denoted by the symbol rad, is the unit of angle in the International System of Units (SI) and is the standard unit of angular measure used in many areas of mathematics. It is defined such that one radian is the angle subtended at ...
s, 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 In geometry, a Cartesian coordinate system (, ) in a plane is a coordinate system that specifies each point uniquely by a pair of real numbers called ''coordinates'', which are the signed distances to the point from two fixed perpendicular o ...
. Equivalently, \operatorname(y, x) is the
argument An argument is a series of sentences, statements, or propositions some of which are called premises and one is the conclusion. The purpose of an argument is to give reasons for one's conclusion via justification, explanation, and/or persu ...
(also called ''phase'' or ''angle'') of the
complex number In mathematics, a complex number is an element of a number system that extends the real numbers with a specific element denoted , called the imaginary unit and satisfying the equation i^= -1; every complex number can be expressed in the for ...
x + iy. (The ''argument'' of a function and the ''argument'' of a complex number, each mentioned above, should not be confused.) The \operatorname 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 to
polar coordinates In mathematics, the polar coordinate system specifies a given point (mathematics), point in a plane (mathematics), plane by using a distance and an angle as its two coordinate system, coordinates. These are *the point's distance from a reference ...
. If \theta = \operatorname(y, x) and r = \sqrt, then x = r \cos \theta and y = r \sin \theta. If , the desired angle measure is \theta = \operatorname(y,x) = \arctan\left( y / x \right). However, when , 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 \operatorname function does away with this correction, simplifying code and mathematical formulas.


Motivation

The ordinary single-argument
arctangent In mathematics, the inverse trigonometric functions (occasionally also called ''antitrigonometric'', ''cyclometric'', or ''arcus'' functions) are the inverse functions of the trigonometric functions, under suitably restricted domains. Specific ...
function only returns angle measures in the interval , and when invoking it to find the direction angle from the origin to an arbitrary point in the Cartesian plane, it will yield incorrect results when the point is in the left half-plane . 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 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 , and sometimes additional cases when is negative or one coordinate is zero. Finding angle measures and converting Cartesian to
polar coordinates In mathematics, the polar coordinate system specifies a given point (mathematics), point in a plane (mathematics), plane by using a distance and an angle as its two coordinate system, coordinates. These are *the point's distance from a reference ...
are common in scientific computing, and this code is redundant and error-prone. To save programmers the trouble, computer
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s introduced the function, at least as early as the Fortran IV language of the 1960s. The quantity is the angle measure between the -axis and a ray from the origin to a point anywhere in the Cartesian plane. The signs of and are used to determine the quadrant of the result and select the correct branch of the
multivalued function In mathematics, a multivalued function, multiple-valued function, many-valued function, or multifunction, is a function that has two or more values in its range for at least one point in its domain. It is a set-valued function with additional p ...
. The function is useful in many applications involving
Euclidean vector In mathematics, physics, and engineering, a Euclidean vector or simply a vector (sometimes called a geometric vector or spatial vector) is a geometric object that has magnitude (or length) and direction. Euclidean vectors can be added and scal ...
s such as finding the direction from one point to another or converting a
rotation matrix In linear algebra, a rotation matrix is a transformation matrix that is used to perform a rotation (mathematics), rotation in Euclidean space. For example, using the convention below, the matrix :R = \begin \cos \theta & -\sin \theta \\ \sin \t ...
to Euler angles. The 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 function with argument order so that the
argument An argument is a series of sentences, statements, or propositions some of which are called premises and one is the conclusion. The purpose of an argument is to give reasons for one's conclusion via justification, explanation, and/or persu ...
(phase angle) of a complex number is \operatornamez = \operatorname(\operatornamez, \operatornamez). This follows the left-to-right order of a fraction written y / x, so that \operatorname(y, x) = \operatorname(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 (\operatornamez, \operatornamez). 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 Microsoft Excel is a spreadsheet editor developed by Microsoft for Microsoft Windows, Windows, macOS, Android (operating system), Android, iOS and iPadOS. It features calculation or computation capabilities, graphing tools, pivot tables, and a ...
uses \operatorname(x,\,y), OpenOffice Calc uses \operatorname(x,\,y), and
Mathematica Wolfram (previously known as Mathematica and Wolfram Mathematica) is a software system with built-in libraries for several areas of technical computing that allows machine learning, statistics, symbolic computation, data manipulation, network ...
uses \operatorname ,y defaulting to one-argument arctangent if called with one argument.


Definition and computation

The function computes the principal
argument An argument is a series of sentences, statements, or propositions some of which are called premises and one is the conclusion. The purpose of an argument is to give reasons for one's conclusion via justification, explanation, and/or persu ...
of the
complex number In mathematics, a complex number is an element of a number system that extends the real numbers with a specific element denoted , called the imaginary unit and satisfying the equation i^= -1; every complex number can be expressed in the for ...
, which is also the imaginary part of the principal value of the
complex logarithm In mathematics, a complex logarithm is a generalization of the natural logarithm to nonzero complex numbers. The term refers to one of the following, which are strongly related: * A complex logarithm of a nonzero complex number z, defined to be ...
. That is, \operatorname(y, x) = \operatorname(x + iy) = \operatorname\operatorname(x + iy). Adding any integer multiple of (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 , can be expressed
piecewise In mathematics, a piecewise function (also called a piecewise-defined function, a hybrid function, or a function defined by cases) is a function whose domain is partitioned into several intervals ("subdomains") on which the function may be ...
: \operatorname(y, x) = \begin \arctan\left(\frac y x\right) &\text x > 0, \\ mu \arctan\left(\frac y x\right) + \pi &\text x < 0 \text y \ge 0, \\ mu \arctan\left(\frac y x\right) - \pi &\text x < 0 \text y < 0, \\ mu +\frac &\text x = 0 \text y > 0, \\ mu -\frac &\text x = 0 \text y < 0, \\ mu \text &\text x = 0 \text y = 0. \end Instead of the tangent, it can be convenient to use the half-tangent as a representation of an angle, partly because the angle has a unique half-tangent, \tan\tfrac12\theta = \frac = \frac. (See tangent half-angle formula.) The expression with in the denominator should be used when and to avoid possible loss of significance in computing . When an function is unavailable, it can be computed as twice the arctangent of the half-tangent . That is, \operatorname(y, x) = 2 \arctan \left(\frac\right) = 2 \arctan \left( \frac \right)\,.


Derivative

As the function is a function of two variables, it has two
partial derivative In mathematics, a partial derivative of a function of several variables is its derivative with respect to one of those variables, with the others held constant (as opposed to the total derivative, in which all variables are allowed to vary). P ...
s. At points where these derivatives exist, is, except for a constant, equal to . Hence, : \begin & \frac\operatorname(y,\, x) = \frac \arctan\left(\frac y x \right) = -\frac, \\ pt& \frac\operatorname(y,\, x) = \frac \arctan\left(\frac y x \right) = \frac x . \end Thus the
gradient In vector calculus, the gradient of a scalar-valued differentiable function f of several variables is the vector field (or vector-valued function) \nabla f whose value at a point p gives the direction and the rate of fastest increase. The g ...
of atan2 is given by :\nabla \text(y,x)=\left(, \ \right). Informally representing the function as the angle function (which is only defined up to a constant) yields the following formula for the
total differential In calculus, the differential represents the principal part of the change in a function y = f(x) with respect to changes in the independent variable. The differential dy is defined by dy = f'(x)\,dx, where f'(x) is the derivative of with resp ...
: :\begin \mathrm\theta &= \frac\operatorname(y,\, x)\,\mathrmx + \frac\operatorname(y,\, x)\,\mathrmy \\ pt&= -\frac\,\mathrmx + \frac\,\mathrmy. \end While the function is discontinuous along the negative -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 mathematics, the winding number or winding index of a closed curve in the plane (mathematics), plane around a given point (mathematics), point is an integer representing the total number of times that the curve travels counterclockwise aroun ...
. In the language of
differential geometry Differential geometry is a Mathematics, mathematical discipline that studies the geometry of smooth shapes and smooth spaces, otherwise known as smooth manifolds. It uses the techniques of Calculus, single variable calculus, vector calculus, lin ...
, this derivative is a
one-form In differential geometry, a one-form (or covector field) on a differentiable manifold is a differential form of degree one, that is, a smooth section of the cotangent bundle. Equivalently, a one-form on a manifold M is a smooth mapping of the to ...
, 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 In mathematics, de Rham cohomology (named after Georges de Rham) is a tool belonging both to algebraic topology and to differential topology, capable of expressing basic topological information about smooth manifolds in a form particularly adapte ...
of the
punctured plane In topology, puncturing a manifold is removing a finite set of points from that manifold. The set of points can be small as a single point. In this case, the manifold is known as once-punctured. With the removal of a second point, it becomes twice ...
. This is the most basic example of such a form, and it is fundamental in differential geometry. The partial derivatives of 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 Two-dimensional rotation can occur in two possible directions or senses of rotation. Clockwise motion (abbreviated CW) proceeds in the same direction as a clock's hands relative to the observer: from the top to the right, then down and then to ...
from zero along the ray to the right. Note that the order of arguments is reversed; the function computes the angle corresponding to the point . This figure shows the values of \arctan(\tan(\theta)) along with \operatorname (\sin(\theta),\cos(\theta)) for 0\le \theta \le 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 cut In the mathematical field of complex analysis, a branch point of a multivalued function is a point such that if the function is n-valued (has n values) at that point, all of its neighborhoods contain a point that has more than n values. Multi-valu ...
s of the \operatorname -function at \theta = \pi, and of the \arctan-function at \theta \in \. The two figures below show 3D views of respectively and over a region of the plane. Note that for , ''rays'' in the ''X''/''Y''-plane emanating from the origin have constant values, but for ''lines'' in the ''X''/''Y''-plane passing through the origin have constant values. For , the two diagrams give identical values.


Angle sum and difference identity

The sum or difference of multiple angles to be computed by can alternately be computed by composing them as
complex number In mathematics, a complex number is an element of a number system that extends the real numbers with a specific element denoted , called the imaginary unit and satisfying the equation i^= -1; every complex number can be expressed in the for ...
s. Given two coordinate pairs and , their angles from the positive axis will be composed (and lengths multiplied) if they are treated as complex numbers and then multiplied together, . The resulting angle can be found using a single operation, so long as the as long as the resulting angle lies in : :\operatorname (y_1, x_1) \pm \operatorname (y_2, x_2) = \operatorname (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 -axis (i.e. exceeds the range ), then the crossings can be counted and the appropriate integer multiple of added to the final result to correct it. This difference formula is frequently used in practice to compute the angle between two planar
vector Vector most often refers to: * Euclidean vector, a quantity with a magnitude and a direction * Disease vector, an agent that carries and transmits an infectious pathogen into another living organism Vector may also refer to: Mathematics a ...
s, since the resulting angle is always in the range .


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

The \mathrm 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 Wind direction is generally reported by the direction from which the wind originates. For example, a ''north'' or ''northerly'' wind blows from the north to the south; the exceptions are onshore winds (blowing onto the shore from the water) and ...
can be calculated using the \mathrm 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(y,\,x),\;\;\;\;\; (East-Counterclockwise Convention) * \mathrm(x,\,y),\;\;\;\;\; (North-Clockwise Convention) * \mathrm(,\,). (South-Clockwise Convention) As an example, let x_=\frac and y_=\frac, then the east-counterclockwise format gives \mathrm(y_, x_)\cdot\frac=30^, the north-clockwise format gives \mathrm(x_, y_)\cdot\frac=60^, and the south-clockwise format gives \mathrm(-x_, -y_)\cdot\frac=-120^. Changing the sign of the x- and/or y-arguments and/or swapping their positions can create 8 possible variations of the \mathrm function and they, interestingly, correspond to 8 possible definitions of the angle, namely, clockwise or counterclockwise starting from each of the 4
cardinal direction The four cardinal directions or cardinal points are the four main compass directions: north (N), south (S), east (E), and west (W). The corresponding azimuths ( clockwise horizontal angle from north) are 0°, 90°, 180°, and 270°. The ...
s, 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 Microsoft Excel is a spreadsheet editor developed by Microsoft for Microsoft Windows, Windows, macOS, Android (operating system), Android, iOS and iPadOS. It features calculation or computation capabilities, graphing tools, pivot tables, and a ...
, OpenOffice.org Calc,
LibreOffice Calc LibreOffice Calc is the spreadsheet component of the LibreOffice suite. After forking from OpenOffice.org in 2010, LibreOffice Calc underwent a massive re-work of external reference handling to fix many defects in formula calculations involvi ...
, Google Spreadsheets, and iWork Numbers, the 2-argument arctangent function has the two arguments in the standard sequence (\operatorname, \operatorname) (reversed relative to the convention used in the discussion above). * In
Mathematica Wolfram (previously known as Mathematica and Wolfram Mathematica) is a software system with built-in libraries for several areas of technical computing that allows machine learning, statistics, symbolic computation, data manipulation, network ...
, the form ArcTan 'x'',''y''/code> is used where the one parameter form supplies the normal arctangent. Mathematica classifies ArcTan ,0/code> as an indeterminate expression. * On most TI graphing calculators (excluding the
TI-85 The TI-85 is a graphing calculator made by Texas Instruments based on the Zilog Z80 microprocessor. Designed in 1992 as TI's second graphing calculator (the first was the TI-81), it was replaced by the TI-86, which has also been discontinued. ...
and TI-86), the equivalent function is called R►Pθ and has the arguments (\operatorname, \operatorname). * On TI-85 the 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: . The (\operatorname, \operatorname) 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 Signed zero is zero with an associated sign. In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are equivalent. However, in computing, some number representations allow for the existence of two zeros, often denoted by ...
, 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 Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
, 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. * Mathcad uses the argument order atan2(x, y). atan2(0, 0) is undefined. * For systems implementing
signed zero Signed zero is zero with an associated sign. In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are equivalent. However, in computing, some number representations allow for the existence of two zeros, often denoted by ...
, infinities, or Not a Number (for example,
IEEE floating point The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point arithmetic originally established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard addressed many probl ...
), it is common to implement reasonable extensions which may extend the range of values produced to include − and −0 when = −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 Signed zero is zero with an associated sign. In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are equivalent. However, in computing, some number representations allow for the existence of two zeros, often denoted by ...
. * 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 . * 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 is converted from
rectangular coordinates In geometry, a Cartesian coordinate system (, ) in a plane is a coordinate system that specifies each point uniquely by a pair of real numbers called ''coordinates'', which are the signed distances to the point from two fixed perpendicular o ...
to
polar coordinates In mathematics, the polar coordinate system specifies a given point (mathematics), point in a plane (mathematics), plane by using a distance and an angle as its two coordinate system, coordinates. These are *the point's distance from a reference ...
. * Systems supporting symbolic mathematics normally return an undefined value for or otherwise signal that an abnormal condition has arisen. * The free math library FDLIBM (Freely Distributable LIBM) available from
netlib Netlib is a repository of software for scientific computing maintained by AT&T, Bell Laboratories, the University of Tennessee and Oak Ridge National Laboratory. Netlib comprises many separate programs and libraries. Most of the code is written in ...
has source code showing how it implements atan2 including handling the various IEEE exceptional values. * For systems without a hardware multiplier the function can be implemented in a numerically reliable manner by the
CORDIC CORDIC, short for coordinate rotation digital computer, is a simple and efficient algorithm to calculate trigonometric functions, hyperbolic functions, square roots, multiplications, divisions, and exponentials and logarithms In ma ...
method. Thus implementations of will probably choose to compute .


See also

* hypot


References


External links


ATAN2 Online calculator



atan2
at
Everything2 Everything2 (styled Everything2 or E2 for short) is a collaborative online community consisting of a database of interlinked user-submitted written material. E2 is moderated for quality, but has no formal policy on subject matter. Writing on E ...

PicBasic Pro solution
atan2 for a PIC18F ;Other implementations/code for atan2 * * *


Notes

{{Trigonometric and hyperbolic functions Inverse trigonometric functions