Version 5 of atan2

Updated 2003-04-13 19:44:57

Purpose: Help on the math function 'atan2'.


The call

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

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

    ( $x / $y )

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 practise, 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!


The commonest use of [atan2] is in Converting between rectangular and polar co-ordinates.


atan2 is also available as a command in Tclx.


Category Mathematics | Math function help