Python 模拟伯努利试验和二项分布

1、模拟 27 次投掷硬币的伯努利试验

代码:

from scipy import stats
import numpy as np

p = 0.5
# 生成冻结分布函数
bernoulliDist = stats.bernoulli(p) 

# 模拟 27 次伯努利实验
trails = bernoulliDist.rvs(27) 

# 查看结果
trails

2、模拟二项分布

代码

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

Ps = [0.5, 0.6, 0.7]
Ns = [20, 20, 20]
colors = ['blue', 'green', 'red']

# 模拟试验绘制图形
for p,n, c in zip(Ps, Ns, colors):
    binomDist = stats.binom(n, p)
    P_k = binomDist.pmf(np.arange(n + 1))
    
    label='p={},n={}'.format(p, n)
    plt.plot(P_k, '--',marker='o', label=label, ms=5)
    
plt.xlabel('X')
plt.ylabel('P(X)')
plt.legend()

plt.show()

 图形

 

。。。

原文地址:https://www.cnblogs.com/shanger/p/11963396.html