Monte Carlo integration - How to find the error

Viewed 448

I need to apply the Monte Carlo integration to estimate the following function in [0,1]:

f(x) = exp(-ax) cos(bx) 

where a=0.3060734 and b=0.11221230. But, I need to use four different Monte Carlo variations: hit or miss, crude, importance sampling and variance control. All of them are on page 392 from this book:https://edisciplinas.usp.br/pluginfile.php/5168099/mod_resource/content/1/Julio%20Stern.pdf. However, after estimating the integral of f(x) in each variation, I need to calculate the relative error ( | g* - g | / g ) < 1% where g is the real value of the integral (unknown) and g* is the estimated value. How do I calculate the error? I thought about using the variance of each variation, but I am not sure about how to do that and make it < 1%. I already have the code calculating each estimation and variance. OBS: I am supposed to use Python or R.

1 Answers

Here is an example (with R) for your Monte Carlo simulation for integration

a <- 0.3060734
b <- 0.11221230
f <- function(x) exp(-a*x)*cos(b*x)

MCsim <- function(n) {
  gs <- sapply(n,function(k) mean(runif(k) <= f(runif(k))))
  g <- integrate(f,0,1)$value
  rel_err <- abs(gs-g)/g
  data.frame(n,gs,g,rel_err)
}

n <- 10**(1:7)
res <- MCsim(n)

such that

> res
      n        gs         g      rel_err
1 1e+01 0.8000000 0.8597815 6.953106e-02
2 1e+02 0.8700000 0.8597815 1.188497e-02
3 1e+03 0.8590000 0.8597815 9.089768e-04
4 1e+04 0.8570000 0.8597815 3.235149e-03
5 1e+05 0.8606900 0.8597815 1.056639e-03
6 1e+06 0.8596650 0.8597815 1.355245e-04
7 1e+07 0.8597802 0.8597815 1.536980e-06
Related