R中积分函数的精度问题

Precision issue of integrate function in R

在 R 中使用 integrate() 函数时,一些精度问题让我感到困惑。比如我要集成这个功能:

p <- function(x)exp(-x^2)

我选择区间[-1e3,1e3],它给出了正确答案:

> integrate(p, -1e3, 1e3)
1.772454 with absolute error < 7.8e-09

但是如果我把区间扩大到[-1e9,1e9],那就错了:

> integrate(p, -1e9, 1e9)
0 with absolute error < 0

为了不调音程,我尝试使用Inf:

> integrate(p, -Inf, Inf)
1.772454 with absolute error < 4.3e-06

可以用,但很快我发现还有一些其他问题:

> integrate(p, -Inf, -Inf)
1.772454 with absolute error < 4.3e-06

在这种情况下,它无法给出正确答案 0。

我想知道为什么会出现这些精度问题,有什么方法可以避免这样的问题?

建议您使用Inf,-Inf。有趣的是,当 integrate() 用作上限时,它似乎正在将 -Inf 转换为 Inf。 :

> integrate(p, -Inf, -1*.Machine$double.xmax)
0 with absolute error < 0
> integrate(p, -Inf, -2*.Machine$double.xmax)
1.772454 with absolute error < 4.3e-06

这没有达到我们的预期。让我们尝试将积分一分为二,首先:

> integrate(p, 0, Inf)
0.8862269 with absolute error < 2.2e-06
> integrate(p, 0, 1e100)
0 with absolute error < 0
> integrate(p, 0, 1e2)
0.8862269 with absolute error < 9.9e-11

这似乎与使用 Inf-Inf 的建议完全一致,但请注意切换符号时会发生什么:

> integrate(p, 0, -Inf)
0.8862269 with absolute error < 2.2e-06
> integrate(p, 0, -1e100)
0 with absolute error < 0
> integrate(p, 0, -1e2)
-0.8862269 with absolute error < 9.9e-11

最后,您可以随时更改公差、细分,但在这种情况下这对您没有帮助。

编辑:正如@Ben 指出的那样,这是一个小错误,因为 integrate 检查上限是否有限,而不是 Inf(或 -Inf)。