为什么 scipy.integrate.quad 在这个积分的某个时间间隔内失败?

Why does scipy.integrate.quad fail for some interval of this integral?

重现:

# Use scipy to create random number for f(x) = 2x when x in [0,1] and 0, otherwise
from scipy.stats import rv_continuous
class custom_rv(rv_continuous):
    "custom distribution"
    def _pdf(self, x):
        if x >= 0.0 and x <=1.0:
            return 2*x
        else:
            return 0.0
rv = custom_rv(name='2x')
from scipy.integrate import quad
print(quad(rv._pdf, -10.0, 10.0))
print(quad(rv._pdf, -5.0, 5.0))
print(quad(rv._pdf, -np.inf, np.inf))

输出:

(0.0, 0.0) # for [-10,10]
(1.0, 1.1102230246251565e-15) # for [-5,5]
(1.0, 2.5284034865791227e-09) # for [-inf, inf]

上下文:

我正在尝试创建一个带有自定义 p.d.f 的随机变量: f(x) = 2*x 如果 x 在 [0,1] 内,否则 f(x) = 0.

这个随机变量不起作用,我尝试通过使用 quad.

检查 p.d.f 的积分来调试

我发现积分不一致。对于某些区间,如 (-inf, inf) 和 (-5,5),它是 1。但是,对于像 (-10,10) 这样的区间,它被评估为零,这是非常意外的。

知道这里出了什么问题吗?

看看 quad function documentation,如果你一直走到底部,你会看到:

Be aware that pulse shapes and other sharp features as compared to the size of the integration interval may not be integrated correctly using this method. A simplified example of this limitation is integrating a y-axis reflected step function with many zero values within the integrals bounds.

提供的例子是:

>>> y = lambda x: 1 if x<=0 else 0
>>> integrate.quad(y, -1, 1)
(1.0, 1.1102230246251565e-14)
>>> integrate.quad(y, -1, 100)
(1.0000000002199108, 1.0189464580163188e-08)
>>> integrate.quad(y, -1, 10000)
(0.0, 0.0)

所以想法是你的功能还不够"smooth",这就是为什么你能得到令人惊讶的结果。