六的倍数
Multiple of Six
题目详情
你掷出一个公平的六面骰子,然后将结果相加,直到达到 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.
解析
假设 是 掷骰后我们的骰子的总和。 的可能值与 的值相同。 乍一看,这可能表明 掷骰后 可能存在 的情况,但请注意,无论 是什么,都存在 掷骰,使总和达到 6 的倍数。(即,如果 ,则必须掷出 才能达到 的倍数)
这意味着你下一次掷骰子达到 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 is the sum of our die after rolls. There are possible values for what can be. At first glance, that might suggest there are possible cases for after rolls, but notice that regardless of what is, there exists exactly roll that brings the sum to a multiple of 6. (ie. If you must roll a to reach a multiple of )
This means the probability of reaching a multiple of 6 on your next roll will always be , resulting in a geometric distribution with . The expectation of such a random variable is given by .
We can also get without knowing the behavior of a geometric distribution. Suppose our number of expected rolls is . We can say (there is a chance we get a multiple of and a chance we go back to square one after an additional roll). Solving this system we also get .
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)