我的Metropolis-Hastings问题具有静态二项分布,所有提议分布q(i,j)均为0.5。参考图和直方图,算法应该如此清晰地以0.5为中心,从二项分布的概率?
pi <- function(x, n, p){
# returning value from binomial distribution
result <- (factorial(n) / (factorial(x) * factorial(n - x))) *
p^x * (1 - p)^(n - x)
return(result)
}
metropolisAlgorithm <- function(n, p, T){
# implementation of the algorithm
# @n,p binomial parameters
# @T number of time steps
X <- rep(runif(1),T)
for (t in 2:T) {
Y <- runif(1)
alpha <- pi(X[t - 1], n, p) / pi(Y, n, p)
if (runif(1) < alpha) X[t] <- Y
else X[t] < X[t - 1]
}
return(X)
}
# calling M-H algorithm and plotting result
test <- metropolisAlgorithm(40,0.5,5000)
par(mfrow=c(2,1))
plot(test, type = "l")
hist(test, breaks = 40)