開始使用免費開始

機率範例

在這個練習中,我們要複習「有放回抽樣」與「無放回抽樣」的差異。我們會用模擬來計算事件的機率,並改變抽樣方式,看看這對機率有什麼影響。

想像一個裝滿彩色糖果的碗——3 顆藍色、2 顆綠色、5 顆黃色。一次抽一顆,總共抽 3 顆,分別在有放回與無放回的情況下進行。你想要計算「三顆糖果全部都是黃色」的機率。

本練習屬於課程

Python 的統計模擬

檢視課程

練習說明

  • 建立 bowl 為一個清單,內含 3 個藍色 'b'、2 個綠色 'g'、5 個黃色 'y' 的糖果。
  • 分別在有放回(sample_rep)與無放回(sample_no_rep)的情況下抽取 3 顆糖果作為樣本。
  • 對於有放回的樣本,如果 sample_rep 中沒有 'b''g',就將 success_rep 加一。類似地,當 sample_no_rep 中沒有 'b''g' 時,將 success_no_rep 加一。
  • 將成功次數除以迭代次數,計算各自的機率。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Set up the bowl
success_rep, success_no_rep, sims = 0, 0, 10000
bowl = list(____*3 + ____*2 + ____*5)

for i in range(sims):
    # Sample with and without replacement & increment success counters
    sample_rep = np.random.____(bowl, size=3, replace=____)
    sample_no_rep = np.random.____(bowl, size=3, replace=____)
    if ('b' not in sample_rep) & ('g' not in sample_rep) : 
        ____
    if ('b' not in sample_no_rep) & ('g' not in sample_no_rep) : 
        ____

# Calculate probabilities
prob_with_replacement = ____/sims
prob_without_replacement = ____/sims
print("Probability with replacement = {}, without replacement = {}".format(prob_with_replacement, prob_without_replacement))
編輯並執行程式碼