matrixjulialinear-algebranumerical-methods

Generate array of complex numbers with absolute value one


I would like to randomly generate an array of arbitrary size, where all the elements of the array are complex numbers with absolute value one. Is there any way to do this within Julia?


Solution

  • I've got four options so far:

    f1(n) = exp.((2*im*π).*rand(n))
    
    f2(n) = map(x->(z = x[1]+im*x[2] ; z ./ abs(z) ),
      eachcol(randn(2,n)))
    
    f3(n) = [im*x[1]+x[2] for x in sincos.(2π*rand(n))]
    
    f4(n) = cispi.(2 .*rand(n))
    

    We have:

    julia> using BenchmarkTools
    
    julia> begin
             @btime f1(1_000);
             @btime f2(1_000);
             @btime f3(1_000);
             @btime f4(1_000);
           end;
      29.390 μs (2 allocations: 23.69 KiB)
      15.559 μs (2 allocations: 31.50 KiB)
      25.733 μs (4 allocations: 47.38 KiB)
      27.662 μs (2 allocations: 23.69 KiB)
    

    Not a crucial difference.