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()

 圖形

 

 

 

。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM