Modify the program CoinTosses to toss a coin n times and record whether or not the proportion of heads is within .1 of .5 (i.e., between .4 and .6). Have your program repeat this experiment 100 times. About how large must n be so that approximately 95 out of 100 times the proportion of heads is between .4 and .6?
Answer: When the number of flips (n) surpasses around 50 flips, then the proportion of heads is between .4 and .6 approximately 95 out of 100 times.
# Function that simulates a coin toss.
coinTosses <- function(n) {
# Define a vector to represent the coin that will be tossed in the experiment.
coin <- c('H', 'T')
# Simulate tossing the coin n times.
coin_tosses <- seq(from = 1, to = n, by = 1)
# Define a matrix to record the probability of a heads result.
probability_of_heads <- matrix(NA, nrow = length(coin_tosses), ncol = 1)
# Define a matrix to record the probability of a tails result.
probability_of_tails <- matrix(NA, nrow = length(coin_tosses), ncol = 1)
# Perform the coin tosses.
for (toss in 1:length(coin_tosses)) {
coin_toss <- sample(coin, coin_tosses[toss], replace = TRUE)
probability_of_heads[toss, 1] <- length(which(coin_toss == 'H')) / coin_tosses[toss]
probability_of_tails[toss, 1] <- length(which(coin_toss == 'T')) / coin_tosses[toss]
}
# Plot the results.
plot(coin_tosses, probability_of_heads, xlab = 'Number of Tosses',
ylab = 'Probability of Heads', type = 'l', font = 2, font.lab = 2)
abline(h = 0.4, col = 'red', lwd = 1.5)
abline(h = 0.5, col = 'blue', lwd = 1.5)
abline(h = 0.6, col = 'red', lwd = 1.5)
}
one_hundred_flips <- coinTosses(100)
As we can see from the above chart, when the number of flips (n) surpasses around 50 flips, then the proportion of heads is between .4 and .6 approximately 95 out of 100 times.
To get a clearer picture of this trend, we can increase the number of flips to 1000 to see what happens.
one_thousand_flips <- coinTosses(1000)
From the above graph, we can observe that as the number of flips increases, The probability of getting a heads results converges and stabilizes at the expected probability of 0.5.