0

I wrote the code for a two dimensional random walk:

def r2walk(T):
    x = np.zeros((T))
    y = np.zeros((T))
    x = [0]*T
    y = [0]*T
    for t in range(0,T):
        walk = random.random()
        if 0 < walk < .25:
            x[t] = x[t-1] + 1
        elif .25 < walk < .5:
            x[t] = x[t-1] - 1
        elif .5 < walk < 0.75:
            y[t] = y[t-1] + 1
        else:
            y[t] = y[t-1] - 1
     return x, y

I would like to be able to plot the path of the random walk on a x,y grid but am unsure how to proceed. Also I am very new to python and I would appreciate any tips on writing code more efficiently (or elegantly as your perspective might put it). Thank you in advance!

pauld
  • 401
  • 1
  • 5
  • 20
  • 1
    x = [0]*T : this makes the previous definition of x get forgotten, and is completely unnecessary. To plot, just use plot() from matplotlib. – mdurant Jul 28 '14 at 20:35
  • You might also consider doing `for t in range(1,T):`, because now on round 0 you probably accidentally use the item `x[-1]` (which is zero and does not cause any severe damage in this context). There are also some rather simple ways of creating your walk by using `np.cumsum`, but that is another story. (The friendly people at CodeReview might want to help you to iron out the small inefficiencies if you want faster and more compact code.) – DrV Jul 28 '14 at 20:41

1 Answers1

1

You need to use some plotting package. The most commonly used is matplotlib which works splendidly with numpy.

Then your code looks like:

import matplotlib.pyplot as plt
import numpy as np
import random

def r2walk(T):
    x = np.zeros((T))
    y = np.zeros((T))
    for t in range(0,T):
        walk = random.random()
        if 0 < walk < .25:
            x[t] = x[t-1] + 1
        elif .25 < walk < .5:
            x[t] = x[t-1] - 1
        elif .5 < walk < 0.75:
            y[t] = y[t-1] + 1
        else:
            y[t] = y[t-1] - 1
    return x, y



x, y = r2walk(100)

# create a figure
fig = plt.figure()
# create a plot into the figure
ax = fig.add_subplot(111)
# plot the data
ax.plot(x,y)

This will give you:

enter image description here

If you are completely new with matplotlib, I suggest you have a look at IPython and pylab plus of course some matplotlib tutorials. You can plot your walk in a million different ways.

DrV
  • 22,637
  • 7
  • 60
  • 72