Write a program to toss a coin 10,000 times. Let Sn be the number of heads in the first n tosses. Have your program print out, after every 1000 tosses, Sn − 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?
n<-1000
heads<-0 #used to count the number of heads in loop
vec<-0
for(i in 1:10){ #iterates 10 times to get 10k
num<-sample(0:1,1000, replace = T)
#print(num)
num<-data.frame(num)
heads <- heads + sum(num==1)
print(heads)
vec <- c(vec,heads/(1000*i))
n <-c(n,1000*i)
}
## [1] 511
## [1] 1018
## [1] 1522
## [1] 2015
## [1] 2513
## [1] 3008
## [1] 3506
## [1] 4017
## [1] 4493
## [1] 5007
data <- data.frame(n,vec)
data
## n vec
## 1 1000 0.0000000
## 2 1000 0.5110000
## 3 2000 0.5090000
## 4 3000 0.5073333
## 5 4000 0.5037500
## 6 5000 0.5026000
## 7 6000 0.5013333
## 8 7000 0.5008571
## 9 8000 0.5021250
## 10 9000 0.4992222
## 11 10000 0.5007000
typeof(data)
## [1] "list"
Since the value of heads is around 5,400, it's around 0.54 or 54%, therefore we can say it is safe to expect around half the tosses as heads.
Sources: https://www.rexamples.com/14/Sample()