繁体   English   中英

如何用 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)

目前我只能找出在第三次翻转时得到 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并提供模拟的形状。 应该给你类似的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM