Run Code  | API  | Code Wall  | Misc  | Feedback  | Login  | Theme  | Privacy  | Patreon 

Monte Carlo Integration

set.seed(100)
#######################################
## Monte Carlo simulation for estimating 
## integral (3x^2 + 5x)_0^1
#######################################
# True value is 3.5
true <- 3.5

# 1. Set n
# 2. Generate n Uniform[0,1]
# 3. Find mean of g(x) = 3x^2 + 5x

n <- 10
samp <- runif(n = n, min = 0, max = 1)
gx <- 3*samp^2 + 5*samp
mean(gx)

# Repeating for larger n
n <- 100
samp <- runif(n = n, min = 0, max = 1)
gx <- 3*samp^2 + 5*samp
mean(gx)

n <- 1000
samp <- runif(n = n, min = 0, max = 1)
gx <- 3*samp^2 + 5*samp
mean(gx)

# Make a running plot of the estimate
n <- 5e3
samp <- runif(n = n, min = 0, max = 1)
gx <- 3*samp^2 + 5*samp

plot.ts(cumsum(gx)/(1:n), ylab = "Running Average", xlab = "n")
abline(h = true, col = "red")
 run  | edit  | history  | help 0