1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| from random import choice, randint import matplotlib.pyplot as plt class RandomWalk(): def __init__(self, walk_nums=100): self.walk_nums = walk_nums self.x_values = [0] self.y_values = [0] def move(self): while len(self.x_values) < self.walk_nums: x_direction = choice([-1, 1]) x_distance = randint(0, 10) x_step = x_direction * x_distance y_direction = choice([-1, 1]) y_distance = randint(0, 10) y_step = y_direction * y_distance if x_step == 0 and y_step == 0: continue self.x_values.append(self.x_values[-1] + x_step) self.y_values.append(self.y_values[-1] + y_step)
randomwalk = RandomWalk(10000) randomwalk.move() point_numbers = range(randomwalk.walk_nums) plt.scatter(randomwalk.x_values, randomwalk.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=15)
plt.scatter(randomwalk.x_values[0], randomwalk.y_values[0], c='red', s=100) plt.scatter(randomwalk.x_values[-1], randomwalk.y_values[-1], c='red', s=100)
plt.axes().get_xaxis().set_visible(True) plt.axes().get_yaxis().set_visible(True)
plt.show()
|