Write a program to toss a coin 10,000 times. Let \(S_{n}\) be the number of heads in the first n tosses. Have your program print out, after every 1000 tosses, \(S_{n} - \frac{n}{2}\). On the basis of this simulation, is it correct to say you can expect heads about half the time when you toss a coin a large number of times?
We could do this all in one call of
rbinom(10000, 1, 0.5), but the question is asking us to keep track of each flip and do something at every 1000 flip, so we’ll do things the slightly less efficient way. Also, we’ll assume that 0 is heads and 1 is tails.
set.seed(123)
coin.flip <- function(n){
num.heads <- 0
for(i in 1:n){
result <- rbinom(1, 1, 0.5)
if(result == 0){
num.heads <- num.heads + 1
}
if(i %% 1000 == 0){
out <- num.heads - (i / 2)
print(paste0("Sn - n/2 at n = ", i, ": ", out))
}
}
print(paste0("Sn/n = ", num.heads/n))
}
coin.flip(10000)
## [1] "Sn - n/2 at n = 1000: 7"
## [1] "Sn - n/2 at n = 2000: 10"
## [1] "Sn - n/2 at n = 3000: 16"
## [1] "Sn - n/2 at n = 4000: 10"
## [1] "Sn - n/2 at n = 5000: 21"
## [1] "Sn - n/2 at n = 6000: 28"
## [1] "Sn - n/2 at n = 7000: 42"
## [1] "Sn - n/2 at n = 8000: 43"
## [1] "Sn - n/2 at n = 9000: 50"
## [1] "Sn - n/2 at n = 10000: 57"
## [1] "Sn/n = 0.5057"
So I added Sn/n for the Law of Averages. We can see, via that, that we’ll expect head roughly half the time. As to Sn - n/2, it seems as though that, if we were to run this often enough, that it would be a positive number. I suppose in an ideal situation that Sn - n/2 would equal to 0 since that would mean exactly half the flips were heads. Maybe for a sufficiently large n it would.