Version 9 of atan2

Updated 2008-04-28 10:13:09 by Geoffm

Purpose: Help on the math function 'atan2'.


The call

    [expr {atan2($y, $x)}]

returns the inverse tangent (expressed in radians) of the quantity,

    ($y / $x)

It never divides by zero, and is careful about the quadrant of the result (which conventional atan() can't be, since the division prior to feeding the quotient into atan() would lose information about which, if any, of $x and $y are negative. In practice, this doubles the range of the result.)


RS notes (testing functional imaging): Contrary to the above claim, on Sun computers the call atan2(0,0) raises the error:

 % expr atan2(0,0)
 domain error: argument not in valid range

Fix: check that at least one coordinate is non-zero:

 proc toPolars p {
    foreach {x y} $p break
    # for Sun, we have to make sure atan2 gets no two 0's
    list [expr {hypot($x,$y)}] [expr {$x||$y? atan2($y,$x): 0}]
 }

Arjen Markus I tested this feature in a small C program on an HPUX and a SGI machine with native compilers. The results were quite similar:

  • HPUX reports a Nan and errno = 0
  • SGI reports a value 0.0 and a Domain error.

Tcl 8.3.1 on SGI responds with a domain error as well, so that is quite consistent!

AMG: GNU (glibc) atan2() is defined [L1 ] to return 0 when both arguments are 0.


The most common use of atan2 is in Converting between rectangular and polar co-ordinates.


atan2 is also available as a command in Tclx.


AM (28 april 2008) Interesting feature:

  • atan2(y,x) will give the mathematical angle, that is, the angle with the positive x axis, oriented counter-clockwise
  • atan2(x,y) (so the arguments in just the opposite order) will give the nautical angle, that is, the angle with the positive y-axis, oriented clockwise (or if you like: the angle on the compass)

GWM (28 april 2008) note that Excel uses the reverse convention from C, Fortran, Tcl (and probably most other languages),

 atan2(0,1) = 0; atan2(1,0) = 1.570796 etc. Have all other spreadsheets been infected by Excel? Does SLK insist on Excel ordered atan2?

Take care when translating a formula that works in Excel to other languages (and vice versa).