This week, we’ll empirically verify Central Limit Theorem. We’ll write code to run a small simulation on some distributions and verify that the results match what we expect from Central Limit Theorem.
f(x) = x, 0 ≤ x ≤ 1 f(x) = 2 − x, 1 < x ≤ 2
f <- function(x){
if (0 <= x && x <=2){
if (x <= 1) {
return(x)
} else {
return(2-x)
}
}
}
f(x) = 1 − x, 0 ≤ x ≤ 1 f(x) = x − 1, 1 < x ≤ 2
f1 <- function(y){
if (0 <= y && y <=2){
if (y <= 1) {
return(1-y)
} else {
return(y-1)
}
}
}
samp_rv <- function(rv){
return(sapply(runif(1000),rv))
}
f(0.8)
## [1] 0.8
vec <- samp_rv(f)
f1(1.5)
## [1] 0.5
vec1 <- samp_rv(f1)
hist(vec)
hist(vec1)
library(ggplot2)
samp_PDF <- function(n, PDF) {
mean_cal <- NULL
for (i in 1:1000) {
x <- runif(n, 0, 2)
y <- sapply(x, PDF)
mean_cal <- c(mean_cal, mean(y))
}
pdfstr <- deparse(substitute(PDF))
title <- paste0("n = ", n, " \n PDF = ", pdfstr)
ggplot() + aes(mean_cal) + geom_histogram(binwidth=.01) +
ggtitle(title) + theme(plot.title = element_text(hjust = 0.5),
axis.title.x=element_blank(),
axis.title.y=element_blank())
}
samp_PDF(20,f)
samp_PDF(10,f)
samp_PDF(30,f1)
samp_PDF(10,f1)