You can download this code by clicking the button below.
This code is now available for download.
This function performs a random walk process and visualizes the result using the matplotlib library.
Technology Stack : matplotlib, random
Code Type : Custom function
Code Difficulty : Intermediate
def random_walk(num_steps, step_length):
import random
import matplotlib.pyplot as plt
x, y = 0, 0
x_positions, y_positions = [x], [y]
for _ in range(num_steps):
direction = random.choice(['up', 'down', 'left', 'right'])
if direction == 'up':
y += step_length
elif direction == 'down':
y -= step_length
elif direction == 'left':
x -= step_length
elif direction == 'right':
x += step_length
x_positions.append(x)
y_positions.append(y)
plt.figure(figsize=(10, 10))
plt.plot(x_positions, y_positions, marker='o')
plt.title('Random Walk')
plt.xlabel('X Position')
plt.ylabel('Y Position')
plt.grid(True)
plt.show()
return x, y