Monte Carlo integration using importance sampling given a proposal function

后端 未结 1 718
没有蜡笔的小新
没有蜡笔的小新 2021-01-15 23:36

Given a Laplace Distribution proposal:

g(x) = 1/2*e^(-|x|)

and sample size n = 1000, I want to Conduct the Monte Carlo (MC) i

1条回答
  •  一整个雨季
    2021-01-16 00:15

    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
    

    0 讨论(0)
提交回复
热议问题