You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Example 2: Computing the areas within a unit-square
S=10000# number of MC samples# x and y are independent uniform RVsx=runif(S)
y=runif(S)
# area below the diagonalz=x>y
mean(z)
# set satysfying x<y^2z=x<y^2
mean(z)
Example 3: Convergence and MC error
S=5e4x=rgamma(rate=2,shape=4,n=S)
runMean=cumsum(x)/(1:length(x))
plot(runMean,type='l',col=4) ; abline(h=2,col=2)
## Let's now see the MC error on estimating the pth quantileprob=.99rate=2shape=4x=rgamma(rate=rate,shape=shape,n=S)
estPercentile<-rep(NA,length=S-100)
for(iin1:length(estPercentile)){
estPercentile[i]<-quantile(x=x[1:(100+i)],prob=prob)
print(i)
}
plot(estPercentile,type='l',col=4); abline(h=qgamma(rate=rate,shape=shape,p=prob),col=2)
Example 4: Approximating the distribution of a deterministic function of a RV
## Approximating the posterior density of log(lambda) in the gamma-poisson model## Gamma Poisson ModelN=100# sample sizelambda=4S=1e5# # of MC samplesy=rpois(n=N,lambda=lambda) # data# prior hyperparametersbPrior=5# our 'prior sample size'aPrior=10# our 'prior n*yBar'# posterior hyper-parametersaPost=aPrior+ sum(y)
bPost=bPrior+N# The posterior density is rgamma(rate=bPost, shape=aPost,..)x<-rgamma(rate=bPost, shape=aPost,n=S) # samples from the posterior distribution
mean( x) #MC Estimate of the posterior meanaPost/bPost# true posterior mean
mean(y) # MLEaPrior/bPrior# prior mean## Estimating the posterior density of log(lambda)y=log(x)
plot(density(y))
Example 5: approximating the marginal likelihood
N=100# sample sizelambda=4S=1e5# # of MC samplesy=rpois(n=N,lambda=lambda) # data# prior hyperparametersbPrior=5# our 'prior sample size'aPrior=10# our 'prior n*yBar'# we first sample lambda from the prior and then evaluat the conditional likelihood# averaging integrates that function.log_condLikelihood<-rep(NA,S)
for(iin1:S){
lambda<-rgamma(rate=bPrior,shape=aPrior,n=1)
tmp<-dpois(x=y,lambda=lambda,log=T)
log_condLikelihood[i]=sum(tmp)
}