# An interesting random walk question and simulation 02 If we flip a coin, we will have 50% of chance getting head and 50% of chance getting tail. The question is: how many numbers of time shall we flip to get 3 consecutive heads?

The question should also be asked with confidence. Before that, let's change it to a math question.

We know $P(H) = 0.5$ and $P(T) = 0.5$. Each flip is $i.i.d.$. So it is easy to know that the probability that we get 3 consecutive Head is:

\begin{aligned} & P(\mbox{3 consecutive Head}) \\ & = P(H) \times P(H) \times P(H) \\ & = \frac{1}{2} \times \frac{1}{2} \times \frac{1}{2} \\ & = \frac{1}{8} \end{aligned}

I try to write the distribution of the random variable but I cannot right now. So I did a simple simulation to estimate it. In the same way, I will ask the question as how many times shall I flip to get 3 consecutive heads with 90% confidence? The answer I got is 18.

import numpy as np

def test():
i = 1
while True:
x = np.random.randint(0, 2, 3)
xsum = x.sum()
if xsum == 3:
#print(x)
return i
i += 1

res = []
for j in range(10000):
res.append(test())

res = np.array(res)
np.percentile(res, 90)

18.0


And the average number of flips to get 3 consecutive heads is 8, which is consistent with our feeling because the probability of get this event is $\frac{1}{8}$.

np.mean(res)

8.0066000000000006