#!/usr/bin/env python # https://svn.red-bean.com/repos/kfogel/trunk/bin/n-rolls # This code is in the public domain. -Karl Fogel # Suppose you have an N-sided die, and that you pick some random # number R between 1 and N. If you roll the die N times, what is the # probability that *at least once* R will come up? # # Hat tip to Noel Taylor for the excellent problem. import sys import getopt import random import itertools def main(): if len(sys.argv) == 1: sys.stderr.write("Usage: %s N\n" % sys.argv[0]) sys.exit(1) randy = random.SystemRandom() n = int(sys.argv[1]) # Choose any number to be R. Note that it should not (and # apparently does not) make a difference if you put the choosing of # R inside the outer 'iterations' loop below instead of here. r = randy.randrange(1, n + 1) # Arbitrarily do 10000 runs. iterations = 10000 num_hits = 0 for _i in itertools.repeat(None, iterations): for _j in itertools.repeat(None, n): # roll the die N times if randy.randrange(1, n + 1) == r: num_hits += 1 break # We said "at least once", right? print "%.2f%% (%d / %d) of runs chose %d from the range 1-%d" \ % (float(num_hits * 100) / float(iterations), num_hits, iterations, r, n) if __name__ == '__main__': main()