Roots of unity

From Rosetta Code
Revision as of 16:15, 13 December 2007 by rosettacode>Goku Sama (→‎{{header|Python}}: add Python)
Task
Roots of unity
You are encouraged to solve this task according to the task description, using any language you may know.

The purpose of this task is to explore working with complex numbers. Given n , find the n-th roots of unity.

ALGOL 68

FOR root FROM 2 TO 10 DO
  printf(($g(4)$,root));
  FOR n TO root -1 DO
    printf(($xg(5,3)g(5,3)"i"$,complex exp( 0 I 2*pi*n/root)))
  OD;
  printf($l$)
OD

Output:

 +2 -1.00+.000i
 +3 -.500+.866i -.500-.866i
 +4 +.000+1.00i -1.00+.000i -.000-1.00i
 +5 +.309+.951i -.809+.588i -.809-.588i +.309-.951i
 +6 +.500+.866i -.500+.866i -1.00+.000i -.500-.866i +.500-.866i
 +7 +.623+.782i -.223+.975i -.901+.434i -.901-.434i -.223-.975i +.623-.782i
 +8 +.707+.707i +.000+1.00i -.707+.707i -1.00+.000i -.707-.707i -.000-1.00i +.707-.707i
 +9 +.766+.643i +.174+.985i -.500+.866i -.940+.342i -.940-.342i -.500-.866i +.174-.985i +.766-.643i
+10 +.809+.588i +.309+.951i -.309+.951i -.809+.588i -1.00+.000i -.809-.588i -.309-.951i +.309-.951i +.809-.588i

J

   rou=: [: ^ i. * (o. 0j2) % ]

   rou 4
1 0j1 _1 0j_1

   rou 5
1 0.309017j0.951057 _0.809017j0.587785 _0.809017j_0.587785 0.309017j_0.951057

The computation can also be written as a loop, shown here for comparison only.

rou1=: 3 : 0
 z=. 0 $ r=. ^ o. 0j2 % y [ e=. 1
 for. i.y do.
  z=. z,e
  e=. e*r
 end.
 z
)

Python

Interpreter: Python 2.5 Function nthroots() returns all n-th roots of unity.

from cmath import exp, pi
def nthroots(n):
    return [exp(k * 2j * pi / n) for k in range(1, n + 1)]

Example:

>>> f = nthroots
>>> for n in range(1, 4):
...    print map(lambda c: ("%.3f " + ("+" if c.imag > 0 else "-") + " %.3gj") % (c.real, abs(c.imag)), f(n))
['1.000 - 2.45e-016j']
['-1.000 + 1.22e-016j', '1.000 - 2.45e-016j']
['-0.500 + 0.866j', '-0.500 - 0.866j', '1.000 - 2.45e-016j']