Misalkan sebaran posterior (target) bagi \(\theta\) adalah: \(g(\theta \mid y) = e^{-\theta}\) dengan \(\theta>0\)
Akan dilakukan sampling berdasarkan sebaran posterior tersebut
Sebaran posterior dinyatakan sebagai sebaran target
Sebaran kandidat (proposal) berbasis pada random-walk
Algoritma Metropolis–Hastings untuk mendapatkan sampel yang sebarannya proporsional pada target
Simulasi sebanyak N = 50 (sebagai ilustrasi untuk tracing)
set.seed(1111)
N = 50
theta <- rep(0, N)
iterasi <- rep(0, N)
alpha <- rep(0, N)
iterasi[1] <- 1
alpha[1] <- 1
theta[1] <- 3 # Sebagai nilai inisial bagi theta
for (i in 2:N) {
current.theta <- theta[i - 1]
iterasi[i] <- i
# Sebaran kandidat atau proposal berbasis Random-Walk
proposal.dtheta <- current.theta + rnorm(1, mean = 0, sd = 1)
# Peluang Penerimaan
alpha[i] <- min(1,target(proposal.dtheta) / target(current.theta))
# Perbandingan dengan sebaran Uniform(0,1)
if (runif(1) < alpha[i]) {
theta[i] <- proposal.dtheta
} else {
theta[i] <- current.theta
}
}