所以我让A
和B
玩一个游戏,游戏以A
掷硬币开始。如果它显示头部,A
获胜,游戏结束。否则,B
掷骰子,如果B
得到一个头球,B
获胜,游戏结束。基本上,游戏一直持续到谁的硬币先露出一个头。你知道吗
理论上,A
获胜的概率是2/3
,而B
获胜的概率是1/3
。引用here
我试图在Python
中模拟这个,运行4000
模拟。然而,对于A
和1/3
我并没有真正接近2/3
对于B
。下面是我的代码:
import random
Atoss = 0
Btoss = 0
Awins = []
Bwins = []
for i in range(4001):
head = False
while (not head):
A = random.randint(0, 2) # random 0 and 1
Atoss += 1
if A == 1:
head = True
else:
B = random.randint(0, 2) # random 0 and 1
Btoss += 1
if B == 1:
head = True
totalToss = Atoss + Btoss
Awin = Atoss / totalToss
Awins.append(Awin)
Bwin = Btoss / totalToss
Bwins.append(Bwin)
probA = sum(Awins) / len(Awins)
probB = sum(Bwins) / len(Bwins)
print("Probability A: ", probA)
print("Probability B: ", probB)
我在什么地方搞砸了吗?你知道吗
编辑:
将randint(0, 2)
改为randint(0, 1)
解决了这个问题,正如@bart cubrich所回答的那样
你的一个问题是随机.randomint应该是
你的版本产生了0,1,2。这完全是搞砸了获得一个头部的机会,因为你真的是一个三边骰子,边=[0,1,2],只有“1”赢。尝试以下操作:
我得到的概率是~A:66%B:33%。你知道吗
注意,在随机.py你知道吗
随机.randint(a,b) -返回一个随机整数N,使a<;=N<;=b
这和numpy.random.randomint随机数这给了
-一个随机整数N,使得a<;=N<;b
Documentation is here
你的
Awin
和Bwin
计算表明,如果A在第5次掷骰中获胜,那么由于A掷骰3次,B掷骰2次,A赢了3/5,B赢了2/5。胜利不是这样的。你知道吗另外,您想要的是
random.randrange
,而不是random.randint
,并且将Atoss
和Btoss
初始化放在循环之前而不是循环内部意味着它们不会在新的迭代中重置。(不过,在正确的实现中,抛掷计数是不必要的。)相关问题 更多 >
编程相关推荐