Trials until first success¶
Problem¶
Question
On the average, how many times must a die be thrown until one gets a 6?
平均需要掷骰子多少次才能得到一个6点?
Tip¶
Tip
Geometric series
几何级数
Solutions¶
Solution1: Analysis¶
Solution1: Analysis
Let's denote the number of tosses required as
T | Probability |
---|---|
1 | |
2 | |
3 | |
... | ... |
Therefore, we have
From
we can deduce that
Hence,
记问题需要的投掷次数为
T | Probability |
---|---|
1 | |
2 | |
3 | |
... | ... |
所以有
由
得
Solution2: Elegant Analysis¶
Solution2: Elegant Analysis
This extremely elegant problem-solving idea comes from the reference answers in the book.
When the first toss is a failure,
the mean number of tosses required is
这个极其优雅的解题思路来自书的参考答案。
当第一次投掷失败时,所需的平均投掷次数为
Solution3: Simulation¶
Solution3: Simulation
We can approximate the average number of times it takes to roll a dice to get a 6 by simulating the process of rolling a dice.
import random
def roll() -> int:
return random.randint(1, 6)
def roll_6_count() -> int:
count = 1
r = roll()
while r != 6:
r = roll()
count += 1
return count
def simulation(run_nums: int = 100000) -> None:
roll_counts = [roll_6_count() for _ in range(run_nums)]
print(f"Expectation times to got a 6: {sum(roll_counts) / run_nums}")
simulation()
Expectation times to got a 6: 6.02792
可以通过模拟掷骰子的过程来近似得到平均需要掷骰子多少次才能得到一个6点。
import random
def roll() -> int:
return random.randint(1, 6)
def roll_6_count() -> int:
count = 1
r = roll()
while r != 6:
r = roll()
count += 1
return count
def simulation(run_nums: int = 100000) -> None:
roll_counts = [roll_6_count() for _ in range(run_nums)]
print(f"Expectation times to got a 6: {sum(roll_counts) / run_nums}")
simulation()
Expectation times to got a 6: 5.98562