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.
I declared two empty vectors maxStreakList and StreaksOverFour.
The vector maxStreakList takes the maximum tail streak length in 10 coin flip by using the coin flip simulation function maxStreak which was discussed in class.
This is iterated 10 times to get the maximum tail streak length of 10 trials with 10 flips each.
Another sequence iterated from i=1to10 evaluates each maximum tail streak length in maxStreakList. If the maximum tail streak length at i is >=4, the vector StreaksOverFour at i is appended to 1, if the maximum tail streak length <4, the vector StreaksOverFour at i is appended to 0.
These series of 0=success and 1=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 StreaksOverFour and divide it by the total number of trails 10.
The probability in each trial varies, but the cumulative probability of a tail streak length greater than or equal to 4 is between 0.1 to 0.3.
importnumpyasnpmaxStreakList=StreaksOverFour=defmaxStreak(n):flips=np.random.randint(0,2,size=n)streakList=streak=0forcoininflips:ifcoin==0:ifstreak!=0:streakList.append(streak)streak=0else:streak+=1returnmax(streakList)foriinrange(10):maxStreakList.append(maxStreak(10))foriinrange(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