Skip to content

Instantly share code, notes, and snippets.

@ismaild
Created November 25, 2012 14:52
Show Gist options
  • Select an option

  • Save ismaild/4143823 to your computer and use it in GitHub Desktop.

Select an option

Save ismaild/4143823 to your computer and use it in GitHub Desktop.
Monte Carlo Simulation for Urn Models
import random
def noReplacementSimulation(numTrials):
'''
Runs numTrials trials of a Monte Carlo simulation
of drawing 3 balls out of a bucket containing
3 red and 3 green balls. Balls are not replaced once
drawn. Returns the a decimal - the fraction of times 3
balls of the same color were drawn.
'''
count_matches = 0
n = 0
while n < numTrials:
urn = ['R','R','R','G','G','G']
ball_set = set()
n += 1
for x in range(3):
ball = random.choice(urn)
urn.pop(urn.index(ball))
ball_set.add(ball)
if len(ball_set) == 1:
count_matches += 1
print 'trials:', n, 'set:', ball_set, 'urn:', urn, '# All balls the same:', count_matches
return count_matches/float(numTrials)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment