如何用 Python 的 scipy.integrate.quad 求多元函数的单积分?

How to evaluate single integrals of multivariate functions with Python's scipy.integrate.quad?

我正在尝试使用 scipy.integrate.quad 将一个功能集成到 Python 中。这个特定的函数有两个参数。我只想整合一个论点。示例如下所示。

from scipy import integrate as integrate
def f(x,a):  #a is a parameter, x is the variable I want to integrate over
    return a*x

result = integrate.quad(f,0,1)

此示例不起作用(您可能很清楚),因为 Python 在我尝试时提醒我:

TypeError: f() takes exactly 2 arguments (1 given)

我想知道如何使用 integrate.quad() 在给定的函数通常是多变量函数时在单变量意义上进行积分,额外的变量为函数提供参数。

使用args参数(参见scipy documentation):

result = integrate.quad(f,0,1, args=(a,))

args=(a,)中的逗号是必需的,因为必须传递一个元组。

the scipy documentation 中找到了答案。

您可以执行以下操作:

from scipy import integrate as integrate
def f(x,a):  #a is a parameter, x is the variable I want to integrate over
    return a*x

result = integrate.quad(f,0,1,args=(1,))

quad 方法中的 args=(1,) 参数将使 a=1 用于积分计算。

这也可以传递给具有两个以上变量的函数:

from scipy import integrate as integrate
def f(x,a,b,c):  #a is a parameter, x is the variable I want to integrate over
    return a*x + b + c

result = integrate.quad(f,0,1,args=(1,2,3))

这将使 a=1, b=2, c=3 用于积分评估。

对于要以这种方式集成的函数,要记住的重要一点是将要集成的变量置于函数的 第一个 参数上。