** Chapter 9 Section 2. Question 4, Page 354 **
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?
gen_random <- function()
{
count = 1000
max = 10
s = sample.int(max, count, replace = TRUE)
avg = mean(s)
expected = 4.5
# Does the average lie within 3 S.D. of the expected value?
stddev = sd(s)
hi = expected + 3*stddev
lo = expected - 3*stddev
within_3_sd = !(avg < lo || avg > hi)
# cat("lo ", lo, "hi ", hi, "actual ", avg)
return(within_3_sd)
}
result = vector()
for (i in 1:1000) {
result[i] = gen_random()
}
print(sum(result == TRUE)/length(result))
## [1] 1