Random Walk
Here, we will study a few examples of Random Walks.
1-Dimensional​
where , and is random variable which takes value or with equal probability.
import numpy as np
import random
import imageio
import os
import matplotlib.pyplot as plt
random.seed(2609)
# Initialize an empty numpy array
y = np.array([])
# Set initial value of y
y_0 = 0
y = np.append(y,y_0)
# Number of iterations for the loop
n_iterations = 1000
# Loop to generate y_t values
for t in range(1, n_iterations):
# Generate epsilon_t which takes value 1 and -1 with equal probability
epsilon_t = random.choice([-1, 1])
# Calculate y_t
y_t = y[t-1] + epsilon_t
# Append y_t to the array
y = np.append(y, y_t)
# Create frames for each step
x=np.arange(0,n_iterations)
filenames = []
for i in range(1, n_iterations + 1):
plt.figure(figsize=(8, 6))
plt.plot(x[:i], y[:i], color='blue')
plt.plot(x[i-1], y[i-1], color='r',marker='o')
plt.xlim(min(x)-10, max(x)+10)
plt.ylim(min(y)-10, max(y)+10)
plt.title(f'Step {i}/{n_iterations}')
plt.xlabel("t")
plt.ylabel("$y_t$")
plt.grid()
# Save frame
filename = f'frames/step_{i}.png'
filenames.append(filename)
plt.savefig(filename)
plt.close()
# Create GIF
with imageio.get_writer('random_walk.gif', mode='I', duration=0.1) as writer:
for filename in filenames:
image = imageio.imread(filename)
writer.append_data(image)
# Clean up the frames
for filename in filenames:
os.remove(filename)
2-Dimensional​
where , and is random variable which takes value or with equal probability.
import matplotlib.pyplot as plt
import random
import imageio
import os
random.seed(2609)
# Function to create a 2D random walk
def random_walk_2d(n_steps):
x, y = 0, 0
walk_x, walk_y = [x], [y]
for i in range(n_steps):
dx, dy = random.choice([(0,1), (0,-1), (1,0), (-1,0)])
x, y = x + dx, y + dy
walk_x.append(x)
walk_y.append(y)
return walk_x, walk_y
# Generate a random walk
n_steps = 1000
walk_x, walk_y = random_walk_2d(n_steps)
# Create directory for frames
os.makedirs('frames', exist_ok=True)
# Create frames for each step
filenames = []
for i in range(1, n_steps + 1):
plt.figure(figsize=(8, 6))
plt.plot(walk_x[:i], walk_y[:i], color='blue')
plt.plot(walk_x[i-1], walk_y[i-1], color='r',marker='o')
plt.xlim(min(walk_x)-1, max(walk_x)+1)
plt.ylim(min(walk_y)-1, max(walk_y)+1)
plt.title(f'Step {i}/{n_steps}')
# Save frame
filename = f'frames/step_{i}.png'
filenames.append(filename)
plt.savefig(filename)
plt.close()
# Create GIF
with imageio.get_writer('random_walk.gif', mode='I', duration=0.1) as writer:
for filename in filenames:
image = imageio.imread(filename)
writer.append_data(image)
# Clean up the frames
for filename in filenames:
os.remove(filename)