有偏差的硬币序列
Biased Coin Sequence
题目详情
你将获得一枚硬币,正面朝上的概率为 ,反面朝上的概率为 。如果你抛这枚硬币,直到出现反面,紧接着出现正面,你预计抛硬币多少次?
You are given a coin with probability to land on heads and 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?
解析
我们将看到紧随其后的正面的反面所需的翻转次数称为 。如果我们的第一次翻转是正面,则已添加一次翻转但尚未取得任何进展,因此我们现在预计翻转总数为 。如果我们第一次翻转是反面,我们就完成下一次正面。直到正面的预期翻转次数与 呈几何关系,因此我们预计会进行额外的 翻转,直到我们获得最终正面。考虑到这些结果的概率,我们可以说: 我们现在可以求解 。
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 . If our first flip is heads, one flip has been added but no progress has been made so we will now expect total flips. If our first flip is tails, we finish on the next heads. The expected number of flips until heads is geometric with so we expect an additonal flips until we get the finishing heads. Given the probabilities these outcomes we can say:
We can now solve for .
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)