##Chapter 7.2 Question 15

Suppose we want to test a coin for fairness. We flip the coin \(n\) times and record the number of times \(X0\) that the coin turns up tails and the number of times \(X1 = n − X0\) that the coin turns up heads. Now we set \[ Z = \frac{1}{n/2} \sum_{i=0}^{n/2} (X_i - n/2)^2\]

Then for a fair coin \(Z\) has approximately a chi-squared distribution with \(2 − 1 = 1\) degree of freedom. Verify this by computer simulation first for a fair coin \((p = 1/2)\) and then for a biased coin \((p = 1/3)\).

# Number of flips
n <- 100

# Number of simulations
num_simulations <- 1000

# Empty vectors to store Z values
Z_values_fair <- numeric(num_simulations)
Z_values_biased <- numeric(num_simulations)

# Run simulations
for (i in 1:num_simulations) {
  # Fair coin (p = 1/2)
  flips_fair <- rbinom(n, 1, 1/2)
  X0_fair <- sum(flips_fair == 0)
  X1_fair <- n - X0_fair
  Z_values_fair[i] <- ((X0_fair - n/2)^2 + (X1_fair - n/2)^2) / (n/2)
  
  # Biased coin (p = 1/3)
  flips_biased <- rbinom(n, 1, 1/3)
  X0_biased <- sum(flips_biased == 0)
  X1_biased <- n - X0_biased
  Z_values_biased[i] <- ((X0_biased - n/2)^2 + (X1_biased - n/2)^2) / (n/2)
}

# Plotting
par(mfrow=c(2,1)) # Set up the graphics layout

# Fair coin histogram and chi-squared density
hist(Z_values_fair, breaks=40, probability=TRUE, main='Fair Coin (p=1/2)', xlab='Z values')
curve(dchisq(x, df=1), add=TRUE, col='blue', lwd=2)

# Biased coin histogram and chi-squared density
hist(Z_values_biased, breaks=40, probability=TRUE, main='Biased Coin (p=1/3)', xlab='Z values')
curve(dchisq(x, df=1), add=TRUE, col='red', lwd=2)

# Reset graphics layout
par(mfrow=c(1,1))

As we can see from the two histograms, the overall distribution of the fair coin matches the density plot of ch-squared density. The biased coin however, does not match the chi-squared distribution.