reject <- function(y,nreps){ # # # This function performs rejection sampling for a posterior as defined # in the function "posterior." The density actually sampled from is # that of a random variable 10Y, where Y has the beta(3,3) distribution. # # Warning: This function is not for a general setting! It is just an # example of how to do rejection sampling. # # samples=1:nreps counts=rep(1,len=nreps) for(i in 1:nreps){ x=10*rbeta(1,3,3) ratio=posterior(x,y)/(3*1.7*dbeta(x/10,3,3)/10^7) check=sign(runif(1)-ratio) while(check > 0){ counts[i]=counts[i]+1 x=10*rbeta(1,3,3) ratio=posterior(x,y)/(3*1.7*dbeta(x/10,3,3)/10^7) check=sign(runif(1)-ratio) } samples[i]=x } list(counts,samples) } posterior = function(theta,y){ n=length(y) poster=exp(-theta^2/50) for(i in 1:n){ poster=poster/(1+(y[i]-theta)^2) } poster }