In: Statistics and Probability
What is the code for running the Monte Carlo integration technique for the integral of the standard normal distribution at 2? Please include a graph of sample size vs relative error in the solution.
The following is the R-code for the MonteCarlo Integration:
#Code for MC Integration for a Single Instance
Nsim <- 100 #Number of simulations
x <- rnorm(Nsim) #Drawing a random sample
mc_value <- mean(x<=2) #Value of MC Estimator
pnorm(2) #Actual Value
#Code for MC Integration for Increasing Sample Sizes
Nsim <- 10^4
x <- rnorm(Nsim)
mc_valuearray <- cumsum(x<=2)/(1:Nsim) #Array of MC estimates
rel_error <- (mc_valuearray-pnorm(2))/pnorm(2)
plot(1:Nsim,rel_error,type="l",main="Relative Error vs Sample
Size",xlab="Sample Size",ylab="Relative Error")
Important Note:
Here inputing "x<=2" in the R console returns a logical array containing TRUEs and FALSEs. As you may know, R treats TRUE as a 1 and FALSE as a 0, and they can be mathematically added. So, the commands "mean" and "cumsum" can be applied to logical arrays.
Here is the plot: