7 Explain how you can generate a random variable whose cumulative distribution function is F(x) = (0, if x < 0, x^2, if 0 ≤ x ≤ 1, 1, if x > 1.
#sample size
sample_size <- 1000
#random samples
set.seed(123)
#random values between 0 and 1
samples <- runif(sample_size)
#inverse transformation for values from cumulative distribution function
inverse_cdf <- function(x) {
ifelse(x <= 0, 0, ifelse(x <= 1, sqrt(x), 1))
}
#values for distribution
distribution_values <- sapply(samples, inverse_cdf)
#bar graph
hist(distribution_values, breaks = 20, col = "lightblue", main = "Empirical Density", xlab = "Value", ylab = "Density")
#define the PDF - probability density function
pdf <- function(x) {
ifelse(x >= 0 & x <= 1, 2 * x, 0)
}
#overlay the PDF on the plot
curve(pdf(x), from = 0, to = 1, col = "purple", lwd = 2, add = TRUE)