在 SymPy 中解析包含用户定义函数的符号表达式 [英] Parsing a symbolic expression that includes user-defined functions in SymPy
本文介绍了在 SymPy 中解析包含用户定义函数的符号表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些调用其他函数的方程.我想象征性地写这个,在Sympy中可以这样做吗?
I have some equations that call other functions. I want to write this symbolically, is it possible to do this in Sympy?
这是我正在尝试做的一个简化示例:
Here's an simplified example of what I'm trying to do:
x = sp.Symbol('x')
omega = sp.Function('omega')(x ** 2)
eq_1 = sp.sympify("omega(x)")
eq_1 使用参数 x 调用函数 omega,返回 x**2.关于如何实现这一点的任何想法?
eq_1 is calling function omega with argument x , returning x**2. Any ideas on how I can implement this?
推荐答案
x = sp.Symbol('x')
omega = sp.Lambda(x, x**2)
eq_1 = sp.sympify("omega(x)", locals={"omega": omega})
关键点:
- Lambda 是一种创建执行特定操作的 SymPy 函数的方法
locals
是sympify
的参数,它将输入的子字符串(例如omega")链接到您创建的 SymPy 对象.没有它,sympify
只会链接像exp
或sin
这样的内置函数,但它不会猜测输入中是否有omega"真正的意思是你的函数,或者一个无关的字母 omega.
- Lambda is a way to create a SymPy function which performs a specific operation
locals
is a parameter ofsympify
which links substrings of the input, such as "omega", to the SymPy objects you created. Without it,sympify
will only link built-in functions likeexp
orsin
, but it will not be guessing whether "omega" in the input really means your function, or an unrelated letter omega.
这篇关于在 SymPy 中解析包含用户定义函数的符号表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文