# This program simulates the following process: several people # announce their birthdays until two of them share a birthday. # We assume that no one is born of Feburary 29th (sorry!), # and that every day is equally likely to be someone's birthday. # The function birthday() counts the number of people before # we get a match. The function makehist(n) runs n trials of # this process and then draws a histogram of the data. # Are you surprised by how small the values are? import random import numpy as np import matplotlib.pyplot as plt def birthday(): birthdays = [] while True: newday = random.randint(0,364) if newday not in birthdays: birthdays.append(newday) else: return len(birthdays) + 1 def makehist(n): bds = [birthday() for _ in range(n)] hist, bins = np.histogram(bds, bins=20) widths = np.diff(bins) plt.bar(bins[:-1], hist, widths) plt.show() makehist(100)