#Practical 4 2012 ST407 Monte Carlo methods #MH algorithm MetropHastings<-function(N=1000, s=1, init){ #Metropolis-Hastings algorithm #To provide N samples from the target distribution of interest #N=number of iterations #init = initial configuration x<-rep(NA, N+1) x[1]<-init #First co-ordinate is the initialisation #All other elements are samples from the target for(i in 2:(N+1)){ y<-rnorm(1, x[i-1], s) #The proposal density, a Normal centered around the current sample alpha<-dnorm(y,0,1) * dnorm(x[i-1], y, s) alpha<-alpha/(dnorm(x[i-1],0,1) * dnorm(y,x[i-1],s)) # The acceptance probability #The target density can be deduced to be the standard Normal u<-runif(1) if(u