Encountering Method error when using abs2 function on a Complex{Num}

The issue is not with abs2. From the stacktrace, we have the lines

  [1] convert(::Type{Float64}, x::Num)
    @ Base .\number.jl:7
  [2] setindex!(A::Vector{Float64}, x::Num, i1::Int64)
    @ Base .\array.jl:1021

We see here that we are attempting to store a Num into a Vector{Float64} (via setindex!, which is used for x[i] = v syntax). To do this, we see that to do this we attempt to convert a Num to a Float64 so that we can store it, but the MethodError indicates this operation tries Float64(::Num) which is not defined.

A MWE is

using Symbolics
x = zeros(Float64, 1)
v = Num(1.0)
x[1] = v # MethodError

We need to tell the system how to do this conversion. The docs indicate that Symbolics.value can be used to extract the value from a Num.

So a fix is to instead use

x[1] = Symbolics.value(v)

In general, try not to post big code for small problems. You should attempt to localize the problem and create a small example showing the error (this can be difficult initially but gets easier the more familiar you become with the language). I provide an example of doing this above.

2 Likes