【问题标题】:Python: Integration over Multiple Dimensions of function taking an array inputPython:采用数组输入的函数的多维集成
【发布时间】:2021-05-11 16:04:57
【问题描述】:

我在使用数组输入计算函数的多个积分时遇到了困难。我想使用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。

感谢您的帮助。

【问题讨论】:

  • 我知道您自己找到了解决方案,习惯上不编辑问题而是实际提供答案。
  • 我把它移下来了。

标签: python-3.x numerical-methods numerical-integration quad n-quads


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 2016-12-09
    相关资源
    最近更新 更多