Open In App

Random Walk (Implementation in Python)

Last Updated : 12 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A random walk is a mathematical concept used to describe a path made up of a series of random steps. It's also called a stochastic process and can be visualized in spaces like the number line or 2D grids.

One of the simplest examples is a random walk on the number line:

  • Start at 0.
  • Move either +1 or -1 with equal probability at each step.

But random walks go beyond just numbers. They can model:

  • The movement of molecules in gases or liquids
  • How animals forage
  • Stock market price fluctuations
  • Financial outcomes for gamblers

Due to their wide use, random walks are applied in many fields like:

  • Biology
  • Chemistry
  • Physics
  • Computer Science
  • Psychology
  • Economics

In this article, we’ll simulate random walks using Python-both in 1D (one dimension) and 2D (two dimensions). We'll generate random paths and visualize them using plots.

Modules Required:

1. matplotlib: It's an external library that helps you to plot the curve. To install this library type the following code in your cmd. 

pip install matplotlib

2. numpy: It's also an external library in python it helps you to work with arrays and matrices. To install the library type the following code in cmd. 

pip install numpy

3. random: It's a built-in Python library used to generate random points therefore it doesn't requires any installation.

1D Random Walk in Python

This example simulates a one-dimensional random walk. The walker starts at a fixed point and moves left or right based on random chance.

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

# Probability for moving down and up
prob = [0.05, 0.95]

# Start from position 2
start = 2
positions = [start]

rr = np.random.random(1000)
downp = rr < prob[0]
upp = rr > prob[1]

for idownp, iupp in zip(downp, upp):
    down = idownp and positions[-1] > 1
    up = iupp and positions[-1] < 4
    positions.append(positions[-1] - down + up)

# Plotting the random walk
plt.plot(positions)
plt.show()

Output: 

Explanation:

  • The walker starts at position 2.
  • At each step, they may move up, down, or stay put, depending on the generated probabilities.
  • The walk is constrained between position 1 and 4.
  • The final path is visualized using matplotlib.

2D Random Walk in Python

In higher dimensions, random walks become even more interesting. Unlike the simple back-and-forth movement in 1D, a 2D random walk can move in four directions-up, down, left, or right-making the path more complex and visually appealing.

Over many steps, these paths can form patterns that resemble fractals-irregular but self-similar shapes. These patterns can help us study randomness, geometry, and movement in more dynamic environments like gas molecules, animal foraging paths, or stock price changes.

Python
import numpy as np
import pylab
import random

n = 100000  # Number of steps
x = np.zeros(n)
y = np.zeros(n)

for i in range(1, n):
    direction = random.randint(1, 4)
    if direction == 1:
        x[i] = x[i - 1] + 1  # Right
        y[i] = y[i - 1]
    elif direction == 2:
        x[i] = x[i - 1] - 1  # Left
        y[i] = y[i - 1]
    elif direction == 3:
        x[i] = x[i - 1]
        y[i] = y[i - 1] + 1  # Up
    else:
        x[i] = x[i - 1]
        y[i] = y[i - 1] - 1  # Down

# Plot the path
pylab.title(f"2D Random Walk ({n} steps)")
pylab.plot(x, y)
pylab.savefig(f"rand_walk_{n}.png", bbox_inches="tight", dpi=600)
pylab.show()

Output: 

Explanation:

  • We simulate n steps, storing each x and y coordinate in separate arrays.
  • At each step, the walker randomly chooses one of four directions.
  • Over time, the walk produces a fractal-like path that appears random but has underlying structure.

Real-World Applications

  1. In computer networks, random walks can model the number of transmission packets buffered at a server.
  2. In population genetics, a random walk describes the statistical properties of genetic drift.
  3. In image segmentation, random walks are used to determine the labels (i.e., "object" or "background") to associate with each pixel.
  4. In brain research, random walks and reinforced random walks are used to model cascades of neuron firing in the brain.
  5. Random walks have also been used to sample massive online graphs such as online social networks.

Also read: Fractals, Numpy, Matplotlib, Random Module.


Next Article
Article Tags :
Practice Tags :

Similar Reads