Version 8 of Converting between rectangular and polar co-ordinates

Updated 2008-04-25 00:53:21 by andy

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} {
     list [expr {hypot($y, $x)}]\
          [expr {atan2($y, $x)}]
 }

 lassign [rect_to_polar $x $y] r theta 

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} {
     list [expr {$r * cos($theta)}]\
          [expr {$r * sin($theta)}]
 }

 lassign [polar_to_rect $r $theta] x y

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


KPV - Hey, I'll take up the hard task of converting cylindrical (r, theta, z) to rectangular (x, y, z).

 proc rect_to_cylindrical {x y z} {
    list {*}[rect_to_polar $x $y] $z
 }
 proc cylindrical_to_rect {r theta z} {
    list {*}[polar_to_rect $r $theta] $z
 }