Skip to content

Instantly share code, notes, and snippets.

@riceissa
Created February 12, 2020 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riceissa/f0679ff2f032ca16d46ba539e40b6623 to your computer and use it in GitHub Desktop.
Save riceissa/f0679ff2f032ca16d46ba539e40b6623 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import numpy as np
def flip():
return np.random.choice([0, 1])
def play(wealth, cost, max_rounds=1e5):
num_rounds = 0
while wealth > cost and num_rounds < max_rounds:
round_winnings = 1
while True:
coin = flip()
if coin == 0:
round_winnings *= 2
else:
break
wealth = wealth - cost + round_winnings
num_rounds += 1
return {"wealth": wealth, "num_rounds": num_rounds}
wealth = 1000 # starting wealth
cost = 9 # cost per round to play the game
print("Using starting wealth of {} and cost per round of {} below.\n".format(wealth, cost))
# first, play for as long as possible
print("Here are some typical rounds, playing for as long as possible:\n")
for _ in range(5):
result = play(wealth, cost)
print("* survived {} rounds with remaining wealth {}".format(result["num_rounds"], result["wealth"]))
# next, commit to playing at most r rounds, and find probability of leaving
# with more money than you started with
print("\nNow we will commit to play a fixed number of rounds (or until\n"
"wealth runs out), and find the probability that we leave with\n"
"more money than we start with:\n")
for r in [10, 100, 1000, 10000]:
wins = 0
losses = 0
for _ in range(1000):
if play(wealth, cost, max_rounds=r)["wealth"] > wealth:
wins += 1
else:
losses += 1
print("* committing to play {} rounds: we had {} wins and {} losses, so {}% chance of winning".format(r, wins, losses, round(wins/(wins + losses)*100, 1)))
@riceissa
Copy link
Author

Typical output of the program:

Using starting wealth of 1000 and cost per round of 9 below.

Here are some typical rounds, playing for as long as possible:

  • survived 171 rounds with remaining wealth 3
  • survived 798 rounds with remaining wealth 7
  • survived 1460 rounds with remaining wealth 4
  • survived 163 rounds with remaining wealth 4
  • survived 717 rounds with remaining wealth 3

Now we will commit to play a fixed number of rounds (or until
wealth runs out), and find the probability that we leave with
more money than we start with:

  • committing to play 10 rounds: we had 109 wins and 891 losses, so 10.9% chance of winning
  • committing to play 100 rounds: we had 179 wins and 821 losses, so 17.9% chance of winning
  • committing to play 1000 rounds: we had 83 wins and 917 losses, so 8.3% chance of winning
  • committing to play 10000 rounds: we had 17 wins and 983 losses, so 1.7% chance of winning

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment