Michiel Kalkman

Notes and observations

06 Jan 2019

R - Coin toss

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
library(ggplot2)
library(gridExtra)
set.seed(1)
coin <- c(0,1)

flipCoin <- function(num_flips=1000) {
  sample(coin, size=num_flips, replace=TRUE)
}

flipEstimate <- function(flips) {
  sum(flips==1) / length(flips)
}

plotFlips <- function(coinflips) {
  qplot(
    1:length(coinflips),
    cumsum(coinflips==1) / (1:length(coinflips)),
    geom='line',
    ylim=coin, 
    xlab = '# of flips',
    ylab = 'Freq coinflip == 1'
  )
}
g1 <- plotFlips(flipCoin(10))
g2 <- plotFlips(flipCoin(100))
g3 <- plotFlips(flipCoin(1000))
g4 <- plotFlips(flipCoin(10000))

grid.arrange(g1, g2, g3, g4, ncol=2)

Plot

Coin toss plot

Next time, we'll talk about "What Tiger King can teach us about x86 Assembly"