In Banks DES textbook, problem 8.

Ex. 8.8:

Develop a generator for a random variable whose pdf is:

\(f(x)=\begin{cases} \frac{1}{3}, & 0 \leq x\leq 2 \\ \frac{1}{24}, & 2 <x\leq 10\\ 0, & otherwise \end{cases}\)

First, I create a function to generate a single value of \(f(x)\):

piecewise_func <- function(i){
  rand_a <- runif(1, 0, 10)

  if(rand_a <= 2){
    func_out <- 1/3
  }else if(rand_a > 2)
    func_out <- 1/24
  else{
    func_out <- 0
  }
  
  pt <- data.frame( i = c(i), x = rand_a, `fx` = func_out, stringsAsFactors = F)
  return(pt)
}
piecewise_func(1)
##   i        x         fx
## 1 1 8.626232 0.04166667

Next, the function my_sim generates n values from the piecewise_func, defined above. The value produced by this function will then be plotted in a histogram. Below, I show 10 sample values generated by my_sim.

my_sim <- function(n){
  c <- piecewise_func(1)
  
  if(n == 1){
    return(c)
  }else{
    for(i in 2:n){
      c <- rbind(c, piecewise_func(i))
    }
  }
  return(c)
}

z <- my_sim(1000)
head(z)
##   i        x         fx
## 1 1 2.565955 0.04166667
## 2 2 4.759255 0.04166667
## 3 3 6.049193 0.04166667
## 4 4 5.450832 0.04166667
## 5 5 8.390882 0.04166667
## 6 6 4.251693 0.04166667

As shown below, the histogram shows that the value of \(\frac{1}{24}\) is 5 times more common than the value of \(\frac{1}{3}\).

hist(z$fx)

I thought this exercise was challenging in that it required me to consider a piecewise function composed of constants as being a distribution.