So I have A and B play a game which begins with A tossing a coin. If it shows head, A wins and game over. Else, B tosses and if B gets a head, B wins and game over. Basically, the game continues until whoever's coin shows a head first.
Theoretically, the probability of A winning is 2/3, and the probability of B winning is 1/3. Referenced here
I'm trying to simulate this in Python, running 4000 simulations. However, I'm not really getting close to 2/3 for A and 1/3 for B. Below is my code:
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)
Did I mess up somewhere?
EDIT:
Changing randint(0, 2) to randint(0, 1) solves the problem, as answered by @bart cubrich
Awin/Bwin/Awins/Bwinscomputations don't look anything like how victory in the game is defined. - user2357112