Monte Carlo integration using importance sampling given a proposal function

痞子三分冷 提交于 2019-12-01 14:11:37

Now we can write a simple R function to sample from Laplace distribution:

## `n` is sample size
rlaplace <- function (n) {
  u <- runif(n, 0, 1)
  ifelse(u < 0.5, log(2 * u), -log(2* (1 - u)))
  }

Also write a function for density of Laplace distribution:

g <- function (x) ifelse(x < 0, 0.5 * exp(x), 0.5 * exp(-x))

Now, your integrand is:

f <- function (x) {
  ifelse(x > 0, exp(-sqrt(x) - 0.5 * x) * sin(x) ^ 2, 0)
  }

Now we estimate the integral using 1000 samples (set.seed for reproducibility):

set.seed(0)
x <- rlaplace(1000)
mean(f(x) / g(x))
# [1] 0.2648853

Also compare with numerical integration using quadrature:

integrate(f, lower = 0, upper = Inf)
# 0.2617744 with absolute error < 1.6e-05
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!