Roots of unity

From Rosetta Code
Revision as of 16:15, 14 December 2007 by rosettacode>Mwn3d (Added Java example.)
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
)

Java

Java doesn't have a nice way of dealing with complex numbers, so the real and imaginary parts are calculated separately based on the angle and printed together. There are also checks in this implementation to get rid of extremely small values (< 1.0E-15). Instead, they are simply represented as 0. To remove those checks (for very high n's), remove both if statements.

public static void unity(int n){
	//all the way around the circle at even intervals
	for(double angle = 0;angle < 2 * Math.PI;angle += (2 * Math.PI) / n){
		double real = Math.cos(angle); //real axis is the x axis
		if(Math.abs(real) < 1.0E-15) real = 0.0; //get rid of annoying sci notation
		double imag = Math.sin(angle); //imaginary axis is the y axis
		if(Math.abs(imag) < 1.0E-15) imag = 0.0; //get rid of annoying sci notation
		System.out.print(real + " + " + imag + "i\t"); //tab-separated answers
	}
}

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']