# X ~ exp(theta=2) # Want to generate 500 observations from X # inverse.cdf.r ############### # generate 500 observations y_i, i=1,...,500, from a Unif(0,1) random variable y <- runif(500, 0 , 1) # plug the y_i values into the inverse cdf to obtain x_i, i=1,...,500 x <- -2 * log(1-y) # plot true density grd <- seq(0,12,length=1000) pdf("inverse-cdf.pdf") plot(grd, 0.5*exp(-0.5*grd), type="l", xlab="x", ylab="f(x)", main="X ~ exp(theta=2)") # make a "rug" with the generated values rug(x) dev.off() # compute mean and variance of generated values # these should be close to E(X)=theta=2 and Var(X)=theta^2=4 cat("mean(x): ",mean(x),"\n") cat("var(x): ",var(x),"\n") # invoking the program (and the output) ####################################### # > source("inverse-cdf.r") # mean(x): 2.073205 # var(x): 3.865034