I want to skip an error during a loop in julia. The example is below. I want to calculate square root of each element in a vector. Since sqrt(-16) is a complex value, Julia will report error and stop the loop. I would like julia to continue the loop when there is an error in the loop. The output I am looking for is that result = [1, 2, 3, 99999, 5, 6] where 99999 indicates there is an error.
vec = [1,4,9,-16,25,36]
result = zeros(6)
for i = 1:6
result[i] = sqrt(vec[i])
end
A try
/catch
will intercept the error. Within the catch
block, you can discard the error and return the sentinel value:
vec = [1,4,9,-16,25,36]
result = zeros(6)
for i = 1:6
result[i] = try
sqrt(vec[i])
catch
999999
end
end
I assume this is a toy example. I will reiterate Julia's style guide: its best to avoid the error in the first place.
In addition to the other answer which uses try / catch
in the spirit of your question, you have a few more options. Probably the best approach would be:
function mysqrt(x)
if x < 0
999999.0
else
sqrt(x)
end
end
vec = [1,4,9,-16,25,36]
julia> mysqrt.(vec)
6-element Array{Float64,1}:
1.0
2.0
3.0
999999.0
5.0
6.0
Though I would strongly suggest you not use 999999.0
as your sentinel value but instead use NaN
or missing
.
Another option available to you would be to lift vec
to a Vector{Complex}
so that you don't run into domain errors, but this will come at a performance cost. That would look like
julia> sqrt.(complex(vec))
6-element Array{Complex{Float64},1}:
1.0 + 0.0im
2.0 + 0.0im
3.0 + 0.0im
0.0 + 4.0im
5.0 + 0.0im
6.0 + 0.0im
and then you can filter the vector by real and imaginary parts as you wish.
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