import matplotlib.pyplot as plt
from random import choice
class RandWalk:
# A class generating random walk
def __init__(self, num_points=5000):
# Initialize random walk properties
self.num_points = num_points
# All random walks begin with (0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
# Calculate all the points included in the random walk
# Keep walking , Until the list reaches the specified length
while len(self.x_values) < self.num_points:
# Determine the direction and the distance to go in that direction
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# Refuse to step in place
if x_step == 0 and y_step == 0:
continue
# Calculate the... Of the next point x Values and y value
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
# Simulate multiple random walks
while True:
rw = RandWalk(50000)
rw.fill_walk()
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(15, 9)) # In inches
point_number = range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values, c=point_number, cmap=plt.cm.Blues, edgecolors='none', s=1)
# Highlight start and end points
ax.scatter(0, 0, c='green', edgecolors='none', s=100)
ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
# Hide axis
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
keep_running = input('Make another walk?(y/n):')
if keep_running == 'n':
break