Created
February 12, 2020 00:31
-
-
Save riceissa/f0679ff2f032ca16d46ba539e40b6623 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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: