- #1
member 428835
Hi PF!
This is related to a forum I just posted here: how many coin tosses are expected to get the sequence HHTH. I believe the answer is 30, explained in the OP. However, I thought I'd try and program it in python. Below is my code:
The results are giving me 18 coin tosses on average. Is my programming wrong or is my calculation in the other post wrong (or maybe both are)?
This is related to a forum I just posted here: how many coin tosses are expected to get the sequence HHTH. I believe the answer is 30, explained in the OP. However, I thought I'd try and program it in python. Below is my code:
Python:
import numpy as np
import statistics
# EXPECTED NUMBER OF TOSSES FOR COIN WITH T WEIGHTED p FOR SEQUENCE HHTH
class coin:
def approx(self, n, p):
lst = []
for _ in range(n):
toss = 0
count = 0
while count < 4:
# THE TOSS
x = np.random.rand()
toss += 1
# LET x < p INDICATE TAILS
# LET x > p INDICATE HEADS
## AFTER HHT, WE SEEK H
if count == 3:
if x > p: # IF HEADS, APPEND lst WITH NUM OF TOSSES
lst.append(toss)
count = 4 # MAKE COUNT 4 TO BREAK WHILE LOOP
else:
count = 0 # SEQUENCE IS HHTT WHICH IS T, SO COUNT RESTARTS
## AFTER HH, WE SEEK T
if count == 2:
if x > p:
count = 2 # IF HEADS, WE HAVE HH
else:
count = 3 # IF TAILS, WE HAVE HHT
# FIRST TWO HH
if count < 2:
if x < p: # IF TAILS, RESTART COUNT
count = 0
else: # IF HEADS, WE HAVE H OR HH
count += 1
return statistics.mean(lst)
if __name__ == "__main__":
n = 10000
p = 0.5
print(coin().approx(n, p))
The results are giving me 18 coin tosses on average. Is my programming wrong or is my calculation in the other post wrong (or maybe both are)?
Last edited by a moderator: