小球放到盒子里概率问题
10个小球,随机扔到12个盒子里,求恰好有10个盒子都为空的概率。题目要求使用暴力模拟10万次来算一下。 原始题目是有人去字节面试,这个是面试题目的第一题。原文在此:https://www.nowcoder.com/discuss/353156239813189632
题目本身不难,只是因为概率太低,使用10万次模拟往往一次结果也没有。最终计算结果,这个概率大约为100万分之一,详细解释上文也给出了,所以最好使用100万次的模拟。
概率计算: C(12, 2) * (2^10 -2) / 12^10 ~= 0.000001089
这个概率极低,这个事情最有意思的一点是,如果不是问恰好10个盒子都是空,而是9个盒子为空或8个为空,那这个概率就会增加很多,这也跟我们实际经验相符。
恰好9个盒子为空的概率: C(12, 3) * (3^10 - C(3,1) - C(3,2) * (2^10 - 2)) / 12^10 ~= 0.0001989
恰好8个盒子为空的概率(这个式子有点复杂,里面包含了上面式子的一部分,我之前列式错了,得到的结果为0.008,跟程序模拟的结果怎么也对不上,后来发现式子列的有问题): C(12, 4) * (4^10 - C(4,1) - C(4,2) * (2^10 -2) - C(4,3) * (3^10 - C(3,1) - C(3,2) * (2^10 - 2))) / 12^10 ~= 0.006544
import random
NUM_OF_BOXES = 12
NUM_OF_BALLS = 10
def try_once(blank_box_num):
boxes = [False for _ in range(NUM_OF_BOXES)]
for _ in range(NUM_OF_BALLS):
picked_box_num = random.randint(0, NUM_OF_BOXES -1)
boxes[picked_box_num] = True
return boxes.count(False) == blank_box_num
def try_many(times, blank_box_num):
bingo = 0
for _ in range(times):
if(try_once(blank_box_num)):
bingo = bingo + 1
print(f"The ratio of there are only \
{blank_box_num} boxes empty: {bingo}/{times}")
# Test
for _ in range(5):
try_many(1000000, 10)
for _ in range(5):
try_many(1000000, 9)
for _ in range(5):
try_many(1000000, 8)
程序运行结果如下,跟计算的概率相当匹配:
The ratio of there are only 10 boxes empty: 2/1000000
The ratio of there are only 10 boxes empty: 1/1000000
The ratio of there are only 10 boxes empty: 0/1000000
The ratio of there are only 10 boxes empty: 0/1000000
The ratio of there are only 10 boxes empty: 0/1000000
The ratio of there are only 9 boxes empty: 194/1000000
The ratio of there are only 9 boxes empty: 163/1000000
The ratio of there are only 9 boxes empty: 194/1000000
The ratio of there are only 9 boxes empty: 200/1000000
The ratio of there are only 9 boxes empty: 197/1000000
The ratio of there are only 8 boxes empty: 6536/1000000
The ratio of there are only 8 boxes empty: 6516/1000000
The ratio of there are only 8 boxes empty: 6551/1000000
The ratio of there are only 8 boxes empty: 6511/1000000
The ratio of there are only 8 boxes empty: 6560/1000000