How to Simulate Random Walks with NumPy

How to Simulate Random Walks with NumPy

Random walks represent a fundamental mathematical concept with profound implications across various scientific domains, from financial modeling to particle physics. These stochastic processes, characterized by a succession of random steps, provide a framework for modeling phenomena where each state depends probabilistically on the previous one.

Understanding random walks through NumPy simulations offers practitioners a powerful computational approach to explore these mathematical constructs while gaining intuitive insights into their behavioral patterns and statistical properties.

Let’s learn to perform random walks with NumPy.

Preparation

As we need the NumPy library, we must install it in our environment. We also would install the Matplotlib for the visualization.

pip install numpy matplotlib

With the NumPy library installed, we will learn more about how to use NumPy to simulate Random Walks.
 

Random Walks Simulation with NumPy

Random walks simulation is a mathematical model for simulating random steps over time that can be shown as a path. The random walk properties are independent of the previous step, and the walk can be in any direction.

Let’s set up the code for a random walk simkulation. We will start with the one-dimensional random walk, in which the position increases or decreases.

def random_walk_1d(steps):
    walk = np.random.choice([-1, 1], size=steps)
    position = np.cumsum(walk)
    return position

We would randomly select the steps (1 or -1), and let’s see the position of the steps in the end.

For 1000 steps, the random walk simulation looks like below.

import matplotlib.pyplot as plt
steps = 1000
position = random_walk_1d(steps)
plt.plot(position)
plt.title('1D Random Walk')
plt.xlabel('Steps')
plt.ylabel('Position')
plt.show()

How to Simulate Random Walks with NumPy

We can also have two-dimensional random walks. This would simulate random walks in both horizontal and vertical (x and y) directions.

steps = 1000
x_position = random_walk_1d(steps)
y_position = random_walk_1d(steps)
plt.scatter(x_position, y_position)
plt.title('2D Random Walk')
plt.xlabel('X Position')
plt.ylabel('Y Position')
plt.show()

How to Simulate Random Walks with NumPy

We can also simulate multiple random walks simultaneously.

steps = 1000
n_walks = 10
steps = np.random.choice([-1, 1], size=(n_walks, steps))
positions = np.cumsum(steps, axis=1)
for i in range(n_walks):
    plt.plot(positions[i], label=f'Walk {i+1}')
plt.title('Multiple 1D Random Walks')
plt.xlabel('Steps')
plt.ylabel('Position')
plt.legend()
plt.show()

How to Simulate Random Walks with NumPy

If you are able to master random walk simulation, you will have the power to simulate any use cases you need.

Additional Resources

Leave a Reply

Your email address will not be published. Required fields are marked *