Adding a complex value to an element of a real array results in InexactError

Hi,

I’m just getting started with Julia and I’ve read that Julia does automatic conversion and promotion of variables, thus

U = 0
U = U + 1im

works properly. However, the following code

U = zeros(4)
U[2] = 1im

gives the error

ERROR: InexactError: Float64(0 + 1im)
Stacktrace:
 [1] Real at .\complex.jl:37 [inlined]
 [2] convert at .\number.jl:7 [inlined]
 [3] setindex!(::Array{Float64,1}, ::Complex{Int64}, ::Int64) at .\array.jl:847
 [4] top-level scope at REPL[9]:1

and I do not understand why.

Your first line can be read as:

U = 0 #Save as U the integer zero
U = U + 1im #Add whatever is in U with the imaginary unit, and bind the result to the variable name U

When you add whatever is in U and the imaginary unit, Julia will promote them to the appropriate type (the integer zero can be promoted to a complex number 0 + 0i. Then it performs the addition succesfully and stores the result with the name U.

In your second attempt you are doing something different:

U = zeros(4) #Create an array of length 4, where all the elements are of type `Float64` and fill it with zeros
U[2] = 1im # Store the imaginary unit as the second element of this array

In here your are first creating an array of Float64s. Then you are trying to store a complex number in that array. Julia tries to convert the Complex to a Float64 in order to store it in your array, but there is no correct way of doing this, since your would lose information. Therefore Julia throws an error indicating that a complex cannot be converted exactly into a float. This is the error you are seeing.

3 Likes

Thanks for the extensive explanation.
So the best way is to overcome this problem is by directly assigning complex values to the array

U = zeros(4)im

You can build the array of that type like:

U = zeros(Complex{Float64},4)
3 Likes