python - 如何用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 数组,因此要获得上述相同的结果,您只需将第三列中的条目数相加 '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 进行模拟并提供模拟的形状。应该给你类似的东西。
推荐阅读
- rust - actix_web 将配置传递给处理程序
- postgresql - 在 PostgreSQL 中,如何获得所有先前值都满足条件的最大值
- python - 如何在特定字符之外的指定位置拆分重复字符串?
- java - 如何在 Map 中进行迭代循环
, FlowRuleStats>? - ios - Firebase如何检查快照的孩子本身是否属于Datasnapshot类型
- node.js - 在 Express 中,为什么 res.send() 在发送存储数字的数组项而不是字符串时会抛出错误?
- actionscript-3 - 使用接口编写 UI 组件树
- swift - SwiftUI 中的键盘快捷键
- javascript - ALT+箭头键在表格中的单元格之间导航
- c# - 我在将信息从数据库获取到视图中的图表时遇到问题