在R中集成函数返回错误

时间:2014-10-15 00:34:00

标签: r integral

我有一个定义为

的函数
tail <- function(x) {585.1961*x^-2.592484}

当我试图将其从5000到Inf的积分时,它会返回错误:

> integrate(tail, 5000, Inf)
Error in integrate(tail, 5000, Inf) : the integral is probably divergent

然而,从1000到Inf和从1000到5000的整合都很好:

> integrate(tail, 1000, Inf)
0.006134318 with absolute error < 2.5e-05
> integrate(tail, 1000, 5000)
0.005661634 with absolute error < 4.9e-09

Isn&#39; t integrate(tail, 5000, Inf)是否等于integrate(tail, 1000, Inf) - integrate(tail, 1000, 5000)?为什么会导致不同的积分?

1 个答案:

答案 0 :(得分:2)

您的默认容差(.Machine$double.eps^0.25)太大,因此我们对其进行更改:

> tail <- function(x) {585.1961*x^-2.592484}
> integrate(tail, 5000, Inf,rel.tol =.Machine$double.eps^0.5 )
0.0004727982 with absolute error < 1.5e-09

这与以下内容大致相同:

> integrate(tail, 1000, Inf)$val-integrate(tail, 1000, 5000)$val
[1] 0.0004726847

当然,您可以将容差设置为.Machine$double.eps,但这需要花费时间:

> library(microbenchmark)
> a<-function(x) for(i in 1:50) integrate(tail, 5000, Inf,rel.tol =.Machine$double.eps^x )
> microbenchmark(a(0.5),a(0.7),a(1))
Unit: milliseconds
   expr      min       lq   median       uq      max neval
 a(0.5) 10.44027 10.97920 11.12981 11.40529 19.70019   100
 a(0.7) 13.02904 13.69813 13.95942 14.89460 23.02422   100
   a(1) 15.14433 15.96499 16.12595 16.38194 26.27847   100

例如。时间增加约50 pct。