朱莉娅:如何将符号表达式转换为函数? [英] Julia: how do I convert a symbolic expression to a function?

查看:123
本文介绍了朱莉娅:如何将符号表达式转换为函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用SymPy包( https://github.com/jverzani/SymPy.jl).我现在想使用Roots包( https://github.com/JuliaLang/Roots.jl).但是,我无法弄清楚如何使用fzeros方法查找根,因为该方法只能应用于类型为Function而不是Sym的对象,这是我的表达式的类型.

这是我正在尝试做的一个例子.我创建一个符号"x"和一个符号表达式sin(x).现在,让我们尝试在值-10和10之间找到sin(x)的零:

using SymPy
x = sym"x"
expr = sin(x)
using Roots
fzeros(expr,-10,10)

这是错误:

ERROR: `fzeros` has no method matching fzeros(::Sym, ::Int64, ::Int64)

如何将Sym类型的表达式转换为Function类型,以便找到根?

解决方案

[更新:在许多情况下,以下讨论已被最近引入的lambdify函数所取代.调用lambdify(expr)创建一个julia函数,该函数不会回调SymPy进行评估,因此应该更快.它应该适用于大多数(当然不是全部)表达式.]

这是一个两步过程:

convert(Function, expr)

在您的情况下,

将返回自由变量x的函数.但是,函数值仍然是符号性的,不能与fzeros一起使用.可以猜测输入,但是返回值的类型是另一回事.但是,在这种情况下,强制浮动会起作用:

fzeros(x -> float(convert(Function, expr)), -10, 10)

(您也可以使用a -> float(replace(expr, x, a))进行此操作.)

对于这个简单的示例,solve(expr)也将起作用,但是通常不会公开SymPy中的findroot函数,因此最后通过SymPy进行数值根运算不是一种解决方法-用户.

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 (https://github.com/JuliaLang/Roots.jl). However, I cannot figure out how to use the fzeros method for finding the roots, since this can only be applied on an object with the type Function rather than Sym, which is the type of my expression.

Here's an example of what I'm trying to do. I create a symbolic "x" and a symbolic expression sin(x). Now lets try to find the zeros of sin(x) between the values -10 and 10:

using SymPy
x = sym"x"
expr = sin(x)
using Roots
fzeros(expr,-10,10)

Here's the error:

ERROR: `fzeros` has no method matching fzeros(::Sym, ::Int64, ::Int64)

How do I convert an expression with Sym type to Function type, so I can find the roots?

解决方案

[UPDATE: The discussion below has been superseded in many cases by the recently introduced lambdify function. The call lambdify(expr) creates a julia function that does not call back into SymPy to evaluate, so should be much faster. It should work for most, but certainly not all, expressions.]

It is a two step process:

convert(Function, expr)

will return a function of the free variables, x, in your case. However, the function values are still symbolic and can't be used with fzeros. The inputs can be guessed, but the type of the return value is another story. However, coercing to float will work in this case:

fzeros(x -> float(convert(Function, expr)), -10, 10)

(You could also do this with a -> float(replace(expr, x, a)).)

For this simple example solve(expr) will also work, but in general, the findroot function in SymPy is not exposed, so numeric root solving via SymPy isn't a workaround without some effort by the end-users.

这篇关于朱莉娅:如何将符号表达式转换为函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆