Write a program to find the average of 1000 random digits 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. Have the program test to see if the average lies within three standard deviations of the expected value of 4.5. Modify the program so that it repeats this simulation 1000 times and keeps track of the number of times the test is passed. Does your outcome agree with the Central Limit Theorem?
# Function to perform simulation and test
average_test <- function() {
digits <- sample(0:9, 1000, replace = TRUE)
average <- mean(digits)
expected_value <- 4.5
std_dev <- sd(digits)
lower_bound <- expected_value - 3 * std_dev
upper_bound <- expected_value + 3 * std_dev
test_result <- average >= lower_bound && average <= upper_bound
return (test_result)
}
# Function to repeat simulation and test 1000 times
run_simulation <- function() {
passed_tests <- 0
for (i in 1:1000) {
if (average_test()) {
passed_tests <- passed_tests + 1
}
}
return(passed_tests)
}
# Main function
main <- function() {
passed_tests <- run_simulation()
cat("Number of times the test is passed:", passed_tests, "\n")
}
# Run the main function
main()
## Number of times the test is passed: 1000
Since all tests passed, meaning all averages lie within three standards deviation from the expected value (\(4.5\)), then the outcome agree with the Central Limit Theorem.