Random walks are a fascinating and simple concept to model in Python, offering endless opportunities for exploration. Here’s how you can get started with a basic implementation and gradually enhance it for more fun.
Basic 1D Random Walk
A one-dimensional random walk is the simplest version. Each step is either forward (+1) or backward (-1) along a line.
import random
import matplotlib.pyplot as plt
def random_walk_1d(steps):
position = 0
walk = [position]
for _ in range(steps):
step = random.choice([-1, 1])
position += step
walk.append(position)
return walk
# Generate and plot a 1D random walk
steps = 100
walk = random_walk_1d(steps)
plt.figure(figsize=(10, 6))
plt.plot(walk)
plt.title("1D Random Walk")
plt.xlabel("Steps")
plt.ylabel("Position")
plt.show()
2D Random Walk
In a 2D walk, the walker can move up, down, left, or right.
def random_walk_2d(steps):
x, y = 0, 0
walk = [(x, y)]
for _ in range(steps):
dx, dy = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
x += dx
y += dy
walk.append((x, y))
return walk
# Generate and plot a 2D random walk
steps = 200
walk = random_walk_2d(steps)
x_coords, y_coords = zip(*walk)
plt.figure(figsize=(8, 8))
plt.plot(x_coords, y_coords, marker="o", markersize=3)
plt.title("2D Random Walk")
plt.xlabel("X Position")
plt.ylabel("Y Position")
plt.axis("equal")
plt.show()
3D Random Walk
In 3D, the walker can move along the x, y, or z axes.
from mpl_toolkits.mplot3d import Axes3D
def random_walk_3d(steps):
x, y, z = 0, 0, 0
walk = [(x, y, z)]
for _ in range(steps):
dx, dy, dz = random.choice([(1, 0, 0), (-1, 0, 0),
(0, 1, 0), (0, -1, 0),
(0, 0, 1), (0, 0, -1)])
x += dx
y += dy
z += dz
walk.append((x, y, z))
return walk
# Generate and plot a 3D random walk
steps = 300
walk = random_walk_3d(steps)
x_coords, y_coords, z_coords = zip(*walk)
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection="3d")
ax.plot(x_coords, y_coords, z_coords)
ax.set_title("3D Random Walk")
plt.show()
Ideas for Exploration
- Boundaries: Simulate walks confined within a grid or sphere.
- Biased Walks: Add probabilities to prefer certain directions.
- Obstacles: Introduce barriers the walker must avoid.
- Multiple Walkers: Model multiple entities walking and possibly interacting.
- Physics-Based Walks: Incorporate inertia or forces for realistic modeling.
- Fractal Patterns: Create self-similar patterns using random walks.
Would you like to dive into any of these ideas or explore enhancements?