模拟两个人掷硬币直到得到第一个头像

2024-09-28 05:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我让AB玩一个游戏,游戏以A掷硬币开始。如果它显示头部,A获胜,游戏结束。否则,B掷骰子,如果B得到一个头球,B获胜,游戏结束。基本上,游戏一直持续到谁的硬币先露出一个头。你知道吗

理论上,A获胜的概率是2/3,而B获胜的概率是1/3。引用here

我试图在Python中模拟这个,运行4000模拟。然而,对于A1/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所回答的那样


Tags: andtrue游戏if硬币random概率head
2条回答

你的一个问题是随机.randomint应该是

A = random.randint(0, 1)  # random 0 and 1
B = random.randint(0, 1)  # random 0 and 1

你的版本产生了0,1,2。这完全是搞砸了获得一个头部的机会,因为你真的是一个三边骰子,边=[0,1,2],只有“1”赢。尝试以下操作:

import random
random.seed(123)
Atoss = 0
Btoss = 0

Awins = 0
Bwins = 0

for i in range(4000):
   head = False
   while (not head):
      A = random.randint(0, 1)  # random 0 and 1

      if A == 1:
         Awins+=1
         head = True

      else:
         B = random.randint(0, 1)  # random 0 and 1
         if B == 1:
            Bwins+=1
            head = True



probA = Awins / (Awins+Bwins)
probB = Bwins / (Awins+Bwins)

print("Probability A: ", probA)
print("Probability B: ", probB)

Out:
'Probability A:  0.6653336665833541'
'Probability B:  0.3346663334166458'

我得到的概率是~A:66%B:33%。你知道吗

注意,在随机.py你知道吗

随机.randint(a,b) -返回一个随机整数N,使a<;=N<;=b

这和numpy.random.randomint随机数这给了

-一个随机整数N,使得a<;=N<;b

Documentation is here

你的AwinBwin计算表明,如果A在第5次掷骰中获胜,那么由于A掷骰3次,B掷骰2次,A赢了3/5,B赢了2/5。胜利不是这样的。你知道吗

另外,您想要的是random.randrange,而不是random.randint,并且将AtossBtoss初始化放在循环之前而不是循环内部意味着它们不会在新的迭代中重置。(不过,在正确的实现中,抛掷计数是不必要的。)

相关问题 更多 >

    热门问题