#This code demonstrates use of rejection sampling to generate a #random sample from the density that is a half circle on (-1,1) #i.e., density is (propotional to) f(y)=sqrt(1-y^2) #Plot the shape of the density x=seq(-1,1,0.001) f=sqrt(1-x^2) par(mfrow=c(2,1),mar=c(5,5,4,4)) plot(x,f,type="l",ylab=expression(sqrt(1-x^2))) #Generate from Uniform(-1,1) nsamps=1000000 g=runif(nsamps,-1,1) hist(g,nclass=100) #Apply rejection sampling y=g[rbinom(nsamps,1,sqrt(1-g^2))==1] hist(y,nclass=100)