R code for generating standard normals using Metropolis sampler with uniform proposal distribution:
# metropolis for N(0,1) based on uniform candidates
norm<-function (n, alpha) { vec <- vector("numeric", n) x <- 0 vec[1] <- x for (i in 2:n) { innov <- runif(1, -alpha, alpha) can <- x + innov aprob <- min(1, dnorm(can)/dnorm(x)) u <- runif(1) if (u < aprob) x <- can vec[i] <- x } vec } normvec<-norm(10000,1) par(mfrow=c(2,1)) plot(ts(normvec)) hist(normvec,30) par(mfrow=c(1,1))
时间: 2024-11-09 00:51:21