# Random Walk Program in Python

Hello there, my fellow programmer. Well, well, well, today we are going to learn about **“Random Walk implementation in Python”.**

Well, let me tell you this for sure this is a great walk into a basic topic.

## Random Walk:

A Random Walk can be simply explained as a simulation to proceed to the next step in a randomized manner such that we get a different path of propagation each time. Such a simulation can somewhat describe the motion such as Brownian motion of particles, stock ticker movement, living cell movement in a substrate, etc.

Random walks can be 1D, 2D, 3D,…., etc. with each increase in dimension the motion explained becomes complex but a simulation like this helps a user to have a great visualization and understanding.

#### 1-D Random Walk::

For a 1D random walk, we consider that the motion is going to be in just two directions i.e. either up or down, or left or right.

Such a situation can be implemented as:

import numpy as np import matplotlib.pyplot as plt def Randomwalk1D(n): #n here is the no. of steps that we require x = 0 y = 0 xposition = [0] #starting from origin (0,0) yposition = [0] for i in range (1,n+1): step = np.random.uniform(0,1) if step < 0.5: # if step is less than 0.5 we move up x += 1 y += 1 #moving up in u direction if step > 0.5: # if step is greater than 0.5 we move down x += 1 y += -1 #moving down in y direction xposition.append(x) yposition.append(y) return [xposition,yposition] Randwalk = Randomwalk1D(1000) #creating an object for the Randomwalk1D class and passing value of n as 100 plt.plot(Randwalk[0],Randwalk[1],'r-', label = "Randwalk1D") # 'r-' makes the color of the path red plt.title("1-D Random Walks") plt.show()

**In the code:**

We randomly assign a number to the “step” variable between 0 and 1 with the help of “random.uniform()” function. Then a threshold of 0.5 is set to determine the next step of the point(you can change the threshold to a value you like). And hence we get a plot of a random path on the 1-D plane.

**OUTPUT:**

In the output above, we can see that the point(or particle) under consideration moves up and down randomly. Starting from the origin(or the zero point) the point goes up and then down randomly taking 1000 steps through the journey. And hence, a 1-D random walk is generated.

#### 2-D Random Walk::

A 2-D Random Walk is propagated in a 2-D(x-y) plane. It consists of motion in 4 directions i.e. all of Up-Down-Left-Right.

To visualize the two-dimensional case, we can think about a person in the imagination who is walking randomly around a city. The city is effectively infinite and also arranged in a square grid of sidewalks. At every intersection, the person randomly chooses one of the four possible routes (including the one originally traveled from)

Such a situation can be implemented as::

import numpy as np import pylab import random n = 1000 #n is the number of steps(increase in the value of n increses the compelxity of graph) x = np.zeros(n) # x and y are arrays which store the coordinates of the position y = np.zeros(n) direction=["NORTH","SOUTH","EAST","WEST"] # Assuming the four directions of movement. for i in range(1, n): step = random.choice(direction) #Randomly choosing the direction of movement. if step == "EAST": #updating the direction with respect to the direction of motion choosen. x[i] = x[i - 1] + 1 y[i] = y[i - 1] elif step == "WEST": x[i] = x[i - 1] - 1 y[i] = y[i - 1] elif step == "NORTH": x[i] = x[i - 1] y[i] = y[i - 1] + 1 else: x[i] = x[i - 1] y[i] = y[i - 1] - 1 pylab.title("Random Walk 2-D") pylab.plot(x, y) #plotting the walk. pylab.show()

**In the Code:**

In the code above we assign a variable “direction” to four directions of movements i.e. North, South, West, East. Then, we randomly assign the direction of movement to the “step” variable with the help of “random. choice” function. According to the direction selected we update the x and y coordinates of the particles and hence the particle moves randomly.

**OUTPUT:**

Random walk with 1000 steps:

The output above shows the movement of a point(or particle) over a 2-D plane in a random manner. According to the randomly chosen direction, the particle can move in four directions, i.e. North, South, East and, West over the course of 1000 steps. If the choice is North then x-coordinate increase by 1, then when it’s South then x coordinate decreases by 1, if East, then y coordinate increases by 1 and, if West then y coordinate decreases by 1. Hence, the particle completes the random walk.

Random walk with 5000 steps:

#### 3-D Random Walk::

A 3-D Random Walk is propagated in a 3-D(x-y-z) plane. Movement of a gas particle in 3-D space can be represented very well with the help of a 3D random walk.

Such a situation can be implemented as::

%matplotlib inline import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D #for plotting the 3-D plot. N =1500 R = (np.random.rand(N)*6).astype("int") #Randomly intializing the steps x = np.zeros(N) y = np.zeros(N) z = np.zeros(N) x[ R==0 ] = -1; x[ R==1 ] = 1 #assigning the axis for each variable to use y[ R==2 ] = -1; y[ R==3 ] = 1 z[ R==4 ] = -1; z[ R==5 ] = 1 x = np.cumsum(x) #The cumsum() function is used to get cumulative sum over a DataFrame or Series axis i.e. it sums the steps across for eachaxis of the plane. y = np.cumsum(y) z = np.cumsum(z) plt.figure() ax = plt.subplot(1,1,1, projection='3d') ax.plot(x, y, z,alpha=0.9) #alpha sets the darkness of the path. ax.scatter(x[-1],y[-1],z[-1]) plt.show()

**In the code:**

In the code, we have defined three axes over which the particle moves by 1 step according to the randomly chosen “R” value. And hence the point completes the motion over 1500 steps.

**OUTPUT:**

In the output above, the point(or particle) starts from the origin(0,0,0) and moves by one step in the 6 direction on a 3-D space randomly and hence generates a random path for in the space.

And, there you have it “Random walk in Python”.

I hope, you enjoyed the post.

Such a helpful post! This is really interesting.