Created
August 1, 2010 21:30
-
-
Save tanghaibao/503788 to your computer and use it in GitHub Desktop.
casino strategy
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
""" | |
This script simulates a common casino strategy when playing roulette: | |
bet on odd/even, and stick to your choice. bet $20 at start, if you lose, | |
double the bet; if you win, start with the $20 bet again. | |
This simulation suggests that if you follow this strategy for a few rounds (say 50), | |
more than 90% of the people will make money, with only a slight chance of bankrupt | |
$ python casino_strategy.py | |
Simulating 50 rolls per trial and generate 10000 trials | |
mean: 10006, median: 10480 | |
93% of the samples earned money | |
3% of the samples got bankrupt | |
However if you adopt this strategy long enough, eventually you'll lose money. | |
See "gambler's ruin" <http://en.wikipedia.org/wiki/Gambler's_ruin> | |
""" | |
from random import choice | |
import sys | |
w = lambda x: sys.stderr.write("%s\n" % x) | |
class Gambler: | |
__slots__ = ("money",) | |
def __init__(self, money=10000): | |
self.money = money | |
reset = __init__ | |
def roll(self, times=50, verbose=False): | |
bet = 20 | |
for i in range(times): | |
self.money -= bet | |
won = choice((True, False)) # binary choice | |
# the gambling strategy | |
if won: | |
self.money += bet * 2 | |
next_bet = 20 | |
else: | |
next_bet = bet * 2 | |
if verbose: | |
w("bet: %d, %s, balance: %d" % \ | |
(bet, "won" if won else "lost", self.money)) | |
# can't bet more than you have | |
if next_bet > self.money: | |
next_bet = self.money | |
bet = next_bet | |
return self.money | |
if __name__ == "__main__": | |
ITERATIONS = 10000 | |
ROLLS = 50 | |
finals = [] | |
g = Gambler() | |
for i in range(ITERATIONS): | |
g.reset() | |
finals.append(g.roll(times=ROLLS)) | |
import matplotlib.pyplot as plt | |
import numpy as np | |
finals = np.array(finals, dtype=int) | |
w("Simulating %d rolls per trial and generate %d trials" % (ROLLS, ITERATIONS)) | |
w("mean: %d, median: %d" % (np.mean(finals), np.median(finals))) | |
w("%d%% of the samples earned money" % (len(finals[finals > 10000]) * 100 / ITERATIONS)) | |
w("%d%% of the samples got bankrupt" % (len(finals[finals == 0]) * 100 / ITERATIONS)) | |
plt.hist(finals, bins=100) | |
plt.savefig(__file__.replace(".py", ".png")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment