首页 > 解决方案 > 如何用python估计硬币翻转的概率?

问题描述

我创建了一个模拟特定数量的硬币翻转的程序。模拟抛硬币 8 次,目前正在运行模拟 10000 次。我想通过模拟找出具体的概率。例如,根据 10000 个结果,在 8 次翻转中恰好得到 2 个反面的概率是多少。我对如何做到这一点有一个简短的想法,但是我不确定如何准确地隔离两个结果。硬币还设置了随机偏差。

代码:

# Random numbers:
coin_flip_seed = random_num

bias_choices = [0.2, 0.4, 0.6, 0.8]

coin_flip_bias = bias_choices[coin_flip_seed % 4]

# Main simulation:
np.random.seed(coin_flip_seed)

results = [['S', 'S', 'S', 'S', 'S', 'S', 'S', 'S']]

tests = 10000

for j in range(tests):
    flips = []
   
    for i in range(8):
        flip_result = np.random.binomial(1,coin_flip_bias)
     
        if flip_result == 1:
            flips = np.append(flips, 'H')
        else:
            flips = np.append(flips, 'T')
   
    results = np.append(results, [flips], axis = 0)

results = results[1:]

print(results[4])
# Probability of getting exactly 2 tails:
num_2T = 0

for k in range(tests):
    if results[k,2] == 'T':
        num_2T += 1
        

print("The probability of getting exactly 2 tails is: ", num_2T/tests)

目前我只能找出在第三次翻转时得到 1 条尾巴的概率。提前致谢。

标签: pythonsimulationprobability

解决方案


如果我设置随机种子:

coin_flip_seed = 111

运行你的代码,我得到:

num_2T
1980

您的results对象是一个 numpy 数组,因此要获得上述相同的结果,您只需将第三列中的条目数相加 'T' :

np.sum(results[:,2] == 'T')
1980

同样,如果我们根据您现在拥有的矩阵来考虑,您需要的是正好有 2 个“T”的行数。这为每一行提供了“T”的数量:

np.sum(results=='T',axis=1)

我们只计算其中有多少是 2:

np.sum(np.sum(results=='T',axis=1)==2)
2933

最后作为评论,您很可能可以results使用 np.random.choice 进行模拟并提供模拟的形状。应该给你类似的东西。


推荐阅读