Python(SymPy、SciPy),从字符串创建符号 lambda
我一直在努力获取方程的文本输入并将其评估为定积分。我需要一个可调用函数来传递给 scipy.integrate。
eq = "x**2"
func = lambda x: eq
func(2)
# outputs:
# x**2
# but if I:
func = lambda x: x**2
func(2)
# outputs:
# 4
I've struggling to take text inputs of an equation and evaluate it as a definite integral. I need a callable function to pass to scipy.integrate
.
eq = "x**2"
func = lambda x: eq
func(2)
# outputs:
# x**2
# but if I:
func = lambda x: x**2
func(2)
# outputs:
# 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不确定,但也许您正在寻找
注意,如果
eq
来自不受信任的来源(例如用户输入),则使用eval()
是危险的。Not sure, but maybe you are looking for
Note that using
eval()
is dangerous ifeq
is from an untrusted source (e.g. user input).您需要使用 eval 将 eq 作为代码运行,而不是将其视为字符串。
You need to use eval to run eq as code and not treat it as a string.
sympify 可能就是您正在寻找。它将字符串表达式转换为 sympy 对象。
例如:
您可以使用 autowrap 将 sympy 对象转换为可调用函数。
sympify may be what you are looking for. It converts a string expression into an sympy object.
For example:
And you can use autowrap to convert a sympy object into a callable function.
尝试 asteval 或 numexpr 可能是 eval() 和 Sympy.sympify().evalf() 的更安全的替代方案。
Try asteval or numexpr for possibly safer alternatives to eval() and Sympy.sympify().evalf().
我不断地遇到以下语法错误,并不懈地试图找出原因:
但是当我将 E 更改为:菜鸟错误时,问题按预期工作
。 :)
I continually got a syntax error for the following and relentlessly was trying to find out why:
But the issue worked as expected when I changed E to:
Rookie mistake. :)