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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With