在有偏差的骰子上寻找概率
Finding Probability on a biased die
我不得不模拟一个有偏向的模具,使得 6 出现的次数超过 50%。我能够使用:
from random import randint,choice
def bdie():
out = random.randint(0,2)
if (out==1 or out == 2):
return 6
else:
r = choice([i for i in range(1,7) if i not in [6]])
return r
def bdthrow(n):
output = []
for i in range(0,n):
if n>0 & n<=100000000:
outcome = bdie()
output.append(outcome)
else:
print("Invalid")
print(output)
其输出为:
[6, 6, 6, 6, 6, 3, 6, 3, 5, 4]
现在,在这个偏向的骰子上,我应该找到顶面为 5 的概率,我需要找到骰子每个面的平均数。
现在在纸上求和很容易,我可以找到概率,但我不确定如何在 python 中实现它。
如果我没理解错的话,您正在寻找获得 5 的无偏估计量。这样的估计量可以是掷骰子足够次数时获得 5 的次数。即 # fives / n
.
从内存的角度来看,我建议使用 defaultdict
。也没有必要在每一轮都检查 n
的值。
from random import randint,choice
from collections import defaultdict
def bdie():
out = randint(0,2)
if (out==1 or out == 2):
return 6
else:
r = choice([i for i in range(1,7) if i not in [6]])
return r
def bdthrow(n):
output = defaultdict(int)
for i in range(0,n):
outcome = bdie()
output[outcome] +=1
return (float(output[5])/n)
代码几乎没有其他优化,但天真地应该可以。
我不得不模拟一个有偏向的模具,使得 6 出现的次数超过 50%。我能够使用:
from random import randint,choice
def bdie():
out = random.randint(0,2)
if (out==1 or out == 2):
return 6
else:
r = choice([i for i in range(1,7) if i not in [6]])
return r
def bdthrow(n):
output = []
for i in range(0,n):
if n>0 & n<=100000000:
outcome = bdie()
output.append(outcome)
else:
print("Invalid")
print(output)
其输出为:
[6, 6, 6, 6, 6, 3, 6, 3, 5, 4]
现在,在这个偏向的骰子上,我应该找到顶面为 5 的概率,我需要找到骰子每个面的平均数。
现在在纸上求和很容易,我可以找到概率,但我不确定如何在 python 中实现它。
如果我没理解错的话,您正在寻找获得 5 的无偏估计量。这样的估计量可以是掷骰子足够次数时获得 5 的次数。即 # fives / n
.
从内存的角度来看,我建议使用 defaultdict
。也没有必要在每一轮都检查 n
的值。
from random import randint,choice
from collections import defaultdict
def bdie():
out = randint(0,2)
if (out==1 or out == 2):
return 6
else:
r = choice([i for i in range(1,7) if i not in [6]])
return r
def bdthrow(n):
output = defaultdict(int)
for i in range(0,n):
outcome = bdie()
output[outcome] +=1
return (float(output[5])/n)
代码几乎没有其他优化,但天真地应该可以。