Metropolis Algo

source('DBDA2E-utilities.R')
Bern <- function(x) rbinom(1,1,x)
Metro <- function(
SD=0.02,
.z=14,
.N=20,
a=1,
b=1,
k=50000,
Print=TRUE){
theta=numeric()
theta[1]=0.01
likely <- function(x,z=.z,N=.N) x^z*(1-x)^(N-z)
for(i in 1:(k-1)){
delta=rnorm(1,0,SD)
theta_p=theta[i]+delta
p=min(1,likely(theta_p)*dbeta(theta_p,a,b)/
(likely(theta[i])*dbeta(theta[i],a,b)))
theta[i+1]=theta[i]+Bern(p)*delta
}
if(Print){
# plot(theta,1:k,type='l')
plotPost(theta,cenTend = 'mean',cex.lab = 1)
plot(theta[1:100],1:100,type='l',xlim=c(0,1))
plot(theta[(k-100):k],(k-100):k,type='l',xlim=c(0,1))}
invisible(theta)
}