Probability – Expected Number of Flips for Biased Coin Sequence

conditional probabilityexpected valueprobabilitystochastic-processes

You are given a coin with probability $\frac23$ to land on heads and
$\frac13$ to land on tails. If you flip this coin until you get a
tails immediately followed by heads, how many times do you expect to
flip the coin?

We can say the E(TH) sequence is $\frac23$(Expectation | first flip is heads) + $\frac13$(Expectation | first flip is tails). If first flip is heads, no progress was made so (Expectation | first flip is heads) = E(TH + 1). If first flip was tails, we flip until we get a heads. This is geometric with $p=\frac23$ so we can expect an additional $\frac32$ more flips. Thus we get:

$E(TH) = \frac23(E(TH) + 1) + \frac13(\frac32 + 1) \rightarrow E(TH) = 4.5$

However, when I script this, I am getting 6 expected flips. Is there a flaw in the math or the script?

enter image description here>

Best Answer

Your simulation isn't quite correct. When getting a T, you throw a new one and check if that is H. But if that second throw is a T, this isn't checked for a following H on the next round.

Easiest fix would be to check after each throw, if we've achieved TH as the last two throws.

def simu():
    ret = 0
    a = [flip_coin()]
    while True:
        a.append(flip_coin())
        if a[-2]=='T' and a[-1]=='H': break
    return len(a)

print (float(sum(simu() for _ in range(num_iters)))/num_iters)