python math small experiment (6) - how many times the coin toss to appear twice in a row up front?

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

How many times the coin toss, two up front to appear?

The problem lies:
https://zhuanlan.zhihu.com/p/68358814

The core problem is the formula: E ( N k N k 1 ) = E ( N k 1 ) + p + ( 1 p ) ( 1 + E ( N k ) ) And (n_k | k-N- {1}) = e (k-N- {1}) + p + (p-1) (1 + E (n_k))

Currently there have been continuous k k times face up, and only a thin last step. E ( N k ) E (n_k) First, at least equal to E ( N k 1 ) And (N- {k-1})
, Because I have been k k test times, this is the first that is right. Then the next step (I call it the key step) There are two cases: if it is face up, then it's done, because the probability is face-up
p p , so it corresponds to the second term of the right side of the equation; if it is negative up, then fall short, start all over again, which corresponds to the third term of the right side of the equation. Finally get the desired 6

Python simulation as follows:

import numpy as np 

def TossCoin(Consecutive_num):
    temp = 0    #记录连续次数
    count = 0   #记录掷硬币次数
    while temp < Consecutive_num+1:
        count += 1
        result = np.random.binomial(1,0.5)
        if result == 1:
            temp += 1
        else:
            temp = 0
        
        if temp == Consecutive_num:
            break  
    return count

TossCoin_result = [] 
for i in range(100000):
    TossCoin_result.append(TossCoin(2))

print(np.mean(TossCoin_result))

Output: 6.00694

experiment p = 1 / 6 p=1/6 3 times, as output: 259.2

According to the calculation E ( N p ) = 1 ( 1 p ) ( 1 p n 1 E(N_p)=\frac{1}{(1-p)}(\frac{1}{p^n}-1)

Supplementary article: https://www.cnblogs.com/avril/archive/2013/06/28/3161669.html

Guess you like

Origin blog.csdn.net/houhuipeng/article/details/93185772