Chapter 8.1 Laws of large numbers Question 3

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 − n/2. On the basis of this simulation, is it correct to say that you can

expect heads about half of the time when you toss a coin a large number of

times?

heads = 0
for(i in 1:10001){
  flip <- sample(0:1,1)
  
  if(flip == 1){
    heads = heads + 1
  }
  if (i %% 1000 == 0){
    dev = heads - i/2
    print(i)
    print(paste0('Number of heads: ',heads,collapse= ''))
    print(paste0('Difference between number of heads and tails: ',dev,collapse = ''))
    print('#############')
    }
  
  
}
## [1] 1000
## [1] "Number of heads: 506"
## [1] "Difference between number of heads and tails: 6"
## [1] "#############"
## [1] 2000
## [1] "Number of heads: 1016"
## [1] "Difference between number of heads and tails: 16"
## [1] "#############"
## [1] 3000
## [1] "Number of heads: 1530"
## [1] "Difference between number of heads and tails: 30"
## [1] "#############"
## [1] 4000
## [1] "Number of heads: 2023"
## [1] "Difference between number of heads and tails: 23"
## [1] "#############"
## [1] 5000
## [1] "Number of heads: 2515"
## [1] "Difference between number of heads and tails: 15"
## [1] "#############"
## [1] 6000
## [1] "Number of heads: 3033"
## [1] "Difference between number of heads and tails: 33"
## [1] "#############"
## [1] 7000
## [1] "Number of heads: 3529"
## [1] "Difference between number of heads and tails: 29"
## [1] "#############"
## [1] 8000
## [1] "Number of heads: 4054"
## [1] "Difference between number of heads and tails: 54"
## [1] "#############"
## [1] 9000
## [1] "Number of heads: 4565"
## [1] "Difference between number of heads and tails: 65"
## [1] "#############"
## [1] 10000
## [1] "Number of heads: 5053"
## [1] "Difference between number of heads and tails: 53"
## [1] "#############"

Yes, you can pretty much expect heads roughly half the time.