Roots of unity: Difference between revisions
Line 447: | Line 447: | ||
<lang haskell>import Data.Complex |
<lang haskell>import Data.Complex |
||
rootsOfUnity n = [cis (2*pi*k/n) | k <- [ |
rootsOfUnity n = [cis (2*pi*k/n) | k <- [0..n-1]]</lang> |
||
Output: |
Output: |
||
<lang haskell>*Main> rootsOfUnity 3 |
<lang haskell>*Main> rootsOfUnity 3 |
||
[1.0 :+ 0.0, |
|||
[(-0.4999999999999998) :+ 0.8660254037844387, |
|||
(-0. |
(-0.4999999999999998) :+ 0.8660254037844387, |
||
(-0.5000000000000004) :+ (-0.8660254037844384)]</lang> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
Revision as of 04:51, 18 September 2011
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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.
Ada
<lang ada>with Ada.Text_IO; use Ada.Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; with Ada.Numerics.Complex_Types; use Ada.Numerics.Complex_Types;
procedure Roots_Of_Unity is
Root : Complex;
begin
for N in 2..10 loop Put_Line ("N =" & Integer'Image (N)); for K in 0..N - 1 loop Root := Compose_From_Polar ( Modulus => 1.0, Argument => Float (K), Cycle => Float (N) ); -- Output Put (" k =" & Integer'Image (K) & ", "); if Re (Root) < 0.0 then Put ("-"); else Put ("+"); end if; Put (abs Re (Root), Fore => 1, Exp => 0); if Im (Root) < 0.0 then Put ("-"); else Put ("+"); end if; Put (abs Im (Root), Fore => 1, Exp => 0); Put_Line ("i"); end loop; end loop;
end Roots_Of_Unity;</lang> Ada provides a direct implementation of polar composition of complex numbers x e2πi y. The function Compose_From_Polar is used to compose roots. The third argument of the function is the cycle. Instead of the standard cycle 2π, N is used. Sample output:
N = 2 k = 0, +1.00000+0.00000i k = 1, -1.00000+0.00000i N = 3 k = 0, +1.00000+0.00000i k = 1, -0.50000+0.86603i k = 2, -0.50000-0.86603i N = 4 k = 0, +1.00000+0.00000i k = 1, +0.00000+1.00000i k = 2, -1.00000+0.00000i k = 3, +0.00000-1.00000i N = 5 k = 0, +1.00000+0.00000i k = 1, +0.30902+0.95106i k = 2, -0.80902+0.58779i k = 3, -0.80902-0.58779i k = 4, +0.30902-0.95106i N = 6 k = 0, +1.00000+0.00000i k = 1, +0.50000+0.86603i k = 2, -0.50000+0.86603i k = 3, -1.00000+0.00000i k = 4, -0.50000-0.86603i k = 5, +0.50000-0.86603i N = 7 k = 0, +1.00000+0.00000i k = 1, +0.62349+0.78183i k = 2, -0.22252+0.97493i k = 3, -0.90097+0.43388i k = 4, -0.90097-0.43388i k = 5, -0.22252-0.97493i k = 6, +0.62349-0.78183i N = 8 k = 0, +1.00000+0.00000i k = 1, +0.70711+0.70711i k = 2, +0.00000+1.00000i k = 3, -0.70711+0.70711i k = 4, -1.00000+0.00000i k = 5, -0.70711-0.70711i k = 6, +0.00000-1.00000i k = 7, +0.70711-0.70711i N = 9 k = 0, +1.00000+0.00000i k = 1, +0.76604+0.64279i k = 2, +0.17365+0.98481i k = 3, -0.50000+0.86603i k = 4, -0.93969+0.34202i k = 5, -0.93969-0.34202i k = 6, -0.50000-0.86603i k = 7, +0.17365-0.98481i k = 8, +0.76604-0.64279i N = 10 k = 0, +1.00000+0.00000i k = 1, +0.80902+0.58779i k = 2, +0.30902+0.95106i k = 3, -0.30902+0.95106i k = 4, -0.80902+0.58779i k = 5, -1.00000+0.00000i k = 6, -0.80902-0.58779i k = 7, -0.30902-0.95106i k = 8, +0.30902-0.95106i k = 9, +0.80902-0.58779i
ALGOL 68
<lang algol68>FORMAT complex fmt=$g(-6,4)"⊥"g(-6,4)$; FOR root FROM 2 TO 10 DO
printf(($g(4)$,root)); FOR n FROM 0 TO root-1 DO printf(($xf(complex fmt)$,complex exp( 0 I 2*pi*n/root))) OD; printf($l$)
OD</lang> Output:
+2 1.0000⊥0.0000 -1.000⊥0.0000 +3 1.0000⊥0.0000 -.5000⊥0.8660 -.5000⊥-.8660 +4 1.0000⊥0.0000 0.0000⊥1.0000 -1.000⊥0.0000 -.0000⊥-1.000 +5 1.0000⊥0.0000 0.3090⊥0.9511 -.8090⊥0.5878 -.8090⊥-.5878 0.3090⊥-.9511 +6 1.0000⊥0.0000 0.5000⊥0.8660 -.5000⊥0.8660 -1.000⊥0.0000 -.5000⊥-.8660 0.5000⊥-.8660 +7 1.0000⊥0.0000 0.6235⊥0.7818 -.2225⊥0.9749 -.9010⊥0.4339 -.9010⊥-.4339 -.2225⊥-.9749 0.6235⊥-.7818 +8 1.0000⊥0.0000 0.7071⊥0.7071 0.0000⊥1.0000 -.7071⊥0.7071 -1.000⊥0.0000 -.7071⊥-.7071 -.0000⊥-1.000 0.7071⊥-.7071 +9 1.0000⊥0.0000 0.7660⊥0.6428 0.1736⊥0.9848 -.5000⊥0.8660 -.9397⊥0.3420 -.9397⊥-.3420 -.5000⊥-.8660 0.1736⊥-.9848 0.7660⊥-.6428 +10 1.0000⊥0.0000 0.8090⊥0.5878 0.3090⊥0.9511 -.3090⊥0.9511 -.8090⊥0.5878 -1.000⊥0.0000 -.8090⊥-.5878 -.3090⊥-.9511 0.3090⊥-.9511 0.8090⊥-.5878
AutoHotkey
ahk forum: discussion <lang AutoHotkey>n := 8, a := 8*atan(1)/n Loop %n%
i := A_Index-1, t .= cos(a*i) ((s:=sin(a*i))<0 ? " - i*" . -s : " + i*" . s) "`n"
Msgbox % t</lang>
BASIC
For high n's, this may repeat the root of 1 + 0*i.
CLS PI = 3.1415926# n = 5 'this can be changed for any desired n angle = 0 'start at angle 0 DO real = COS(angle) 'real axis is the x axis IF (ABS(real) < 10 ^ -5) THEN real = 0 'get rid of annoying sci notation imag = SIN(angle) 'imaginary axis is the y axis IF (ABS(imag) < 10 ^ -5) THEN imag = 0 'get rid of annoying sci notation PRINT real; "+"; imag; "i" 'answer on every line angle = angle + (2 * PI) / n 'all the way around the circle at even intervals LOOP WHILE angle < 2 * PI
C
<lang c>#include <stdio.h>
- include <math.h>
int main() { double a, c, s, PI2 = atan2(1, 1) * 8; int n, i;
for (n = 1; n < 10; n++) for (i = 0; i < n; i++) { c = s = 0; if (!i ) c = 1; else if(n == 4 * i) s = 1; else if(n == 2 * i) c = -1; else if(3 * n == 4 * i) s = -1; else a = i * PI2 / n, c = cos(a), s = sin(a);
if (c) printf("%.2g", c); printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s); printf(i == n - 1 ?"\n":", "); }
return 0; }</lang>
C#
<lang csharp>using System; using System.Collections.Generic; using System.Linq; using System.Numerics;
class Program {
static IEnumerable<Complex> RootsOfUnity(int degree) { return Enumerable .Range(0, degree) .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree)); }
static void Main() { var degree = 3; foreach (var root in RootsOfUnity(degree)) { Console.WriteLine(root); } }
}</lang> Output: <lang>(1, 0) (-0,5, 0,866025403784439) (-0,5, -0,866025403784438)</lang>
C++
<lang cpp>#include <complex>
- include <cmath>
- include <iostream>
double const pi = 4 * std::atan(1);
int main() {
for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; }
}</lang>
Common Lisp
<lang lisp>(defun roots-of-unity (n)
(loop for i below n collect (cis (* pi (/ (* 2 i) n)))))</lang>
The expression is slightly more complicated than necessary in order to preserve exact rational arithmetic until multiplying by pi. The author of this example is not a floating point expert and not sure whether this is actually useful; if not, the simpler expression is (cis (/ (* 2 pi i) n)).
D
<lang d>import std.stdio, std.math, std.range, std.algorithm;
auto nthroots(int n) {
return map!((int k){ return expi(PI * 2 * k / n); })(iota(1, n+1));
}
void main() {
foreach (i; 1 .. 6) writefln("#%d: %5.2f", i, nthroots(i));
}</lang> Output:
#1: [ 1.00+ 0.00i] #2: [-1.00+-0.00i, 1.00+ 0.00i] #3: [-0.50+ 0.87i, -0.50+-0.87i, 1.00+ 0.00i] #4: [-0.00+ 1.00i, -1.00+-0.00i, 0.00+-1.00i, 1.00+ 0.00i] #5: [ 0.31+ 0.95i, -0.81+ 0.59i, -0.81+-0.59i, 0.31+-0.95i, 1.00+ 0.00i]
Forth
Complex numbers are not a native type in Forth, so we calculate the roots by hand. <lang forth>: f0. ( f -- )
fdup 0e 0.001e f~ if fdrop 0e then f. ;
- .roots ( n -- )
dup 1 do pi i 2* 0 d>f f* dup 0 d>f f/ ( F: radians ) fsincos cr ." real " f0. ." imag " f0. loop drop ;
3 set-precision 5 .roots</lang>
Fortran
Sin/Cos + Scalar Loop
<lang fortran>PROGRAM Roots
COMPLEX :: root INTEGER :: i, n REAL :: angle, pi
pi = 4.0 * ATAN(1.0) DO n = 2, 7 angle = 0.0 WRITE(*,"(I1,A)", ADVANCE="NO") n,": " DO i = 1, n root = CMPLX(COS(angle), SIN(angle)) WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j " angle = angle + (2.0*pi / REAL(n)) END DO WRITE(*,*) END DO
END PROGRAM Roots</lang> Output
2: +1.0000+0.0000j -1.0000+0.0000j 3: +1.0000+0.0000j -0.5000+0.8660j -0.5000-0.8660j 4: +1.0000+0.0000j +0.0000+1.0000j -1.0000+0.0000j +0.0000-1.0000j 5: +1.0000+0.0000j +0.3090+0.9511j -0.8090+0.5878j -0.8090-0.5878j +0.3090-0.9511j 6: +1.0000+0.0000j +0.5000+0.8660j -0.5000+0.8660j -1.0000+0.0000j -0.5000-0.8660j +0.5000-0.8660j 7: +1.0000+0.0000j +0.6235+0.7818j -0.2225+0.9749j -0.9010+0.4339j -0.9010-0.4339j -0.2225-0.9749j +0.6235-0.7818j
Exp + Array-valued Statement
<lang fortran>program unity
real, parameter :: pi = 3.141592653589793 complex, parameter :: i = (0, 1) complex, dimension(0:7-1) :: unit_circle integer :: n, j do n = 2, 7 !!!! KEY STEP, does all the calculations in one statement !!!! unit_circle(0:n-1) = exp(2*i*pi/n * (/ (j, j=0, n-1) /) )
write(*,"(i1,a)", advance="no") n, ": " write(*,"(sp,2f7.4,a)", advance="no") (unit_circle(j), "j ", j = 0, n-1) write(*,*) end do end program unity</lang>
GAP
<lang gap>roots := n -> List([0 .. n-1], k -> E(n)^k);
r:=roots(7);
- [ 1, E(7), E(7)^2, E(7)^3, E(7)^4, E(7)^5, E(7)^6 ]
List(r, x -> x^7);
- [ 1, 1, 1, 1, 1, 1, 1 ]</lang>
Go
<lang go>package main
import (
"fmt" "math" "cmath"
)
func main() {
for n := 2; n <= 5; n++ { fmt.Printf("%d roots of 1:\n", n) for _, r := range roots(n) { fmt.Printf(" %18.15f\n", r) } }
}
func roots(n int) []complex128 {
r := make([]complex128, n) for i := 0; i < n; i++ { r[i] = cmath.Rect(1, 2 * math.Pi * float64(i) / float64(n)) } return r
}</lang> Output:
2 roots of 1: ( 1.000000000000000+0.000000000000000i) (-1.000000000000000+0.000000000000000i) 3 roots of 1: ( 1.000000000000000+0.000000000000000i) (-0.500000000000000+0.866025403784439i) (-0.500000000000000-0.866025403784438i) 4 roots of 1: ( 1.000000000000000+0.000000000000000i) ( 0.000000000000000+1.000000000000000i) (-1.000000000000000+0.000000000000000i) (-0.000000000000000-1.000000000000000i) 5 roots of 1: ( 1.000000000000000+0.000000000000000i) ( 0.309016994374948+0.951056516295154i) (-0.809016994374947+0.587785252292473i) (-0.809016994374947-0.587785252292473i) ( 0.309016994374947-0.951056516295154i)
Groovy
Because the Groovy language does not provide a built-in facility for complex arithmetic, this example relies on the Complex class defined in the Complex numbers example. <lang groovy>/** The following closure creates a list of n evenly-spaced points around the unit circle,
* useful in FFT calculations, among other things */
def rootsOfUnity = { n ->
(0..<n).collect { Complex.exp(Complex.I * 2 * Math.PI * it / n) }
}</lang>
Test program: <lang groovy>def tol = 0.000000001 // tolerance: acceptable "wrongness" to account for rounding error
((1..6) + [16]). each { n ->
println "rootsOfUnity(${n}):" def rou = rootsOfUnity(n) rou.each { println it } assert rou[0] == 1 def actual = n > 1 ? rou[Math.floor(n/2) as int] : rou[0] def expected = n > 1 ? (n%2 == 0) ? -1 : ~rou[Math.ceil(n/2) as int] : rou[0] def message = n > 1 ? (n%2 == 0) ? 'middle-most root should be -1' : 'two middle-most roots should be conjugates' : assert (actual - expected).abs() < tol : message assert rou.every { (it.rho - 1) < tol } : 'all roots should have magnitude 1' println()
}</lang>
Output:
rootsOfUnity(1): 1.0 rootsOfUnity(2): 1.0 -1.0 + 1.2246467991473532E-16i rootsOfUnity(3): 1.0 -0.4999999998186198 + 0.8660254038891585i -0.5000000003627604 - 0.8660254035749988i rootsOfUnity(4): 1.0 6.123233995736766E-17 + i -1.0 + 1.2246467991473532E-16i -1.8369701987210297E-16 - i rootsOfUnity(5): 1.0 0.30901699437494745 + 0.9510565162951535i -0.8090169943749473 + 0.5877852522924732i -0.8090169943749475 - 0.587785252292473i 0.30901699437494723 - 0.9510565162951536i rootsOfUnity(6): 1.0 0.4999999998186201 + 0.8660254038891584i -0.5000000003627598 + 0.8660254035749991i -1.0 - 6.283181638240517E-10i -0.4999999992744804 - 0.8660254042033175i 0.5000000009068993 - 0.8660254032608401i rootsOfUnity(16): 1.0 0.9238795325112867 + 0.3826834323650898i 0.7071067811865476 + 0.7071067811865475i 0.38268343236508984 + 0.9238795325112867i 6.123233995736766E-17 + i -0.3826834323650897 + 0.9238795325112867i -0.7071067811865475 + 0.7071067811865476i -0.9238795325112867 + 0.3826834323650899i -1.0 + 1.2246467991473532E-16i -0.9238795325112868 - 0.38268343236508967i -0.7071067811865477 - 0.7071067811865475i -0.38268343236509034 - 0.9238795325112865i -1.8369701987210297E-16 - i 0.38268343236509 - 0.9238795325112866i 0.7071067811865474 - 0.7071067811865477i 0.9238795325112865 - 0.3826834323650904i
Haskell
<lang haskell>import Data.Complex
rootsOfUnity n = [cis (2*pi*k/n) | k <- [0..n-1]]</lang>
Output: <lang haskell>*Main> rootsOfUnity 3 [1.0 :+ 0.0,
(-0.4999999999999998) :+ 0.8660254037844387, (-0.5000000000000004) :+ (-0.8660254037844384)]</lang>
Icon and Unicon
<lang icon>procedure main()
roots(10)
end
procedure roots(n)
every n := 2 to 10 do every writes(n | (str_rep((0 to (n-1)) * 2 * &pi / n)) | "\n")
end
procedure str_rep(k)
return " " || cos(k) || "+" || sin(k) || "i"
end</lang> Notes:
- The The Icon Programming Library implements a complex type but not a polar type
IDL
For some example n:
<lang idl>n = 5 print, exp( dcomplex( 0, 2*!dpi/n) ) ^ ( 1 + indgen(n) )</lang>
Outputs: <lang idl>( 0.30901699, 0.95105652)( -0.80901699, 0.58778525)( -0.80901699, -0.58778525)( 0.30901699, -0.95105652)( 1.0000000, -1.1102230e-16)</lang>
J
<lang j> rou=: [: ^ 0j2p1 * i. % ]
rou 4
1 0j1 _1 0j_1
rou 5
1 0.309017j0.951057 _0.809017j0.587785 _0.809017j_0.587785 0.309017j_0.951057</lang>
The computation can also be written as a loop, shown here for comparison only.
<lang j>rou1=: 3 : 0
z=. 0 $ r=. ^ o. 0j2 % y [ e=. 1 for. i.y do. z=. z,e e=. e*r end. z
)</lang>
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-3 where scientific notation sets in for Doubles). Instead, they are simply represented as 0. To remove those checks (for very high n's), remove both if statements. <lang java>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-3) 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-3) imag = 0.0; //get rid of annoying sci notation System.out.print(real + " + " + imag + "i\t"); //tab-separated answers } }</lang>
Liberty BASIC
<lang lb>WindowWidth =400 WindowHeight =400
'nomainwin
open "N'th Roots of One" for graphics_nsb_nf as #w
- w "trapclose [quit]"
for n =1 To 10
angle =0 #w "font arial 16 bold" print n; "th roots." #w "cls" #w "size 1 ; goto 200 200 ; down ; color lightgray ; circle 150 ; size 10 ; set 200 200 ; size 2" #w "up ; goto 200 0 ; down ; goto 200 400 ; up ; goto 0 200 ; down ; goto 400 200" #w "up ; goto 40 20 ; down ; color black" #w "font arial 6" #w "\"; n; " roots of 1."
for i = 1 To n x = cos( Radian( angle)) y = sin( Radian( angle))
print using( "##", i); ": ( " + using( "##.######", x);_ " +i *" +using( "##.######", y); ") or e^( i *"; i -1; " *2 *Pi/ "; n; ")"
#w "color "; 255 *i /n; " 0 "; 256 -255 *i /n #w "up ; goto 200 200" #w "down ; goto "; 200 +150 *x; " "; 200 -150 *y #w "up ; goto "; 200 +165 *x; " "; 200 -165 *y #w "\"; str$( i) #w "up"
angle =angle +360 /n
next i
timer 500, [on] wait [on] timer 0
next n
wait
[quit]
close #w
end
function Radian( theta)
Radian =theta *3.1415926535 /180
end function
</lang>
Lua
Complex numbers from the Lua implementation on the complex numbers page.
<lang lua>--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs. complex = setmetatable({ __add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end, __sub = function(u, v) return complex(u.real - v.real, u.imag - v.imag) end, __mul = function(u, v) return complex(u.real * v.real - u.imag * v.imag, u.real * v.imag + u.imag * v.real) end, __div = function(u, v) return u * complex(v.real / v.norm, -v.imag / v.norm) end, __unm = function(u) return complex(-u.real, -u.imag) end, __concat = function(u, v)
if type(u) == "table" then return u.real .. " + " .. u.imag .. "i" .. v
elseif type(u) == "string" or type(u) == "number" then return u .. v.real .. " + " .. v.imag .. "i" end end, __index = function(u, index)
local operations = { norm = function(u) return u.real ^ 2 + u.imag ^ 2 end, conj = function(u) return complex(u.real, -u.imag) end, } return operations[index] and operations[index](u)
end, __newindex = function() error() end }, { __call = function(z, realpart, imagpart) return setmetatable({real = realpart, imag = imagpart}, complex) end } ) n = io.read() + 0 val = complex(math.cos(2*math.pi / n), math.sin(2*math.pi / n)) root = complex(1, 0) for i = 1, n do
root = root * val print(root .. "")
end</lang>
Mathematica
Setting this up in Mathematica is easy, because it already handles complex numbers: <lang Mathematica>RootsUnity[nthroot_Integer?Positive] := Table[Exp[2 Pi I i/nthroot], {i, 0, nthroot - 1}]</lang> Note that Mathematica will keep the expression as exact as possible. Simplifications can be made to more known (trigonometric) functions by using the function ExpToTrig. If only a numerical approximation is necessary the function N will transform the exact result to a numerical approximation. Examples (exact not simplified, exact simplified, approximated): <lang Mathematica>RootsUnity[2] RootsUnity[3] RootsUnity[4] RootsUnity[5]
RootsUnity[2]//ExpToTrig RootsUnity[3]//ExpToTrig RootsUnity[4]//ExpToTrig RootsUnity[5]//ExpToTrig
RootsUnity[2]//N RootsUnity[3]//N RootsUnity[4]//N RootsUnity[5]//N</lang> gives back:
MATLAB
<lang MATLAB>function z = rootsOfUnity(n)
assert(n >= 1,'n >= 1'); z = roots([1 zeros(1,n-1) -1]);
end</lang>
Sample Output: <lang MATLAB>>> rootsOfUnity(3)
ans =
-0.500000000000000 + 0.866025403784439i -0.500000000000000 - 0.866025403784439i 1.000000000000000 </lang>
Maxima
<lang maxima>solve(1 = x^n, x)</lang> Demonstration: <lang maxima>for n:1 thru 5 do display(solve(1 = x^n, x));</lang> Output: <lang maxima>solve(1 = x, x) = [x = 1] solve(1 = x^2, x) = [x = -1, x = 1] solve(1 = x^3, x) = [x = (sqrt(3)*%i-1)/2, x = -(sqrt(3)*%i+1)/2, x = 1] solve(1 = x^4, x) = [x = %i, x = -1, x = -%i, x = 1] solve(1 = x^5, x) = [x = %e^((2*%i*%pi)/5), x = %e^((4*%i*%pi)/5), x = %e^(-(4*%i*%pi)/5), x = %e^(-(2*%i*%pi)/5), x = 1]</lang>
OCaml
<lang ocaml>open Complex
let pi = 4. *. atan 1.
let () =
for n = 1 to 10 do Printf.printf "%2d " n; for k = 1 to n do let ret = polar 1. (2. *. pi *. float_of_int k /. float_of_int n) in Printf.printf "(%f + %f i)" ret.re ret.im done; print_newline () done</lang>
Octave
<lang octave>for j = 2 : 10
printf("*** %d\n", j); for n = 1 : j disp(exp(2i*pi*n/j)); endfor disp("");
endfor</lang>
PARI/GP
<lang parigp>vector(n,k,exp(2*Pi*I*k/n))</lang>
Perl
<lang perl>use Math::Complex;
foreach $n (2 .. 10) {
printf "%2d", $n; foreach $k (0 .. $n-1) { $ret = cplxe(1, 2 * pi * $k / $n); $ret->display_format(style => 'cartesian', format => '%.3f'); print " $ret"; } print "\n";
}</lang> Output:
2 1.000 -1.000+0.000i 3 1.000 -0.500+0.866i -0.500-0.866i 4 1.000 0.000+1.000i -1.000+0.000i -0.000-1.000i 5 1.000 0.309+0.951i -0.809+0.588i -0.809-0.588i 0.309-0.951i 6 1.000 0.500+0.866i -0.500+0.866i -1.000+0.000i -0.500-0.866i 0.500-0.866i 7 1.000 0.623+0.782i -0.223+0.975i -0.901+0.434i -0.901-0.434i -0.223-0.975i 0.623-0.782i 8 1.000 0.707+0.707i 0.000+1.000i -0.707+0.707i -1.000+0.000i -0.707-0.707i -0.000-1.000i 0.707-0.707i 9 1.000 0.766+0.643i 0.174+0.985i -0.500+0.866i -0.940+0.342i -0.940-0.342i -0.500-0.866i 0.174-0.985i 0.766-0.643i 10 1.000 0.809+0.588i 0.309+0.951i -0.309+0.951i -0.809+0.588i -1.000+0.000i -0.809-0.588i -0.309-0.951i 0.309-0.951i 0.809-0.588i
Perl 6
<lang perl6>sub roots_of_unity (Int $n where { $n > 0 }) {
map { exp 2i * pi/$n * $_ }, ^$n
}
printf "% .5f + % .5fi\n", .re, .im for roots_of_unity 10;</lang>
Output:
1.00000 + 0.00000i 0.80902 + 0.58779i 0.30902 + 0.95106i -0.30902 + 0.95106i -0.80902 + 0.58779i -1.00000 + 0.00000i -0.80902 + -0.58779i -0.30902 + -0.95106i 0.30902 + -0.95106i 0.80902 + -0.58779i
PL/I
<lang PL/I>complex_roots:
procedure (N); declare N fixed binary nonassignable; declare x float, c fixed decimal (10,8) complex; declare twopi float initial ((4*asin(1.0)));
do x = 0 to twopi by twopi/N; c = complex(cos(x), sin(x)); put skip list (c); end;
end complex_roots;
1.00000000+0.00000000I 0.80901700+0.58778524I 0.30901697+0.95105654I -0.30901703+0.95105648I -0.80901706+0.58778518I -1.00000000-0.00000008I -0.80901694-0.58778536I -0.30901709-0.95105648I 0.30901712-0.95105648I 0.80901724-0.58778494I </lang>
PicoLisp
<lang PicoLisp>(load "@lib/math.l")
(for N (range 2 10)
(let Angle 0.0 (prin N ": ") (for I N (let Ipart (sin Angle) (prin (round (cos Angle) 4) (if (lt0 Ipart) "-" "+") "j" (round (abs Ipart) 4) " " ) ) (inc 'Angle (*/ 2 pi N)) ) (prinl) ) )</lang>
PureBasic
<lang Purebasic>OpenConsole() For n = 2 To 10
angle = 0 PrintN(Str(n)) For i = 1 To n x.f = Cos(Radian(angle)) y.f = Sin(Radian(angle)) PrintN( Str(i) + ": " + StrF(x, 6) + " / " + StrF(y, 6)) angle = angle + (360 / n) Next
Next Input()</lang>
Python
<lang python>import cmath class Complex(complex):
def __repr__(self): rp = '%7.5f'%self.real if not self.pureImag() else ip = '%7.5fj'%self.imag if not self.pureReal() else conj = if (self.pureImag() or self.pureReal() or self.imag<0.0) else '+' return '0.0' if (self.pureImag() and self.pureReal()) else rp+conj+ip def pureImag(self): return abs( self.real) < 0.000005 def pureReal(self): return abs( self.imag) < 0.000005
def croots(n):
if n<=0: return None return (Complex(cmath.exp(2j*k*cmath.pi/n)) for k in range(n)) # in Python 2.6+: return (Complex(cmath.rect(1, 2*k*cmath.pi/n)) for k in range(n))
for nr in range(2,11):
print nr, list(croots(nr))</lang>
Output:
2 [1.00000, -1.00000] 3 [1.00000, -0.50000+0.86603j, -0.50000-0.86603j] 4 [1.00000, 1.00000j, -1.00000, -1.00000j] 5 [1.00000, 0.30902+0.95106j, -0.80902+0.58779j, -0.80902-0.58779j, 0.30902-0.95106j] 6 [1.00000, 0.50000+0.86603j, -0.50000+0.86603j, -1.00000, -0.50000-0.86603j, 0.50000-0.86603j] 7 [1.00000, 0.62349+0.78183j, -0.22252+0.97493j, -0.90097+0.43388j, -0.90097-0.43388j, -0.22252-0.97493j, 0.62349-0.78183j] 8 [1.00000, 0.70711+0.70711j, 1.00000j, -0.70711+0.70711j, -1.00000, -0.70711-0.70711j, -1.00000j, 0.70711-0.70711j] 9 [1.00000, 0.76604+0.64279j, 0.17365+0.98481j, -0.50000+0.86603j, -0.93969+0.34202j, -0.93969-0.34202j, -0.50000-0.86603j, 0.17365-0.98481j, 0.76604-0.64279j] 10 [1.00000, 0.80902+0.58779j, 0.30902+0.95106j, -0.30902+0.95106j, -0.80902+0.58779j, -1.00000, -0.80902-0.58779j, -0.30902-0.95106j, 0.30902-0.95106j, 0.80902-0.58779j]
R
<lang R>for(j in 2:10) {
r <- sprintf("%d: ", j) for(n in 1:j) { r <- paste(r, format(exp(2i*pi*n/j), digits=4), ifelse(n<j, ",", "")) } print(r)
}</lang>
Output:
[1] "2: -1+0i , 1-0i " [1] "3: -0.5+0.866i , -0.5-0.866i , 1-0i " [1] "4: 0+1i , -1+0i , 0-1i , 1-0i " [1] "5: 0.309+0.9511i , -0.809+0.5878i , -0.809-0.5878i , 0.309-0.9511i , 1-0i " [1] "6: 0.5+0.866i , -0.5+0.866i , -1+0i , -0.5-0.866i , 0.5-0.866i , 1-0i " [1] "7: 0.6235+0.7818i , -0.2225+0.9749i , -0.901+0.4339i , -0.901-0.4339i , -0.2225-0.9749i , 0.6235-0.7818i , 1-0i " [1] "8: 0.7071+0.7071i , 0+1i , -0.7071+0.7071i , -1+0i , -0.7071-0.7071i , 0-1i , 0.7071-0.7071i , 1-0i " [1] "9: 0.766+0.6428i , 0.1736+0.9848i , -0.5+0.866i , -0.9397+0.342i , -0.9397-0.342i , -0.5-0.866i , 0.1736-0.9848i , 0.766-0.6428i , 1-0i " [1] "10: 0.809+0.5878i , 0.309+0.9511i , -0.309+0.9511i , -0.809+0.5878i , -1+0i , -0.809-0.5878i , -0.309-0.9511i , 0.309-0.9511i , 0.809-0.5878i , 1-0i "
Racket
<lang Racket>#lang racket
(define (roots-of-unity n)
(for/list ([k n]) (make-polar 1 (* k (/ (* 2 pi) n)))))</lang>
Will produce a list of roots, for example:
> (for ([r (roots-of-unity 3)]) (displayln r)) 1 -0.4999999999999998+0.8660254037844388i -0.5000000000000004-0.8660254037844384i
RLaB
RLaB can find the n-roots of unity by solving the polynomial equation
It uses the solver polyroots. Interested user is recommended to check the rlabplus manual for details on the solver and the parameters that tune the solver performance.
<lang RLaB>// specify polynomial >> n = 10; >> a = zeros(1,n+1); a[1] = 1; a[n+1] = -1; >> polyroots(a)
radius roots success
>> polyroots(a).roots
-0.309016994 + 0.951056516i -0.809016994 + 0.587785252i -1 + 5.95570041e-23i -0.809016994 - 0.587785252i -0.309016994 - 0.951056516i 0.309016994 - 0.951056516i 0.809016994 - 0.587785252i 1 + 0i 0.809016994 + 0.587785252i 0.309016994 + 0.951056516i</lang>
REXX
REXX doesn't have complex arithmetic, so the (real) values of COS and SIN of multiples of 2π radians (divided by K) are used.
Also, REXX doesn't have the pi constant defined, nor a SIN or COS function, so they are included below. <lang rexx>/*REXX program to compute K roots of unity. */
arg n frac . /*get the argument(s) (if any).*/ if n== then n=1 /*no argument given? Use one. */ start=abs(n) /*assume only one K is wanted.*/ if n<0 then start=1 /*Negative? Use a range of K's.*/ if frac= then frac=5 /*No frac? Use default of 5 dig*/ numeric digits 60 /*use sixty digits of precision.*/ pi=pi() /*compute PI to sixty digits. */
/*display unity roots for a ... */ do k=start to abs(n) /* ... range or just for one K.*/ say right(k 'roots of unity',40,"─") /*display a pretty separator. */
do angle=0 by 2*pi/k for k /*compute angle for each root. */ rp=cos(angle) /*compute real part via COS func*/ rp=adjust(rp) /*adjust Rpart by limiting digs.*/ if left(rp,1)\=='-' then rp=' 'rp /*not negative? Pad with blank.*/
ip=sin(angle) /*compute imag part via SIN func*/ ip=adjust(ip) /*adjust Ipart by limiting digs.*/ if left(ip,1)\=='-' then ip='+'ip /*not negative? Pad with + char*/
if ip=0 then say rp /*only real part? Ignore IMAG. */ else say left(rp,frac+4)ip'i' /*show real & imag part.*/
end /*angle*/ end /*k*/
exit
/*─────────────────────────────────────ADJUST subroutine───────────────*/ adjust: arg x; near0='1e-'||(digits()-digits()%10) /*compute small #.*/ if abs(x)<near0 then x=0 /*if near zero, then assume zero*/ return format(x,,frac)/1 /*"frac" digits past dec point.*/
/*─────────────────────────────────────PI subroutine (100 digits)──────*/ pi: return , 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068
/*─────────────────────────────────────R2R subroutine──────────────────*/ r2r: return arg(1)//(2*pi()) /*# radians to -360 ──> +360 deg*/
/*─────────────────────────────────────COS subroutine──────────────────*/ cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9); if a=pi() then return -1; if a=pi()/2 | a=2*pi() then return 0; if a=pi()/3 then return .5; if a=2*pi()/3 then return -.5; return sincos(1,1,-1)
/*─────────────────────────────────────SIN subroutine──────────────────*/ sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3); if abs(x)=pi() then return 0; return sincos(x,x,1)
/*─────────────────────────────────────SINCOS subroutine───────────────*/ sincos: parse arg z,_,i; x=x*x; p=z;
do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end;
return z</lang> Output when the input is:
5
────────────────────────5 roots of unity 1 0.30902 +0.95106i -0.80902 +0.58779i -0.80902 -0.58779i 0.30902 -0.95106i
Output when the input is:
10 35
───────────────────────10 roots of unity 1 0.80901699437494742410229341718281906 +0.58778525229247312916870595463907277i 0.30901699437494742410229341718281906 +0.95105651629515357211643933337938214i -0.30901699437494742410229341718281906 +0.95105651629515357211643933337938214i -0.80901699437494742410229341718281906 +0.58778525229247312916870595463907277i -1 -0.80901699437494742410229341718281906 -0.58778525229247312916870595463907277i -0.30901699437494742410229341718281906 -0.95105651629515357211643933337938214i 0.30901699437494742410229341718281906 -0.95105651629515357211643933337938214i 0.80901699437494742410229341718281906 -0.58778525229247312916870595463907277i
Output when the input is:
-12
────────────────────────1 roots of unity 1 ────────────────────────2 roots of unity 1 -1 ────────────────────────3 roots of unity 1 -0.5 +0.86603i -0.5 -0.86603i ────────────────────────4 roots of unity 1 0 +1i -1 0 -1i ────────────────────────5 roots of unity 1 0.30902 +0.95106i -0.80902 +0.58779i -0.80902 -0.58779i 0.30902 -0.95106i ────────────────────────6 roots of unity 1 0.5 +0.86603i -0.5 +0.86603i -1 -0.5 -0.86603i 0.5 -0.86603i ────────────────────────7 roots of unity 1 0.62349 +0.78183i -0.22252 +0.97493i -0.90097 +0.43388i -0.90097 -0.43388i -0.22252 -0.97493i 0.62349 -0.78183i ────────────────────────8 roots of unity 1 0.70711 +0.70711i 0 +1i -0.70711 +0.70711i -1 -0.70711 -0.70711i 0 -1i 0.70711 -0.70711i ────────────────────────9 roots of unity 1 0.76604 +0.64279i 0.17365 +0.98481i -0.5 +0.86603i -0.93969 +0.34202i -0.93969 -0.34202i -0.5 -0.86603i 0.17365 -0.98481i 0.76604 -0.64279i ───────────────────────10 roots of unity 1 0.80902 +0.58779i 0.30902 +0.95106i -0.30902 +0.95106i -0.80902 +0.58779i -1 -0.80902 -0.58779i -0.30902 -0.95106i 0.30902 -0.95106i 0.80902 -0.58779i ───────────────────────11 roots of unity 1 0.84125 +0.54064i 0.41542 +0.90963i -0.14231 +0.98982i -0.65486 +0.75575i -0.95949 +0.28173i -0.95949 -0.28173i -0.65486 -0.75575i -0.14231 -0.98982i 0.41542 -0.90963i 0.84125 -0.54064i ───────────────────────12 roots of unity 1 0.86603 +0.5i 0.5 +0.86603i 0 +1i -0.5 +0.86603i -0.86603 +0.5i -1 -0.86603 -0.5i -0.5 -0.86603i 0 -1i 0.5 -0.86603i 0.86603 -0.5i
Ruby
Hopefully someone will fix the formatting <lang ruby>require 'complex'
for n in 2..10
printf "%2d ", n puts (0..n-1).map { |k| Complex.polar(1, 2 * Math::PI * k / n) }.join(" ")
end</lang> Output:
2 1.0+0.0i -1.0+1.22460635382238e-16i 3 1.0+0.0i -0.5+0.866025403784439i -0.5-0.866025403784438i 4 1.0+0.0i 6.12303176911189e-17+1.0i -1.0+1.22460635382238e-16i -1.83690953073357e-16-1.0i 5 1.0+0.0i 0.309016994374947+0.951056516295154i -0.809016994374947+0.587785252292473i -0.809016994374948-0.587785252292473i 0.309016994374947-0.951056516295154i 6 1.0+0.0i 0.5+0.866025403784439i -0.5+0.866025403784439i -1.0+1.22460635382238e-16i -0.5-0.866025403784438i 0.5-0.866025403784439i 7 1.0+0.0i 0.623489801858734+0.78183148246803i -0.222520933956314+0.974927912181824i -0.900968867902419+0.433883739117558i -0.900968867902419-0.433883739117558i -0.222520933956315-0.974927912181824i 0.623489801858733-0.78183148246803i 8 1.0+0.0i 0.707106781186548+0.707106781186547i 6.12303176911189e-17+1.0i -0.707106781186547+0.707106781186548i -1.0+1.22460635382238e-16i -0.707106781186548-0.707106781186547i -1.83690953073357e-16-1.0i 0.707106781186547-0.707106781186548i 9 1.0+0.0i 0.766044443118978+0.642787609686539i 0.17364817766693+0.984807753012208i -0.5+0.866025403784439i -0.939692620785908+0.342020143325669i -0.939692620785908-0.342020143325669i -0.5-0.866025403784438i 0.17364817766693-0.984807753012208i 0.766044443118978-0.64278760968654i 10 1.0+0.0i 0.809016994374947+0.587785252292473i 0.309016994374947+0.951056516295154i -0.309016994374947+0.951056516295154i -0.809016994374947+0.587785252292473i -1.0+1.22460635382238e-16i -0.809016994374948-0.587785252292473i -0.309016994374948-0.951056516295154i 0.309016994374947-0.951056516295154i 0.809016994374947-0.587785252292473i
Scala
Using Complex class from task Arithmetic/Complex. <lang scala>def rootsOfUnity(n:Int)=for(k <- 0 until n) yield Complex.fromPolar(1.0, 2*math.Pi*k/n)</lang> Usage:
rootsOfUnity(3) foreach println 1.0+0.0i -0.4999999999999998+0.8660254037844387i -0.5000000000000004-0.8660254037844385i
Seed7
<lang seed7>$ include "seed7_05.s7i";
include "float.s7i"; include "complex.s7i";
const proc: main is func
local var integer: n is 0; var integer: k is 0; begin for n range 2 to 10 do write(n lpad 2 <& ": "); for k range 0 to pred(n) do write(polar(1.0, 2.0 * PI * flt(k) / flt(n)) digits 4 lpad 15 <& " "); end for; writeln; end for; end func;</lang>
Output: <lang seed7>2: 1.0000+0.0000i -1.0000+0.0000i
3: 1.0000+0.0000i -0.5000+0.8660i -0.5000-0.8660i 4: 1.0000+0.0000i 0.0000+1.0000i -1.0000+0.0000i 0.0000-1.0000i 5: 1.0000+0.0000i 0.3090+0.9511i -0.8090+0.5878i -0.8090-0.5878i 0.3090-0.9511i 6: 1.0000+0.0000i 0.5000+0.8660i -0.5000+0.8660i -1.0000+0.0000i -0.5000-0.8660i 0.5000-0.8660i 7: 1.0000+0.0000i 0.6235+0.7818i -0.2225+0.9749i -0.9010+0.4339i -0.9010-0.4339i -0.2225-0.9749i 0.6235-0.7818i 8: 1.0000+0.0000i 0.7071+0.7071i 0.0000+1.0000i -0.7071+0.7071i -1.0000+0.0000i -0.7071-0.7071i 0.0000-1.0000i 0.7071-0.7071i 9: 1.0000+0.0000i 0.7660+0.6428i 0.1736+0.9848i -0.5000+0.8660i -0.9397+0.3420i -0.9397-0.3420i -0.5000-0.8660i 0.1736-0.9848i 0.7660-0.6428i
10: 1.0000+0.0000i 0.8090+0.5878i 0.3090+0.9511i -0.3090+0.9511i -0.8090+0.5878i -1.0000+0.0000i -0.8090-0.5878i -0.3090-0.9511i 0.3090-0.9511i 0.8090-0.5878i</lang>
Scheme
<lang scheme>(define pi (* 4 (atan 1)))
(do ((n 2 (+ n 1)))
((> n 10)) (display n) (do ((k 0 (+ k 1))) ((>= k n)) (display " ") (display (make-polar 1 (* 2 pi (/ k n))))) (newline))</lang>
Tcl
<lang Tcl>package require Tcl 8.5 namespace import tcl::mathfunc::*
set pi 3.14159265 for {set n 2} {$n <= 10} {incr n} {
set angle 0.0 set row $n: for {set i 1} {$i <= $n} {incr i} { lappend row [format %5.4f%+5.4fi [cos $angle] [sin $angle]] set angle [expr {$angle + 2*$pi/$n}] } puts $row
}</lang>
TI-89 BASIC
<lang ti89b>cZeros(x^n - 1, x)</lang>
For n=3 in exact mode, the results are <lang ti89b>{-1/2+√(3)/2*i, -1/2-√(3)/2*i, 1}</lang>
Ursala
The roots function takes a number n to the nth root of -1, squares it, and iteratively makes a list of its first n powers (oblivious to roundoff error). Complex functions cpow and mul are used, which are called from the host system's standard C library.
<lang Ursala>#import std
- import nat
- import flo
roots = ~&htxPC+ c..mul:-0^*DlSiiDlStK9\iota c..mul@iiX+ c..cpow/-1.+ div/1.+ float
- cast %jLL
tests = roots* <1,2,3,4,5,6></lang> The output is a list of lists of complex numbers.
< <1.000e+00-2.449e-16j>, < 1.000e+00-2.449e-16j, -1.000e+00+1.225e-16j>, < 1.000e+00-8.327e-16j, -5.000e-01+8.660e-01j, -5.000e-01-8.660e-01j>, < 1.000e+00-8.882e-16j, 2.220e-16+1.000e+00j, -1.000e+00+4.441e-16j, -6.661e-16-1.000e+00j>, < 1.000e+00-5.551e-17j, 3.090e-01+9.511e-01j, -8.090e-01+5.878e-01j, -8.090e-01-5.878e-01j, 3.090e-01-9.511e-01j>, < 1.000e+00-1.221e-15j, 5.000e-01+8.660e-01j, -5.000e-01+8.660e-01j, -1.000e+00+6.106e-16j, -5.000e-01-8.660e-01j, 5.000e-01-8.660e-01j>>