Skip to content

Instantly share code, notes, and snippets.

@piroyoung
Created December 23, 2013 13:07
Show Gist options
  • Save piroyoung/8096883 to your computer and use it in GitHub Desktop.
Save piroyoung/8096883 to your computer and use it in GitHub Desktop.
MCMC visualization from sublime text
Sample <- c(4,3,4,7,7,
6,3,7,8,0,
1,7,8,6,7,
4,4,7,3,4)
n <- 8
Step <- 0.001
mcmcStep <- 20000
mcmcTimes <- 20
Z <- 1:mcmcStep
LE <- function(p){
prod(dbinom(Sample,n,p))
}
Culc.metro <- function(ini){
X <- 1:mcmcStep
q <- ini
for(i in 1:mcmcStep){
d <- Step *(2 * rbinom(1,1,0.5) - 1)
q1 <- q + d
if(LE(q) < LE(q1)){
q <- q1
}else if(LE(q) > LE(q1)){
if(rbinom(1,1,LE(q1)/LE(q)) == 1){
q <- q1
}
}
X[i] <- q1
}#1:100
X #return
}
Init <- round(runif(mcmcTimes, min=0, max=1),2)
plot(Z,Culc.metro(Init[1]),ylim = c(0,1),type = "l")
for(i in 2:mcmcTimes){
par(new = TRUE)
plot(Z,Culc.metro(Init[i]),ylim = c(0,1),type = "l")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment