import random # Programmer: Sriram Pemmaraju # Date: Feb 10, 2012 # Version 4: moves the person at random, one step at a time, left or right, # until the person reaches a barrier n or -n. Performs many simulations # each value of the barrier and returns the average walk length. # This function takes in the value of the barrier, simulates a random # walk that terminates on reaching the barrier, and returns the length # of the simulated random walk def randomWalk(n): location = 0 # tracks the person's current location length = 0 # tracks the length of the random walk # This moves the person until she reaches the barrier at n or -n while abs(location) != n: step = random.randint(0, 1) # returns 0 or 1, each with prob. 1/2 # Adjusts the random number to be either -1 or +1 if step == 0: step = -1 location = location + step # updates location length = length + 1 return length # Simulates random walks with barrier n as many times as specified by # numRepititions. Returns the average length of a walk. def manyRandomWalks(n, numRepititions): sum = 0 # tracks the total length of all simulated random walks counter = 0 # tracks the number of walks being performed while counter < numRepititions: sum = sum + randomWalk(n) counter = counter + 1 return float(sum)/numRepititions # Main loop for generating various values of the barrier size n = 10 while n <= 100: print manyRandomWalks(n, 100) n = n + 10