如何估计 python 抛硬币的概率?

How can I estimate the probability of coin flips with 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)

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

如果我设置随机种子:

coin_flip_seed = 111

还有运行你的代码,我得到:

num_2T
1980

您的 results 对象是一个 numpy 数组,因此要获得与上面相同的结果,您只需将第 3 列中的条目数相加 '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

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