python 中连续两次正面朝上的预期抛球的蒙特卡洛模拟

Monte-Carlo Simulation of expected tosses for two consecutive heads in python

连续两次正面朝上的预期投掷次数为 6。但是,在执行以下多次运行该实验的模拟时,我得到了与预期不同的图。你能帮我找出逻辑上的错误吗? 谢谢

模拟投掷并检查何时遇到两个连续正面重复 10000 次的代码:

import random
def toss():
    return random.randint(0, 1)

expected_tosses=list()
for test in range(10000):
    a=toss()
    for i in range(2,100):
        b=toss()
        if a and b:
            expected_tosses.append(i)
            break
        a=b

import matplotlib.pyplot as plt
plt.hist(expected_tosses, range(1,10)) 
plt.show()

答:代码中有一些细微的错误

您正在通过限制上循环来更改统计信息。请改用无限循环。

代码如下所示,应该更准确:

import random
def toss():
    return random.randint(0, 1)

expected_tosses=list()
for test in range(10000):
    a=toss()

    i = 2
    while True:
        b=toss()
        if a and b:
            expected_tosses.append(i)
            break
        a=b
        i+=1

import matplotlib.pyplot as plt
print(sum(expected_tosses) / float(len(expected_tosses)))
plt.hist(expected_tosses, range(1,10))
plt.show()

B:输出的解释

结果还可以!

我引入了计算所需的抛掷次数(在上面的代码中)并将其打印出来。你会看到,手段看起来像你预期的那样!

一些示例输出(我们不使用种子,因此结果会有所不同 运行):

5.9941

需要说明的是:均值并不能告诉您关于直方图形状的太多信息。也许这是你困惑的根源(在你的情节中有接近最小值 6)。

这里是模拟N个连续正面的函数:

import numpy as np

def toss1():
    return np.random.randint(0, 2)

def headN(N):
    # expected number of tosses 
    # to get N consecutive heads
    i = 0
    temp = [0]*N
    while np.sum(temp)<N:
        temp[i%N] = toss1()
        i += 1
    return i