julia.core.JuliaError: Exception 'MethodError: no method matching Float64(::Num)

julia.core.JuliaError: Exception 'MethodError: no method matching Float64(::Num)

尝试调用 python 中的 julia ModellingToolkit(使用 JuliaCall)并在尝试定义符号变量时出现以下错误。

from julia import Main as jl

jl.eval("using ModelingToolkit")
jl.eval("using DifferentialEquations")
jl.eval("@variables t")

结果出现如下错误

julia.core.JuliaError: Exception 'MethodError: no method matching Float64(::Num)
Closest candidates are:
  (::Type{T})(::Real, !Matched::RoundingMode) where T<:AbstractFloat at ~/Julia/julia-1.7.2/share/julia/base/rounding.jl:200
  (::Type{T})(::T) where T<:Number at ~/Julia/julia-1.7.2/share/julia/base/boot.jl:770
  (::Type{T})(!Matched::VectorizationBase.Double{T}) where T<:Union{Float16, Float32, Float64, VectorizationBase.Vec{<:Any, <:Union{Float16, Float32, Float64}}, VectorizationBase.VecUnroll{var"#s35", var"#s34", var"#s33", V} where {var"#s35", var"#s34", var"#s33"<:Union{Float16, Float32, Float64}, V<:Union{Bool, Float16, Float32, Float64, Int16, Int32, Int64, Int8, UInt16, UInt32, UInt64, UInt8, SIMDTypes.Bit, VectorizationBase.AbstractSIMD{var"#s34", var"#s33"}}}} at ~/.julia/packages/VectorizationBase/xnzUX/src/special/double.jl:84
  ...' occurred while calling julia code:
convert(PyCall.PyObject, @variables t)

似乎 supertype(Num) 产生 Real,因此 PyCall 在 Python.

中显示之前尝试将其转换为 Float64

一个简单的解决方法是提供您自己的包装器:

jl.eval("Float64(::Num) = NaN")

现在您将无法从 ModelingToolkit 中看到对象,但您可以在 Python 中操作它们。

>>> jl.eval("@variables x y")
[nan, nan]
>>> jl.eval("@show simplify((x+y)^2 - (x-y)^2; expand=true)")
simplify((x + y) ^ 2 - (x - y) ^ 2; expand = true) = 4x*y
nan