Created
May 19, 2010 00:30
-
-
Save artlung/405766 to your computer and use it in GitHub Desktop.
Monte Carlo Python Program
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
"""Run a Monte Carlo simulation to validate the lottery example.""" | |
import random | |
from lottery import winner, PEOPLE | |
def simulate(runs, f=winner, arg=PEOPLE): | |
"""Simulate function f with argument arg with number of given runs.""" | |
# Store the number of results in a dict. | |
result_counts = {} # this is a dict | |
# Initialize the result counter. | |
for a in arg: | |
result_counts[a] = 0 | |
for run in xrange(runs): | |
result = f(arg) | |
result_counts[result] += 1 | |
return result_counts | |
if __name__ == '__main__': | |
# random.seed(0) | |
total_runs = 100000 | |
people_counts = simulate(total_runs) | |
for k,v in people_counts.items(): | |
print "%s: %d (%.02f%%)" % (k, v, (v / float(total_runs) * 100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I do not recall the context, 12 years later, of why I saved this as a gist.