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

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