CoCalc Public FilesFair coin simulation.ipynbOpen with one click!
Author: Julia Burnside
Views : 36
Compute Environment: Ubuntu 20.04 (Default)

Coin Flip Simulator

Suppose you flip a fair coin 10 times. What is the probability that you flip at least 4 consecutive tails? Estimate this probability using a simulation.

0=tails0 = tails

1=heads1= heads

I declared two empty vectors maxStreakListmaxStreakList and StreaksOverFourStreaksOverFour.

The vector maxStreakListmaxStreakList takes the maximum tail streak length in 1010 coin flip by using the coin flip simulation function maxStreakmaxStreak which was discussed in class.

This is iterated 1010 times to get the maximum tail streak length of 1010 trials with 1010 flips each.

Another sequence iterated from i=1 to 10i = 1\ to\ 10 evaluates each maximum tail streak length in maxStreakListmaxStreakList. If the maximum tail streak length at ii is >=4>=4, the vector StreaksOverFourStreaksOverFour at ii is appended to 11, if the maximum tail streak length <4<4, the vector StreaksOverFourStreaksOverFour at ii is appended to 00.

These series of 0=success0=success and 1=failure1=failure values can be interpreted as the results of a series of Bernoulli trails. To find the probability that the maximum tail streak length, take the sum of values in the vector StreaksOverFourStreaksOverFour and divide it by the total number of trails 1010.

The probability in each trial varies, but the cumulative probability of a tail streak length greater than or equal to 44 is between 0.10.1 to 0.30.3.

In [230]:
import numpy as np maxStreakList=[] StreaksOverFour=[] def maxStreak(n): flips = np.random.randint(0,2,size=n) streakList = [] streak = 0 for coin in flips: if coin == 0: if streak != 0: streakList.append(streak) streak = 0 else: streak += 1 return max(streakList) for i in range(10): maxStreakList.append(maxStreak(10)) for i in range(10): if (maxStreakList[i]>=4): StreaksOverFour.append(1) else: StreaksOverFour.append(0) print(StreaksOverFour) print("Probability of getting a streak of four or more tails in ten flips", sum(StreaksOverFour)/10)
[0, 0, 1, 0, 0, 0, 0, 0, 0, 1] Probability of getting a streak of four or more tails in ten flips 0.2