Write a computer program to simulate 10,000 Bernoulli trials with probabil- ity .3 for success on each trial. Have the program compute the 95 percent confidence interval for the probability of success based on the proportion of successes. Repeat the experiment 100 times and see how many times the true value of .3 is included within the confidence limits.
# load the binom package for computing the confidence intervals
library(binom)
# Function to perform trials I use the asymptotic - the text-book definition for confidence limits on a single proportion using the Central Limit Theorem. interval DataFrame
trial <- function(n_trials, p_success, n_repeats = 100) {
success_count <- 0
true_value <- p_success
for (i in 1:n_repeats) {
trials <- rbinom(n_trials, 1, p_success)
confidence_interval <- binom.confint(sum(trials), n_trials, conf.level = 0.95,tol = 1e-2)
confidence_interval <- confidence_interval[1,]
if (true_value >= confidence_interval[5] && true_value <= confidence_interval[6]) {
success_count <- success_count + 1
}
}
return(success_count)
}
# Parameters
n_trials <- 10000
p_success <- 0.3
n_repeats <- 100
# Perform experiment
success_count <- trial(n_trials, p_success, n_repeats)
print(paste("The true value", 0.3, "falls in between the computed confidence interval", success_count,"times in 100 tries"))
## [1] "The true value 0.3 falls in between the computed confidence interval 96 times in 100 tries"