返回题库

有偏差的硬币序列

Biased Coin Sequence

专题
Probability / 概率
难度
L5

题目详情

你将获得一枚硬币,正面朝上的概率为 23\frac23,反面朝上的概率为 13\frac13。如果你抛这枚硬币,直到出现反面,紧接着出现正面,你预计抛硬币多少次?

You are given a coin with probability 23\frac23 to land on heads and 13\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?

解析

我们将看到紧随其后的正面的反面所需的翻转次数称为 THTH。如果我们的第一次翻转是正面,则已添加一次翻转但尚未取得任何进展,因此我们现在预计翻转总数为 E[TH]+1E[TH] + 1。如果我们第一次翻转是反面,我们就完成下一次正面。直到正面的预期翻转次数与 p=23p = \frac23 呈几何关系,因此我们预计会进行额外的 32\frac32 翻转,直到我们获得最终正面。考虑到这些结果的概率,我们可以说: E(TH)=23(E(TH)+1)+13(32+1)E(TH) = \frac23(E(TH) + 1) + \frac13(\frac32+ 1) 我们现在可以求解 E(TH)E(TH)E(TH)=23E(TH)+96E(TH) = \frac23E(TH) + \frac96 13E(TH)=96\frac13E(TH) = \frac96 E(TH)=92\Rightarrow E(TH) = \boxed{\frac92}

import random

flip_coin = lambda: 'T' if random.randint(1, 3) == 1 else 'H'

sequence_lengths = []
num_iters = 100_000
for i in range(num_iters):

    sequence = [flip_coin()]
    while(True):

        sequence.append(flip_coin())
        if sequence[-2]=='T' and sequence[-1]=='H':
            sequence_lengths.append(len(sequence))
            break

print(sum(sequence_lengths) / num_iters)

Original Explanation

Let's call the number of flips needed to see a tails immediately followed heads THTH. If our first flip is heads, one flip has been added but no progress has been made so we will now expect E[TH]+1E[TH] + 1 total flips. If our first flip is tails, we finish on the next heads. The expected number of flips until heads is geometric with p=23p = \frac23 so we expect an additonal 32\frac32 flips until we get the finishing heads. Given the probabilities these outcomes we can say:

E(TH)=23(E(TH)+1)+13(32+1)E(TH) = \frac23(E(TH) + 1) + \frac13(\frac32+ 1)

We can now solve for E(TH)E(TH). E(TH)=23E(TH)+96E(TH) = \frac23E(TH) + \frac96 13E(TH)=96\frac13E(TH) = \frac96 E(TH)=92\Rightarrow E(TH) = \boxed{\frac92}

import random

flip_coin = lambda: 'T' if random.randint(1, 3) == 1 else 'H'

sequence_lengths = []
num_iters = 100_000
for i in range(num_iters):

    sequence = [flip_coin()]
    while(True):

        sequence.append(flip_coin())
        if sequence[-2]=='T' and sequence[-1]=='H':
            sequence_lengths.append(len(sequence))
            break

print(sum(sequence_lengths) / num_iters)