Python(SymPy、SciPy),从字符串创建符号 lambda

发布于 2024-11-05 00:05:25 字数 209 浏览 4 评论 0原文

我一直在努力获取方程的文本输入并将其评估为定积分。我需要一个可调用函数来传递给 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

随梦而飞# 2024-11-12 00:05:43

不确定,但也许您正在寻找

eq = "x**2"
func = eval("lambda x: " + eq)

注意,如果 eq 来自不受信任的来源(例如用户输入),则使用 eval() 是危险的。

Not sure, but maybe you are looking for

eq = "x**2"
func = eval("lambda x: " + eq)

Note that using eval() is dangerous if eq is from an untrusted source (e.g. user input).

夏了南城 2024-11-12 00:05:43

您需要使用 eval 将 eq 作为代码运行,而不是将其视为字符串。

eq = "x**2"
func = lambda x: eval(eq)
func(2)

# outputs:
# 4

You need to use eval to run eq as code and not treat it as a string.

eq = "x**2"
func = lambda x: eval(eq)
func(2)

# outputs:
# 4
冰雪之触 2024-11-12 00:05:43

sympify 可能就是您正在寻找。它将字符串表达式转换为 sympy 对象。

例如:

import sympy as sp
f=sp.sympify('x**2+sin(y)')

您可以使用 autowrap 将 sympy 对象转换为可调用函数。

sympify may be what you are looking for. It converts a string expression into an sympy object.

For example:

import sympy as sp
f=sp.sympify('x**2+sin(y)')

And you can use autowrap to convert a sympy object into a callable function.

怎言笑 2024-11-12 00:05:43

尝试 astevalnumexpr 可能是 eval() 和 Sympy.sympify().evalf() 的更安全的替代方案。

Try asteval or numexpr for possibly safer alternatives to eval() and Sympy.sympify().evalf().

大姐,你呐 2024-11-12 00:05:43

我不断地遇到以下语法错误,并不懈地试图找出原因:

E="2x+1"
F=lambda x: (x, eval(E)) # to get an xy coordinate 

但是当我将 E 更改为:菜鸟错误时,问题按预期工作

E="2*x+1"

。 :)

I continually got a syntax error for the following and relentlessly was trying to find out why:

E="2x+1"
F=lambda x: (x, eval(E)) # to get an xy coordinate 

But the issue worked as expected when I changed E to:

E="2*x+1"

Rookie mistake. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文