Python
•
•
By Alan
蒙地卡羅模擬:用 Python 破解大樂透中獎機率
數據不會說謊
大樂透從 49 個號碼選 6 個,頭獎機率約為 1/13,980,000。為了直觀感受這個數字,我們可以寫一個模擬器。
利用 random.sample(range(1, 50), 6) 產生一組不重複號碼,並與「開獎號碼」進行集合運算 (set.intersection) 計算中獎號碼數。
import random
def simulate_lottery(trials):
jackpot_count = 0
winning_numbers = set(random.sample(range(1, 50), 6))
for _ in range(trials):
my_numbers = set(random.sample(range(1, 50), 6))
if len(winning_numbers & my_numbers) == 6:
jackpot_count += 1
return jackpot_count
當你跑了 1000 萬次迴圈 (可能需要幾分鐘),發現 jackpot_count 經常是 0 時,你就會明白為什麼莊家總是贏家。這是一個很好的機率與 Python 集合操作練習。