返回题库

六的倍数

Multiple of Six

专题
Probability / 概率
难度
L3

题目详情

你掷出一个公平的六面骰子,然后将结果相加,直到达到 6 的倍数。你预计掷骰子的次数是多少。

You roll a fair six-sided and sum the outcomes until you reach a multiple of 6. What is the expected number of times you expect to roll the die.

解析

假设 ssnn 掷骰后我们的骰子的总和。 66 的可能值与 smod6s \mod 6 的值相同。 乍一看,这可能表明 nn 掷骰后 ss 可能存在 66 的情况,但请注意,无论 ss 是什么,都存在 11 掷骰,使总和达到 6 的倍数。(即,如果 2smod62 \equiv s\mod6,则必须掷出 44 才能达到 66 的倍数)

这意味着你下一次掷骰子达到 6 倍数的概率将始终为 16\frac16,从而导致 p=16p = \frac16 的几何分布。这种随机变量的期望由 μ=1p=6\mu = \frac1p= 6 给出。

我们也可以在不知道几何分布行为的情况下得到 66。假设我们预期的掷骰数是 xx。我们可以说 x=16(1)+56(x+1)x = \frac16(1) + \frac56(x+1) \\(有 16\frac16 机会我们得到 66 的倍数,56\frac56 有机会我们在额外掷骰后回到第一个方块)。求解该系统我们还得到x=6x = 6

import random
from typing import Callable

roll_dice: Callable [[None], int] = lambda: random.randrange(1,7)

total_rolls = 0
num_iters = 10_000
#simulates rolling until we get a multiple of 6 num_iters times
for i in range(num_iters):

   run_sum = roll_dice()
   rolls = 1

   #reroll until the sum is a multiple of 6
   while run_sum % 6 != 0:
      run_sum += roll_dice()
      rolls += 1

   total_rolls += rolls

#expecting value close to 6.00
print(total_rolls/num_iters)

Original Explanation

Suppose ss is the sum of our die after nn rolls. There are 66 possible values for what smod6s \mod 6 can be. At first glance, that might suggest there are 66 possible cases for ss after nn rolls, but notice that regardless of what ss is, there exists exactly 11 roll that brings the sum to a multiple of 6. (ie. If 2smod62 \equiv s\mod6 you must roll a 44 to reach a multiple of 66)

This means the probability of reaching a multiple of 6 on your next roll will always be 16\frac16, resulting in a geometric distribution with p=16p = \frac16. The expectation of such a random variable is given by μ=1p=6\mu = \frac1p= 6.

We can also get 66 without knowing the behavior of a geometric distribution. Suppose our number of expected rolls is xx. We can say x=16(1)+56(x+1)x = \frac16(1) + \frac56(x+1) \\ (there is a 16\frac16 chance we get a multiple of 66 and a 56\frac56 chance we go back to square one after an additional roll). Solving this system we also get x=6x = 6.

import random
from typing import Callable

roll_dice: Callable [[None], int] = lambda: random.randrange(1,7)

total_rolls = 0
num_iters = 10_000
#simulates rolling until we get a multiple of 6 num_iters times
for i in range(num_iters):

   run_sum = roll_dice()
   rolls = 1

   #reroll until the sum is a multiple of 6
   while run_sum % 6 != 0:
      run_sum += roll_dice()
      rolls += 1

   total_rolls += rolls

#expecting value close to 6.00
print(total_rolls/num_iters)