I'm trying to use the rejection method (accept/reject) to simulate samples of various dimensions from the distribution with density function of probability enter image description here

And graphically check whether the sample comes from a population with Beta distribution (1/2, 3).

Here's what I've done:

 # 1. Define sample size
nvals <- 5000

# 2. Rejection sampling method 
reject.beta <- function(nvals)
  x.aceite <- NULL
  u.aceite <- NULL
  nx <- 0
  x.rejected <- NULL
  u.rejected <- NULL
  nrejected <- 0
  while(nx < nvals) {
    Y <- runif(1,0,1) #I can't use uniform distribution
    U <- runif(1,0,1.875) #1.875 = 30/16
    if(U <= (15/16)*(Y^(-1/2))*(1-Y)^2) {
      nx <- nx + 1
      x.aceite[nx] <- Y
      u.aceite[nx] <- U
    } else {
      nrejected <- nrejected + 1
      x.rejected[nrejected] <- Y
      u.rejected[nrejected] <- U
  plot(x.aceite,u.aceite,pch=20,col="green",xlab="x",ylab="f(x)",main="Beta(1/2,3) - pontos escolhidos pelo Método de Rejeição")

XX <- reject.beta(nvals)
hist(XX,breaks=20,prob=TRUE,xlim=c(0,1),ylim=c(0,3),main="Distribuição(2,3) obtida pelo Método de Rejeição")
x.val <- seq(0,4,0.001)
lines(x.val, dbeta(x.val, 1/2, 3) ,col="blue")

However, I can't use uniform distribution to solve this, I need to use the probability density function:

enter image description here

The suggestion I've got was to assign Y variable with a value from this p.d.f using the inversion method. (I thought extracting a value between the min and max would suffice)

Can someone please tell me how can I do that?


I assume you have a cumulative density function $F$ and you want to sample a random variable $Y$ whose distribution functions is $F$ ($Y \sim F$).

To do this note that $F(Y)$ is uniformly distributed. Let $U \sim Uni[0,1]$ then you know that $F^{-1}(U) \sim Y$. This means that all you have to do to sample from $Y$ is to generate a sample $u$ from $U$ and compute $F^{-1}(u)$.

To find $F^{-1}(u)$ in R you might find the function uniroot very useful, since all you really want is a solution for the equation $F(x) = u$.

  • $\begingroup$ Too bad I'm not that good at statistics to understand what you're saying. +1 though $\endgroup$
    – SaintLike
    Dec 18 '16 at 16:17
  • $\begingroup$ Can you provide an R example? I'm having trouble in understanding what you're saying $\endgroup$
    – SaintLike
    Dec 18 '16 at 22:13
  • 1
    $\begingroup$ Sorry, I cant provide a R example, but I will gladly answer any question you have. If you are having trouble understanding what I wrote and can't formulate a question I encourage you to check the wikipedia article about the Rejection Sampling algorithm. $\endgroup$
    – Mur1lo
    Dec 18 '16 at 22:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.