
# file "Rmetnorm" -- a simple Metropolis algorithm in one dimension

g = function(y) { dnorm(y) }

h = function(y) { return(y) }

M = 4000  # run length
B = 2000  # amount of burn-in
#X = runif(1)  # overdispersed starting distribution
X = 20
sigma = 0.1  # proposal scaling
xlist = rep(0,M)  # for keeping track of chain values
hlist = rep(0,M)  # for keeping track of h function values
numaccept = 0;

for (i in 1:M) {
    Y = X + sigma * rnorm(1)  # proposal value
    U = runif(1)  # for accept/reject
    alpha = g(Y) / g(X)  # for accept/reject
    if (U < alpha) {
	X = Y  # accept proposal
        numaccept = numaccept + 1;
    }
    xlist[i] = X;
    hlist[i] = h(X);
}

cat("ran Metropolis algorithm for", M, "iterations, with burn-in", B, "\n");
cat("acceptance rate =", numaccept/M, "\n");
u = mean(hlist[(B+1):M])
cat("mean of h is about", u, "\n")

se1 =  sd(hlist[(B+1):M]) / sqrt(M-B)
cat("iid standard error would be about", se1, "\n")

varfact <- function(xxx) {
  2 * sum(acf(xxx, lag.max=200, plot=FALSE)$acf) - 1
}
thevarfact = varfact(hlist[(B+1):M])
se = se1 * sqrt( thevarfact )
cat("varfact = ", thevarfact, "\n")
cat("true standard error is about", se, "\n")
cat("approximate 95% confidence interval is (", u - 1.96 * se, ",",
						u + 1.96 * se, ")\n\n")

plot(xlist, type='l')
# acf(xlist, lag.max=200)
# acf(xlist[(B+1):M], lag.max=200)

