Skip to content

Instantly share code, notes, and snippets.

@emhart
Created April 27, 2012 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emhart/2512598 to your computer and use it in GitHub Desktop.
Save emhart/2512598 to your computer and use it in GitHub Desktop.
Code for Monte Carlo integration of a normal PDF
x <- seq(-4,4,length=1000)
y <- dnorm(x,0,1)
plot(x,y,type='l',ylim=c(0,.5))
###Set the lower limits of interest
ll <- -1
ul <- 1
######Hit and miss MC integration#####
###First pick domain
x.dom <- seq(-4,4,length=1000)
y.dom <- seq(0,.5,length=1000)
prog <- txtProgressBar(min=0, max=n.sim, char="*", style=3)
n.sim <- 10000
x.r <- y.r <- vector()
under.curve <- rep(0,n.sim)
for(i in 1:n.sim){
###Draw random x and y
x.r[i] <- sample(x.dom,1)
y.r[i] <- sample(y.dom,1)
if(y.r[i] < dnorm(x.r[i],0,1)){
###Set further constraints on the x axis
if(x.r[i] >= ll && x.r[i] <= ul){under.curve[i]<-1}}
setTxtProgressBar(prog, i)
}
plot(-100,-100,ylim=range(y.dom),xlim=range(x.dom),col=2,lwd=2)
points(x.r,y.r,col=under.curve+1,pch=19)
lines(x,y,col=2,lwd=4)
f.h <- sum(under.curve)/n.sim
V.samp <- diff(range(x.dom))*diff(range(y.dom))
###Approximate integration value is area
area <- f.h*V.samp
###compare to the true value
pnorm(ul,0,1) - pnorm(ll,0,1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment