模拟 2 人抛硬币直到得到第一个正面 Python

Simulate 2 people tossing coin until get first head Python

所以我让 AB 玩一个以 A 抛硬币开始的游戏。如果出现正面,则 A 获胜并结束游戏。否则,B 抛球,如果 B 正面,B 获胜并结束游戏。基本上,游戏一直持续到谁的硬币先出现正面。

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

我正在尝试在 Python、运行 4000 模拟中对此进行模拟。但是,我并没有真正接近 A2/3B1/3。下面是我的代码:

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

所回答

你的 AwinBwin 计算表明,如果 A 在第 5 次投掷中获胜,那么由于 A 投掷了 3 次,B 投掷了 2 次,A 获得 3/5 的胜利,而 B得到 2/5。这不是胜利该有的样子。

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

你遇到的一个问题是 random.randomint 应该是

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

您的版本正在生成零、一和二。这完全搞砸了正面朝上的机会,因为您实际上是在掷 3 面骰子,边数 = [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%。

请注意,在 random.py

的文档中

random.randint(a, b) -Return 一个随机整数 N 使得 a <= N <= b.

这与 numpy 不同。random.randomint 给出

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

Documentation is here