python - Python 中的 Q : Expected number of coin tosses to get N heads in a row,。我的代码给出的答案与已发布的正确答案不匹配,但不确定原因

标签 python probability montecarlo

我正在尝试编写 Python 代码来查看平均需要掷多少次硬币才能连续出现 N 个正面朝上的序列。

让我感到困惑的是,我的代码生成的答案与在线给出的答案不匹配,例如这里(和许多其他地方)https://math.stackexchange.com/questions/364038/expected-number-of-coin-tosses-to-get-five-consecutive-heads

据此,我需要连续获得各种正面朝上的预期 throw 次数为:E(1) = 2, E(2) = 6, E(3) = 14, E( 4) = 30, E(5) = 62。但我没有得到这些答案!例如,我得到 E(3) = 8,而不是 14。运行下面的代码给出该答案,但您可以更改 n 以测试连续出现正面的其他目标数量。

出了什么问题?大概我的代码逻辑有问题,但我承认我无法弄清楚它是什么。

您可以在此处查看、运行和制作我的代码的修改副本:https://trinket.io/python/17154b2cbd

下面是代码本身,位于可运行的 trinket.io 页面之外。如果您能帮助找出问题所在,我们将不胜感激!

非常感谢,

拉杰 附言我能找到的最接近的相关问题是这个:Monte-Carlo Simulation of expected tosses for two consecutive heads in python 然而,据我所知,该问题中的代码实际上并没有测试两个 连续 头,而是测试一个以头开始的序列,然后在稍后的某个时间,可能是非连续,时间得到另一个头。

# Click here to run and/or modify this code:
# https://trinket.io/python/17154b2cbd

import random
# n is  the target number of heads in a row
# Change the value of n, for different target heads-sequences
n = 3  
possible_tosses = [ 'h', 't' ]
num_trials = 1000
target_seq = ['h' for i in range(0,n)]
toss_sequence = []
seq_lengths_rec = []

for trial_num in range(0,num_trials):

    if (trial_num % 100) == 0:
        print 'Trial num', trial_num, 'out of', num_trials
        # (The free version of trinket.io uses Python2)

    target_reached = 0
    toss_num = 0

    while target_reached == 0:

        toss_num += 1
        random.shuffle(possible_tosses)
        this_toss = possible_tosses[0]
        #print([toss_num, this_toss])
        toss_sequence.append(this_toss)
        last_n_tosses = toss_sequence[-n:]
        #print(last_n_tosses)
    if last_n_tosses == target_seq:
        #print('Reached target at toss', toss_num)
        target_reached = 1
        seq_lengths_rec.append(toss_num)

print 'Average', sum(seq_lengths_rec) / len(seq_lengths_rec)

最佳答案

您不需要为每个实验重新初始化 toss_sequence,因此您使用预先存在的正面序列开始每个实验,有二分之一的机会在第一次击中目标序列尝试每个新实验。

在外循环中初始化 toss_sequence 将解决您的问题:

import random
# n is  the target number of heads in a row
# Change the value of n, for different target heads-sequences
n = 4
possible_tosses = [ 'h', 't' ]
num_trials = 1000
target_seq = ['h' for i in range(0,n)]
seq_lengths_rec = []

for trial_num in range(0,num_trials):

    if (trial_num % 100) == 0:
        print('Trial num {} out of {}'.format(trial_num, num_trials))
        # (The free version of trinket.io uses Python2)

    target_reached = 0
    toss_num = 0
    toss_sequence = []

    while target_reached == 0:

        toss_num += 1
        random.shuffle(possible_tosses)
        this_toss = possible_tosses[0]
        #print([toss_num, this_toss])
        toss_sequence.append(this_toss)
        last_n_tosses = toss_sequence[-n:]
        #print(last_n_tosses)
        if last_n_tosses == target_seq:
            #print('Reached target at toss', toss_num)
            target_reached = 1
            seq_lengths_rec.append(toss_num)

print(sum(seq_lengths_rec) / len(seq_lengths_rec))

您可以稍微简化您的代码,使其不易出错:

import random
# n is  the target number of heads in a row
# Change the value of n, for different target heads-sequences
n = 3
possible_tosses = [ 'h', 't' ]
num_trials = 1000
seq_lengths_rec = []

for trial_num in range(0, num_trials):

    if (trial_num % 100) == 0:
        print('Trial num {} out of {}'.format(trial_num, num_trials))
        # (The free version of trinket.io uses Python2)

    heads_counter = 0
    toss_counter = 0

    while heads_counter < n:
        toss_counter += 1

        this_toss = random.choice(possible_tosses)

        if this_toss == 'h':
            heads_counter += 1
        else:
            heads_counter = 0
    seq_lengths_rec.append(toss_counter)


print(sum(seq_lengths_rec) / len(seq_lengths_rec))

关于python - Python 中的 Q : Expected number of coin tosses to get N heads in a row,。我的代码给出的答案与已发布的正确答案不匹配,但不确定原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55377700/

相关文章:

algorithm - 将相同项目放入匿名存储桶后的可能分布及其概率

r - 在 R 中生成概率分布函数 (PDF) 的问题

python - 如何在蒙特卡罗积分中实现多处理

r - 在 R 中进行简单蒙特卡洛积分时出现错误结果

python - 如何在 Python 中获得漂亮的 API Plot?

python - Scrapy尝试抓取网页的信息内部链接

python长数数据丢失

c - rand() 在 OSX 上是否返回零?

java - 如何从 Java 运行 python 2.7 代码?