Question

Exercise 2.2.22 Write a program to carry out the following experiment. A coin is tossed 100 times and the number of heads that turn up is recorded. This experiment is then repeated 1000 times. Have your program plot a bar graph for the proportion of the 1000 experiments in which the number of heads is \(n\), for each \(n\) in the interval [35,65]. Does the bar graph look as though it can be fit with a normal curve?

Simulation

There are 1000 experiments with 100 coin tosses per experiment.

reps <- 1000 # number of experiment
tosses_per_experiment <- 100 #number of coin tosses per experiment
num_heads <- numeric(reps)

Simulate the coin tossing

First, we set a random number seed to ensure reproducibility. Create a loop to simulate the experiment 1000 times.

set.seed(123) 
for (i in 1:reps) {
  experiment <- sample(c("H", "T"), tosses_per_experiment, replace = TRUE) # A loop that randomly tosses a coin 100 times within each experiment 
  num_heads[i] <- sum(experiment == "H") # Counts the number of heads in each experiment and records it in a new vector, num_heads. There will be 1000 values for 1000 experiments
}

Calculate the proportion of the 1000 experiments in which the number of heads is \(n\), for each \(n\) in the interval [35,65]

proportions <- numeric(31) # There will be 31 values within the interval [35,65]
for (n in 35:65) {
  proportions[n - 34] <- sum(num_heads == n) / reps #For each experiment from experiments 35 to 65, we calculate the (total number of heads in each experiment)/number of experiments
}

Plot

The bar graph does look as if it will fit with a normal curve.

barplot(proportions, names.arg = 35:65, xlab = "Number of Heads", ylab = "Proportion",
        main = "Proportion of Experiments vs. Number of Heads")