Julia: how do I convert a symbolic expression to a function?

后端 未结 2 1299
遇见更好的自我
遇见更好的自我 2021-01-12 22:07

I have created a symbolic expression using the SymPy package (https://github.com/jverzani/SymPy.jl). I want to now find the roots of that expression using the Roots package

2条回答
  •  被撕碎了的回忆
    2021-01-12 22:32

    With Julia 0.6 this works straight out of box:

    julia> using SymPy, Roots
    
    julia> x = Sym("x")
    x
    
    julia> expr = sin(x)
    sin(x)
    
    julia> fzeros(expr, -10, 10)
    7-element Array{Float64,1}:
     -9.42478
     -6.28319
     -3.14159
      0.0
      3.14159
      6.28319
      9.42478
    

    But it's a lot slower than pure Julia solution. Here are some benchmarks I ran with BenchmarkTools:

    Naive Solution (6.8s):

    fzeros(expr, -10, 10)
    

    Pure Julia (1.5ms):

    fzeros(x-> sin(x), -10, 10)
    

    Semi-Naive (7.6ms):

    fzeros(Function(expr), -10, 10)
    

    Explicit Conversion (3.8ms):

    expr2 = Function(expr)
    fzeros(expr2, -10, 10)
    

提交回复
热议问题