Python:采用数组输入的函数的多维积分

Python: Integration over Multiple Dimensions of function taking an array input

我在使用数组输入计算函数的多重积分时遇到困难。我想使用 scipy.integrate's nquad function 因为我需要能够从 -np.inf to np.inf 进行积分(我正在使用概率密度函数)。问题是 nquad 期望一个函数被表述如下:

function(x_1, x_2, ..., x_n)

我需要集成的功能采用以下形式:

function(np.array([x_1, x_2, ..., x_n]))

有没有办法改变一个接受数组接受多个参数的函数?如果没有,是否有 nquad 的替代方案?我试过使用quadpy,但它说我的积分超过31,而实际值为1。

感谢您的帮助。

我找到了解决办法。我通过创建一个包含 *args 的包装函数、将 args 转换为 numpy 数组并集成包装函数来解决这个问题。

这是一个例子:

from scipy.integrate import nquad
from scipy.stats import multivariate_normal

mean = [0., 0.]
cov = np.array([[1., 0.],
                [0., 1.]])

bivariate_normal = multivariate_normal(mean=mean, cov=cov)

def pdf(*args):
    x = np.array(args)
    return bivariate_normal.pdf(x)

integration_range = [[-18, 18], [-18, 18]]

nquad(pdf, integration_range)

Output: (1.000000000000001, 1.3429066352690133e-08)