tagdodger33
tagdodger33

Reputation: 1

Coin flip simulation using R

I am attempting to simulate a biased coin that is repeatedly flipped until either 2 heads appear in a row or 2 tails appear in a row (then the flipping stops). I want to find the probability P(two heads in a row appears before two tails in a row).

Looking for assistance on incorporating the "tails" flips into the loop. Thanks

 flip <- function(bias_p) {                           
    n_flips <- 0                                           
    head <- 0
    tail <- 0
    while (head != 2 & tail != 2) {                                 
       n_flips <- n_flips + 1
       head_flips <- sample(c(1,0), 1, prob = c(bias_p, 1 - bias_p))
       if(head_flips == 1) ((head <- head + 1) & (tail <- 0))
       else ((tail <- tail + 1) & (head <- 0))
       } 
    return(c(head, tail))
    }  
 y <- replicate(5000, flip(0.8))
 length(which(y[1,] ==2)) / (ncol(y)) 

Upvotes: 0

Views: 1997

Answers (1)

Marius
Marius

Reputation: 60180

To get your current approach working, I had to make a few changes:

  • Only generate one flip per iteration. Currently you generate two totally independent random results per iteration - hflip and tflip may not be consistent with each other
  • If the flip is a head, add to nheads and reset ntails to 0
  • If the flip is tails, add to ntails and reset nheads

(using {} for if/else can make it clearer what the logic flow is, your current else is only connected to the line above it, not the first if test)

coin_flip <- function(head_p) {                           
    nflips <- 0                                           
    nheads <- 0
    ntails <- 0
    while (nheads != 2 & ntails != 2) {                                 
        nflips <- nflips + 1
        # Only generate 1 flip
        flip <- sample(c(1,0),1,prob=c(head_p,1-head_p))
        # If heads:
        if (flip == 1) {
            nheads <- nheads + 1
            # Reset tails counter
            ntails <- 0
        # There are only two possibilities for what 'flip'
        # can be (1 or 0), so we can just use else rather than 
        # testing for 0 specifically
        } else {
           ntails <- ntails + 1
           nheads <- 0
        }
    } 
    return(nflips)
}

If you need the function to output whether 2 heads or 2 tails came first, you could replace return(nflips) with return(nheads == 2): the function will then output 1 if 2 heads came first, 0 if 2 tails.

Upvotes: 2

Related Questions