Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. set.seed(325)
  2. # Use the rejection sampling method to generate a random sample of size 10000 from the Gamma(2,2) distribution f(y).
  3. # Draw a target function f(y) to obtain the idea of proposal distribution
  4. f_y <- function(y){
  5. y^(2-1)*exp(-2*y)
  6. }
  7.  
  8. y <- seq(0.01, 4, 0.01)
  9. plot(y, f_y(y), type ="l", xlab = "", ylab = "")
  10. # Use chi-sq (df = 3) distribution as a proposal distribution g(y).
  11. y <- seq(0.01, 4, 0.01)
  12. plot(y, f_y(y), type ="l", xlab = "", ylab = "")
  13. lines(y, dchisq(y, df = 3), col = "red")
  14. # Draw a f(y)/g(y) plot to choose c
  15. y <- seq(0.01, 4, 0.01)
  16. plot(y, f_y(y)/dchisq(y,df = 3), type ="l", xlab = "", ylab = "")
  17. max(f_y(y)/dchisq(y, df = 3))
  18. # choose c = 0.88
  19.  
  20. # Rejection Sampling
  21. n <- 10000
  22. k <- 0 # counter for accepted
  23. j <- 0 # counter for iterations
  24. x <- rep(0, n)
  25.  
  26. while(k < n){
  27. y <- rchisq(1, df = 3) #random variate from g(y) which is Chisq(df = 3)
  28. u <- runif(1)
  29. j <- j + 1
  30. if (u < f_y(y)/(0.88*dchisq(y,df = 3))){
  31. #we accept y
  32. k <- k + 1
  33. x[k] <- y
  34. }
  35. }
  36.  
  37. mean(x)
  38.  
  39. # Compare empirical and theoretical percentiles
  40. p <- seq(0.1, 0.9, 0.01)
  41. Qhat <- quantile(x, p) #quantile of sample
  42. Q <- qnorm(p) #theoretical quantiles
  43. plot(Q, Qhat)
  44.  
  45. round(rbind(Q, Qhat),2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement