When using the integrate()
function in R, some precision issues make me confused. For example, I want to integrate this function:
p <- function(x)exp(-x^2)
I choose the interval [-1e3,1e3], and it gives the right answer:
> integrate(p, -1e3, 1e3)
1.772454 with absolute error < 7.8e-09
But if I expand the interval to [-1e9,1e9], it's wrong:
> integrate(p, -1e9, 1e9)
0 with absolute error < 0
In order not to tune the interval, I try to use Inf
:
> integrate(p, -Inf, Inf)
1.772454 with absolute error < 4.3e-06
It works, but soon I find there are some other problems :
> integrate(p, -Inf, -Inf)
1.772454 with absolute error < 4.3e-06
In this case it can't give the right answer 0.
I wonder why these precision problem will happen and are there any methods to avoid such problem?