A Random Walk

Now, let's adapt the game of hop-and-skip, by cutting the user out. Instead, we will start in the middle of the field, and will either step right or left, at random. We want to know how long it takes to reach either end of the field.

Why do this? Well, random walks are useful in modeling physical processes like Brownian motion, and also the behaviour of stock prices.

Here is a program that counts the number of steps in the random walk:
import random

w = int(raw_input("width? "))
x = w/2
pathLength = 0
while True:
    r = random.randrange(1,3)

    if r == 1:
        x += 1
    else:
        x -= 1

    print 'r=', r, 'x=',x
    if x < 0 or x >= w:
        break
    pathLength += 1
print 'The walk took ', pathLength, 'steps'
    
Here, I've introduced another function from the random library: random.randrange(a,b) returns a random value between a and b-1, so random.randrange(1,3) return either 1 or 2, at random.

Each time we run the program, a different sequence occurs, with a different path length. Now, I want to get some statistics: how long is the path length, on average?

To do this, I need to run the random walk many times, and get the path length each time. So, I will place the above code inside another loop, which runs 100 times. I will add up all the path lengths, and divide by 100, to get the average length. This program is the result:

import random

w = int(raw_input("width? "))
sum_path_lengths = 0
for attempt in range(100):
   x = w/2
   pathLength = 0
   while True:
       r = random.randrange(1,3)

       if r == 1:
           x += 1
       else:
           x -= 1

       if x < 0 or x >= w:
           break
       pathLength += 1
   sum_path_lengths += path_length
avg_path_length = float(sum_path_lengths) / 100