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

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

问题描述

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

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.

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

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)

这是错误:

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

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

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

推荐答案

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

[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.]

这是一个两步过程:

convert(Function, expr)

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

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)

(您也可以使用 a -> float(replace(expr, x, a)).)

对于这个简单的例子,solve(expr) 也可以工作,但一般来说,SymPy 中的 findroot 函数是不暴露的,所以如果没有最终用户的一些努力,通过 SymPy 求解数字根不是一种解决方法.

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.

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

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