Python: 如何将符号表达式转换为函数,使其可以进行数值积分?

Python: how is it possible to convert a symbolic expression into a function so that it can be numerically integrated?

我一直在使用 Python 中的符号表达式,并且已经得出了一个我想要在一定时间间隔内整合的表达式。表达式包含 pi.

问题是我还没有弄清楚如何将这个表达式转换成一个可以作为参数输入到 scipy.integrate.quad 的函数。我的代码相关部分如下:

from sympy import *
import numpy as np
import scipy.integrate as integrate
from sympy.utilities.lambdify import lambdify

# this defines the symbols that
# we will be using in our computations:
x, y, g, y1, a0, a1, a2 = symbols('x y g y1 a0 a1 a2')

# this defines what a0 and a1,
# and what y and y' are:

a0 = 2
a1 = -((2/pi)+(pi*a2))

y = a0+a1*x+a2*x**2
y1 = y.diff(x)   

# this defines the integrand that
# here represents the Lagrangian:

L=sqrt((1+y1**2)/(2*g*y))

# this differentiates the above with
# respect to a2, to define the integrand:

difL = L.diff(a2)

我要整合的是difL。我尝试通过以下方式将其定义为函数:

def integrand(a2):
    return difL

f = lambdify(x, integrand(a2))

无济于事。所以我的问题是:如何将 difL 转换为可以使用 scipy.integrate.quad 集成的函数?

而且,作为免责声明,我是 Python 的新手,所以如果我使用的术语不正确,请告诉我。

不需要scipy,sympy完全可以进行数值积分。现在,您有很多未定义的变量(例如 g),因此我将构建一个更简单的示例,让您适应您的问题。

from sympy import *
from sympy.abc import x, a

# x is variable, a is parameter
y = x**2 + a

# integrate over x from 0 to 1; then evaluate with the value of the parameter
integrate(y, (x, 0, 1)).evalf(subs={a: -4})