to ← {dirn←1} ##.polar fm ⍝ Polar from/to cartesian coordinates. [to] and [fm] are corresponding arrays of shape (2,S), where pairs along the first axis represent either cartesian or polar coordinates. Coordinate pairs are arranged along the _first_ axis. The optional left argument determines the direction of translation: 1 polar ... ⍝ polar from cartesian coordinates. ¯1 polar ... ⍝ cartesian from polar coordinates. NB: The phase angle for polar coordinates is in the range: ○0 2. NB: The polar equivalent of cartesian (0 0) is undefined. This implementation arbitrarily chooses to map it to (0, ○1). Technical notes: ¯1∘polar is straightforward but 1∘polar has a couple of tricky areas. In general, the phase angle for cartesian (x y) is (¯3○y÷x). However, if x=0, a domain error is generated, so we must take steps to avoid such values: atan←¯3○y÷x+x=0 ⍝ arctan y÷x (avoiding y÷0). and to return results ○1÷2 and ○3÷2 for +ive and -ive values of y, respectively. Secondly, ¯3○ returns values in the range ○÷¯2 2 (+/- pi-by-two). Using the sign of the cartesian coodinates, we map this value onto a range 0 ≤< ○2. ┌────┬────┬────┐ y>0│a+○1│○1÷2│ a │ where a←¯3○y÷x ├────┼────┼────┤ y=0│a+○1│(○1)│ a │ ├────┼────┼────┤ y<0│a+○1│○3÷2│a+○2│ └────┴────┴────┘ x<0 x=0 x>0 Ref: http://en.wikipedia.org/wiki/Polar_coordinates Examples: cmpts ← ⍉↑ ¯1 0 1∘.,1 0 ¯1 ⍝ compass points. ⍴cmpts ⍝ 3×3 array of coordinate pairs. 2 3 3 ⊂[⎕io] cmpts ┌─────┬────┬────┐ │¯1 1 │0 1 │1 1 │ ├─────┼────┼────┤ │¯1 0 │0 0 │1 0 │ ├─────┼────┼────┤ │¯1 ¯1│0 ¯1│1 ¯1│ └─────┴────┴────┘ 0 3⍕polar cmpts ⍝ polar from cartesian. 1.414 1.000 1.414 1.000 0.000 1.000 1.414 1.000 1.414 2.356 1.571 0.785 3.142 3.142 0.000 3.927 4.712 5.498 polar 0 0 ⍝ singularity at 0 0 0 3.141592654 ¯1 polar polar 0 0 ⍝ round-trip awkward case. 0 0 rnd ← {(10*-⍺)×⌊0.5+⍵×10*⍺} ⍝ rounding to ⍺ decimal places. cmpts ≡ 6 rnd ¯1 polar polar cmpts ⍝ round-trip within 6 dec places. 1 See also: cxdraw Back to: contents Back to: Workspaces