我想模擬一枚有偏差的硬幣被翻轉 2048 次,并記錄每次嘗試的結果,以及每枚硬幣的總計數。我當前的代碼功能齊全,能夠模擬公平的硬幣,但我不確定如何在當前代碼中實作 0.25 的偏差。我能做些什么來增加這種特殊的偏見?
def heads_tails(number_of_flips):
tails_count = 0
heads_count = 0
for i in range(number_of_flips):
rand = random.randint(1,2)
if rand == 1:
tails_count = 1
print(tails_count, 'tails')
else:
heads_count = 1
print(heads_count, 'heads')
print('Total Heads: ', heads_count)
print('Total Tails: ', tails_count)
heads_tails(2048)
uj5u.com熱心網友回復:
您應該使用random.choices, 和所需的權重。
rand = random.choices((1,2),weights=(0.4,0.6)) # 40% for 1 , and 60% for 2
uj5u.com熱心網友回復:
您可以修改這部分代碼
rand = random.randint(1,2)
if rand == 1:
至
rand = random.random() # randoms a value between 0.0 and 1.0
if rand < 0.25:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516073.html
下一篇:僅保留檔案名的最終版本或最新版本
