Search code examples
rfor-loopsimulationmontecarlopurrr

Monte Carlo simulation of 8 coin flips


I am trying to solve the following problem with Monte Carlo simulation

Let's say that head = 1 and tails = 0 and I flip 8 coins. What is the probability that all are tails?

What I have so far is the following

sum(sample(c(0,1),8,replace=T))

This counts the number of heads in a sample of 8. I would like to run this 1e6 times and count the number of times 0 shows up, divided by 1e6. What are some various ways to accomplish this in R?


Solution

  • Here's most of a purrr solution

    set.seed(101)
    n <- 1e5
    xx <- rerun(n,sample(0:1,8,replace=TRUE)) %>%  map_dbl(sum) 
    mean(xx==0)
    

    You can do the last step functionally via

    ... %>% tibble %>% summarise(prob=mean(.==0))
    

    (. is the single unnamed variable in the tibble) but that feels kind of cheesy