Roots of unity: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|J}}: format fiddling)
m (=={{header|ALGOL 68}}==)
Line 5: Line 5:
Given<tt> n</tt> ,<tt> </tt>find the<tt> n</tt>-th
Given<tt> n</tt> ,<tt> </tt>find the<tt> n</tt>-th
[http://en.wikipedia.org/wiki/Roots_of_unity roots of unity].
[http://en.wikipedia.org/wiki/Roots_of_unity roots of unity].
=={{header|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


=={{header|J}}==
=={{header|J}}==

Revision as of 12:04, 13 December 2007

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
)