python - 是否可以使用 scipy.integrate.fixed_quad 计算二重积分?

标签 python scipy numerical-integration

我正在尝试使用 n 阶高斯求积计算二重积分(在节点位于 (0,0)、(0,1)、(1,0) 的三角形上)。然而,运行

import scipy.integrate as integrate
f = lambda x,y: x+y
inside = lambda x: integrate.fixed_quad(f, 0, 1-x, args=(x,), n=5)[0]
outside = integrate.fixed_quad(inside, 0, 1, n=5)

给予

Traceback (most recent call last): File "", line 1, in File "/Users/username/anaconda/lib/python3.5/site-packages/scipy/integrate/quadrature.py", line 82, in fixed_quad return (b-a)/2.0 * np.sum(w*func(y, *args), axis=0), None File "", line 1, in File "/Users/username/anaconda/lib/python3.5/site-packages/scipy/integrate/quadrature.py", line 78, in fixed_quad if np.isinf(a) or np.isinf(b):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

这是问题的第二部分Can scipy.integrate.fixed_quad compute integral with functional boundaries? .

最佳答案

您的问题的答案是,在特定条件下是的。

出于演示目的,我首先选择与您不同的界限(11 而不是 1 - x)。

通常,可以使用 dblquad 求解这些类型的积分:

area_dblquad = integrate.dblquad(lambda x, y: x + y, 0, 1, lambda x: 0, lambda x: 11)[0]

这里返回 66。这不是您在评论中提到的选项。

现在可以逐步执行此集成,它适用于 quad 以及 fixed_quad:

def integrand(x, y):
    return x + y

def fint_quad(x):
    return integrate.quad(integrand, 0, 11, args=(x, ))[0]

def fint_fixed_quad(x):
    return integrate.fixed_quad(integrand, 0, 11, args=(x, ), n=5)[0]

res_quad = integrate.quad(lambda x: fint_quad(x), 0, 1)
res_fixed_quad = integrate.fixed_quad(lambda x: fint_fixed_quad(x), 0, 1, n=5)

正如预期的那样,它们都返回 66。这表明它可以使用 scipy.integrate.fixed_quad 计算二重积分。

但是,当现在将上限更改回您之前的上限(从 111 - x)时,它仍然适用于 quad 但是 fixed_quad 崩溃了:

area_dblquad = integrate.dblquad(lambda x, y: x + y, 0, 1, lambda x: 0, lambda x: 1 - x)[0]
res_quad = integrate.quad(lambda x: fint_quad(x), 0, 1)

两者都返回 0.333333...,使用 fixed_quad 的调用会导致您收到错误。通过查看源代码可以理解错误:

x, w = _cached_roots_legendre(n)
x = np.real(x)
if np.isinf(a) or np.isinf(b):
    raise ValueError("Gaussian quadrature is only available for "
                         "finite limits.")
y = (b-a)*(x+1)/2.0 + a
return (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1), None

当一个人打印 ab 一个人得到:

a:  0
b:  1
a:  0
b:  [ 0.95308992  0.76923466  0.5         0.23076534  0.04691008]

所以对于 1-x 的调用,b 实际上是一个包含 n 元素的 numpy 数组,并且不能将数组与无穷大进行比较,这就是它崩溃的原因。无论这是预期的行为还是错误,我都无法回答;可能值得在 github 上提出一个问题。

关于python - 是否可以使用 scipy.integrate.fixed_quad 计算二重积分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42272817/

相关文章:

python - logistic/sigmoid 函数实现数值精度

python - 使用 scipy 的 trapz 函数进行积分

python - 通过 python 程序将参数传递给 Cygwin

python - 在 PyCharm 中使用 Ctrl/C 选择行,就像 Sublime Text 一样

python - 使用非 int64(indptr,索引)为点构建的 Scipy 稀疏矩阵

r - R 中的 2 倍(重复)积分

c++ - C++中的复合辛普森规则

python - pytesseract tessedit_char_whitelist 不接受报价

python - 解码 Unicode 字符串;这是什么意思,我该如何避免呢?

python - 将 Voronoi 图单元格区域转换为像素坐标列表