Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia error while computing powers of a complex number

Tags:

julia

I'm a beginner at Julia and am using it to compute the power of a complex number as a subroutine in a larger scientific task where I run

array = [1im^(i-j) for i in 1:5, j in 1:5]

but I get the following DomainError :

DomainError with -1:
Cannot raise an integer x to a negative power -1.
Convert input to float.

Particularly, when I run the for loop and print the value for each (i,j), the same error occurs at (i=2,j=1). I'll be very grateful if someone can help me with this. What seems to be wrong with my code? How can I overcome this error?

Thank you in advance.

like image 865
Ananth_Rao Avatar asked Jun 16 '21 09:06

Ananth_Rao


1 Answers

Use a float as a base like this (this is what the error message recommends you to do):

julia> [(1.0im)^(i-j) for i in 1:5, j in 1:5]
5×5 Matrix{ComplexF64}:
  1.0+0.0im   0.0-1.0im  -1.0-0.0im  -0.0+1.0im   1.0+0.0im
  0.0+1.0im   1.0+0.0im   0.0-1.0im  -1.0-0.0im  -0.0+1.0im
 -1.0+0.0im   0.0+1.0im   1.0+0.0im   0.0-1.0im  -1.0-0.0im
 -0.0-1.0im  -1.0+0.0im   0.0+1.0im   1.0+0.0im   0.0-1.0im
  1.0-0.0im  -0.0-1.0im  -1.0+0.0im   0.0+1.0im   1.0+0.0im

or like this

julia> [float(im)^(i-j) for i in 1:5, j in 1:5]
5×5 Matrix{ComplexF64}:
  1.0+0.0im   0.0-1.0im  -1.0-0.0im  -0.0+1.0im   1.0+0.0im
  0.0+1.0im   1.0+0.0im   0.0-1.0im  -1.0-0.0im  -0.0+1.0im
 -1.0+0.0im   0.0+1.0im   1.0+0.0im   0.0-1.0im  -1.0-0.0im
 -0.0-1.0im  -1.0+0.0im   0.0+1.0im   1.0+0.0im   0.0-1.0im
  1.0-0.0im  -0.0-1.0im  -1.0+0.0im   0.0+1.0im   1.0+0.0im

The error follows from this definition:

^(z::Complex{<:Integer}, n::Integer) = power_by_squaring(z,n) # DomainError for n<0
like image 129
Bogumił Kamiński Avatar answered Oct 09 '22 07:10

Bogumił Kamiński