Description of the problem
Use the Rejection Method to generate n = 10000 values for a random variable X that has the pdf of f(x) = (x^2)/9, 0<x<3.Create a density histogram for your generated values.Superimpose the probability density function of the target distribution to the histogram.Use the generated values to estimate the mean, standard deviation, and the probability that X < 2.
Simulated Data
# We generate X number for a random variable X that has the pdf of f(x) = (x^2)/9, 0<x<3
N = 10000
p =0
q = 3
z = 1
f = function (x) {(x^2)/9}
n1 = 0
n2 = 0
r = NULL
for (k in 1:N)
{
while (TRUE)
{
X = runif (1,p,q)
Y = runif (1,0,z)
n1 = n1 + 1
if (Y<=f(X))
{
n2=n2 +1
break
}
}
r[k]=X
}
head (r)
## [1] 2.982874 2.545023 1.533207 2.782387 2.616706 2.762393
Summary graphs/tables
#We calculate/display the acceptance rate
cat("Acceptance rate: ", n2/n1, "\n\n") #Acceptance rate
## Acceptance rate: 0.3352779
#We calculate/display the rejection rate
cat("The rejection rate is: ", (1- (n2/n1)), "\n\n")
## The rejection rate is: 0.6647221
#We calculate/display the probability that X <2
mean (r<2)
## [1] 0.2938
## We create the density Histogram
hist (r,prob = TRUE, xlab ="x", main = "Histogram of x", col = "cornsilk3")
curve (f, add = TRUE, col = "blue4")

#We calculate/display the mean
mean (r)
## [1] 2.253886
#We calculate/display the standard deviation of generated values
sd(r)
## [1] 0.581087
Discussion
10000 values for a random variable X have been generated using the rejection method. The acceptance rate and rejection rate are 0.3360328 and 0.6639672. The mean of the random 10000 generated values 2.248455, sensibly equals to thetheoretical mean which is 2.25; and the standard deviation of the random 10000 generated values is 0.5837414 , sensibly equals to our theoritical value which is 0.58.