# STATS 4CI3/6CI3 Winter 2019 # Examples done in class on March 18-21 2019 # Bayesian Inference for a binomial probability # The prior density prior <- function(theta) pi/2*sin(pi*theta) # The data n <- 10 x <- 2 # The posterior function (up to a normalizing constant). posterior <- function(theta, x, n) 100*sin(pi*theta)*theta^x*(1-theta)^(n-x) # Generate samples using Accept-Reject # Find the maximum of the density ratio by numeric optimization max.ratio <- optimize(function(theta) posterior(theta, 2, 10), interval=c(0,1), maximum=TRUE) M <- max.ratio$objective set.seed(18032019) N <- 1000000 Y <- runif(N) # Candidates py <- posterior(Y, x, n)/M # the acceptance probability U <- runif(N) theta.obs <- Y[U