""" craps_2010.py Craps simulation, worked out in class Oct 14 2010 Jim Mahoney, GPL """ debugPrint = False def d6(n): """ Return total from rolling n 6 sided dice. """ from random import randrange total = 0 for i in range(n): total = total + randrange(1,7) return total def test_dice(n_dice, number_of_times): """ Make sure d6() is doing what it should. >>> test_dice(2, 100) True """ low = n_dice high = 6 * n_dice for i in range(number_of_times): roll = d6(n_dice) if roll < low: return False if roll > high: return False return True def craps(): """ Simulate one round of craps. Return True for win. """ roll1 = d6(2) if debugPrint: print " debug: roll1 = ", roll1 if roll1 == 7 or roll1 == 11: return True elif roll1 == 2 or roll1 == 3 or roll1 == 12: return False else: while True: rolln = d6(2) if debugPrint: print " debug: rolln = ", rolln if rolln == roll1: return True elif rolln == 7: return False def count_wins(n_games): """ Return number of wins when playing n_games of craps. """ wins = 0 for i in range(n_games): if craps(): wins = wins + 1 return wins def simulate_series(n_games, n_times): """ Return (high, low) probability of wins in n_games over n_times. """ highest = -1 lowest = 1.1 for i in range(n_times): n_wins = count_wins(n_games) prob = float(n_wins)/n_games if prob > highest: highest = prob if prob < lowest: lowest = prob return (highest, lowest) def main(): """ Simulate craps, and report odds. """ print "--- Estimated odds of winning at craps ---" n_games = input("How many games would you like to simulate? ") print "Simulating %i games ..." % n_games n_wins = count_wins(n_games) print "done." print "Number of simulated wins : %i" % n_wins print "Odds of winning : %.3f" % (float(n_wins) / n_games) # print "--- Estimated error ---" n_times = input("How many times would you like to repeat that series of %i games? " % n_games) print "Simulating %i series of %i games ..." % (n_times, n_games) (high_prob, low_prob) = simulate_series(n_games, n_times) print "done." print "Lowest estimated odds = %.3f" % low_prob print "Highest estimated odds = %.3f" % high_prob print "Error range = (high-low) = %.3f" % (high_prob - low_prob) if __name__ == "__main__": from doctest import testmod testmod() main()