Skip to content

Instantly share code, notes, and snippets.

@BytefishMedium
Created July 24, 2024 11:37
Show Gist options
  • Select an option

  • Save BytefishMedium/ef1058bfc4e5d21d6a4deb3a8e3968b1 to your computer and use it in GitHub Desktop.

Select an option

Save BytefishMedium/ef1058bfc4e5d21d6a4deb3a8e3968b1 to your computer and use it in GitHub Desktop.
import random
import matplotlib.pyplot as plt
def simulate_game(A_start, B_start):
"""Simulate a single game until one player loses all money."""
A_money = A_start
B_money = B_start
while A_money > 0 and B_money > 0:
if random.random() < 2 / 3:
# A wins the round
A_money += 1
B_money -= 1
else:
# B wins the round
A_money -= 1
B_money += 1
return A_money > 0 # True if A wins, False if B wins
def estimate_probability(A_start, B_start, num_simulations):
"""Estimate the probability that A wins all the money."""
A_wins = 0
for _ in range(num_simulations):
if simulate_game(A_start, B_start):
A_wins += 1
return A_wins / num_simulations
# Define the range for B's initial money
B_start_values = range(1, 101) # B's initial money from 1 to 100
A_start = 1 # A always starts with $1
num_simulations = 10000 # Number of simulations for each initial condition
A_win_probabilities = []
# Run the simulations for each initial condition of B's money
for B_start in B_start_values:
prob = estimate_probability(A_start, B_start, num_simulations)
A_win_probabilities.append(prob)
print(f"B starts with ${B_start}, A's win probability: {prob:.4f}")
# Plotting the results
plt.figure(figsize=(10, 6))
plt.plot(B_start_values, A_win_probabilities, marker='o', linestyle='-', color='b')
plt.xlabel('B\'s Initial Money')
plt.ylabel('A\'s Win Probability')
plt.title('A\'s Win Probability vs B\'s Initial Money')
plt.grid(True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment