I am using Monte Carlo method to evaluate the integral above:
$$\int_0^\infty \frac{x^4sin(x)}{e^{x/5}} \ dx $$
I transformed variables using $u=\frac{1}{1+x}$ so I have the following finite integral:
$$\int_0^1 \frac{(1-u)^4 sen\frac{1-u}u}{u^6e^{\frac{1-u}{5u}}} \ du $$
I wrote the following code on R:
set.seed (666)
n <- 1e6
f <- function(x) ( (1-x)^4 * sin ((1-x)/x) ) / ( exp((1-x)/(5*x) ) * x^6 )
x <- runif(n)
I <- sum (f(x))/n
But I get the wrong answer, but if I integrate f(x) using the R built-in function and not Monte Carlo I get the right answer.
Best Answer
Let us use for instance sage to get the exact value of the integral (and some numerical approximation of this exact value).
Now back to
R
. Indeed, Monte Carlo delivers a number far away from this one, but theR
integral is a good approximation.The question asks for the reason. It is hard to analyze as a human the
x
sample above, but it is good to notice the big variance of the function after the substitution. For instance, on the following intervals...There are big numbers in the first lines of code, and small changes of the limits lead to "relatively big variations",
so even increasing
n
may not help. Here is a plot of the function under the integraland note that we have
1e6
random points chosen on the whole interval, only a part of them on the tiny interval with variation in the same big range. This explains the relatively big difference betweenJ
(101.9375
) and the true value (11.993560341832...
) of the integral.