DATA604_Discussion_Week_6

Dilip Ganesan

Random Variate Generation.

Problem 8.5

Given the following CDF for a continous variable with range from -3 to 4, develop a generator for the variable, generate 10000 values, and plot a histogram

#        0,              x <= 3
#        1/2 + x/6,     -3 < x <=0   
#F(x) =  1/2 + x^2/32    0 < x <=4
#        1,              x > 4



# Step 1: Given the CDF we will perform Inverse Tranformation and we can equate the equation F(x) = R.

# Step 2: For the first and fourth the value of R =0 and R = 1.

# Step 3: Let us try to resolve the second and third between ranges -3 < x <= 4

# R = 1/2 + X/6 
# R = (3 + X)/6
# X + 3 = 6R
# X = 6R - 3 -> Equation 1

# R = 1/2 + X^2/32
# 32R = 16 + X^2
# X = 4(sqrt(2R-1)) -> Equation 2

# Step 4, now changing the ranges from x to R since the equation is now interms of R

# Apply -3 and 0 in Equation 1, Range for R becomes 0 < R <= 1/2
# Apply 0 and 4 in Equation 2, Range for R becomes 1/2 < R <= 1

# Step 5, Running the random generator for 1000 samples in the range [0,1]

rand = runif(1000, 0 ,1)
out <- c()
for (i in rand) {
  if(i > 0 && i <= 1/2){
  X = 6 * i - 3
  }else{
  X = 4 * sqrt(2 * i - 1)
  }
  out <- c(out, X)
}

hist(out)