Version 4 of Converting between rectangular and polar co-ordinates

Updated 2002-10-24 12:20:44

Purpose: Show how to convert between rectangular and polar co-ordinates in Tcl.


If you have rectangular co-ordinates $x and $y, and you need polar co-ordinates $r and $theta, you can use the following:

 proc rect_to_polar { x y } {
     set r [expr { hypot( $x, $y ) }]
     set theta [expr { atan2( $y, $x ) }]
     return [list $r $theta]
 }

 foreach { r theta } [rect_to_polar $x $y] break

Note the use of hypot and atan2 in the code above. These functions are much more robust than any corresponding code using atan and sqrt.


If you have polar co-ordinates $r and $theta, and you need rectangular co-ordinates $x and $y, you can use the following:

 proc polar_to_rect { r theta } {
     set x [expr { $r * cos($theta) }]
     set y [expr { $r * sin($theta) }]
     return [list $x $y]
 }

 foreach { x y } [polar_to_rect $r $theta] break

[Next up: three-dimensional (x, y, z) <-> (r, theta, phi) Maybe cylindrical, after that ...]


Category Mathematics