2017-04-01 83 views
0

我想知道如何在擲硬幣模擬器中計算結果的可能性。頭部有50%的可能性和50%的尾巴。 我會如何解決返回結果的可能性? 這裏是我的代碼:查找概率

您在模擬已經得到了結果的
import random 
head = 0 
tail = 0 
length = int(input('How many coins do you want to flip? ')) 
for i in range(length): 
    side = random.randint(0, 1) 
    if side == 1: 
     head = head + 1 
    else: 
     tail = tail + 1 
print('There where ' + str(tail) + ' tails and ' + str(head) + ' heads') 
+0

您是否想要測量在給定模擬次數的情況下獲得相同數量的正面和反面的概率? – fulaphex

+0

說你翻了10次我想告訴你它給出的尾部數量的概率,然後是頭部的數量 – Monkeybike123

+0

你要我告訴你:有p1的概率,有1尾,p2會有兩個尾巴...? – fulaphex

回答

2

概率可以打印這樣的:

print('Tail: ' + str(float(tail)/length) + ' Head ' + str(float(head)/length)) 
+0

這顯示了每個結果(頭/尾)的百分比,而不是獲得該特定結果的機會。 – Monkeybike123

1

要計算你應該使用二項式係數這樣的概率。 enter image description here - 這給你所有可能的h頭和t尾的組合。用enter image description here所有可能的組合來區分它,並且你得到了你的概率。

爲了得到階乘函數,感嘆號,你可以寫:

def fact(n): 
    if n == 0: 
     return 1 
    return n * fact(n-1) 

這將爲所有正數工作。如果你想加快速度,你可以有一本字典,讓你記住以前的電話。那將是:

_d = {0:1} 
def fact(n): 
    if n in _d: return _d[n] 
    _d[n] = n * fact(n-1) 
    return _d[n] 
+0

我如何得到python中的感嘆號,我明白它是如何工作的,但是不會被重新調用 – Monkeybike123

+0

感嘆號只是階乘函數。 – fulaphex