Tio Miserias
Tio Miserias

Reputation: 495

Calculating n-roots of unity in Julia

I would like to have an algorithm in Julia depending on $n$, such that it generates the n-roots of unity.

(1,w^{1}, w^{2}, ..., w^{n-1}. Such that for every 1\leq i\leq n, we have that (w^{i})^{n}-1=0 )

Thank you so much for your collaboration,

Upvotes: 1

Views: 260

Answers (1)

mcabbott
mcabbott

Reputation: 2580

julia> roots(n) = map(cispi, range(0, 2, length=n+1)[1:end-1])
roots (generic function with 1 method)

julia> roots(8)
8-element Vector{ComplexF64}:
                 1.0 + 0.0im
  0.7071067811865476 + 0.7071067811865476im
                 0.0 + 1.0im
 -0.7071067811865476 + 0.7071067811865476im
                -1.0 + 0.0im
 -0.7071067811865476 - 0.7071067811865476im
                 0.0 - 1.0im
  0.7071067811865476 - 0.7071067811865476im

You could write roots_exp(n) = exp.(im .* range(0, 2pi, length=n+1)[1:end-1]), but for a pure imaginary argument, cis is slightly more efficient than exp. And cispi is slightly more accurate, or at least, more likely to give you nice round numbers when you expect them, as shown above.

Upvotes: 7

Related Questions