logo4 Evolution is progress—                          
progress is creativity.        
vline

Random walk

This page mainly shows a random walk example implemented in python with numpy and pylab. The theory behind random walk can be learned from Wikipedia.

def set_figure(fig):    
   import numpy as np
   import matplotlib.pyplot as plt

   def rand_walkn(X,sigma=1,mu=0):
       Y = np.empty(X.size)
       for i in range(X.size):
           previous = Y[i-1] if i != 0 else 0
           Y[i] = sigma * np.random.randn() + previous
       return Y
    
   def rand_walk(X):
       Y = np.empty(X.size)
       for i in range(X.size):
           previous = Y[i-1] if i != 0 else 0
           Y[i] = previous + 1 if np.random.rand() > 0.5 else previous - 1
       return Y

   ax=fig.add_subplot(1,1,1)
   X = np.arange(100)

   ax.plot(X,rand_walkn(X),'g-',X,rand_walk(X),'b--')
   ax.set_xlabel("Number of points")
   ax.set_ylabel("Walking distance")
   title = u"Random walk gaussian vs. uniform"
   ax.set_title(title)
   ax.legend(('gaussian','uniform'), loc='upper left')
Random walk in python with numpy and pylab

Tags: Theory


Categories: Mathematics

 
   

(c) Mato Nagel, Weißwasser 2004-2013, Disclaimer