3 隨機漫步
3.1 RandomWalk類
先創建一個生成並保存隨機數的類,初始化屬性:
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
隨機漫步從0開始:
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_value = [0]
self.y_value = [0]
創建生成隨機數並保存的方法:
from random import choice
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_value = [0]
self.y_value = [0]
def fill_walk(self):
while len(self.x_value) <= self.num_points:
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
if x_step == 0 and y_step == 0:
continue
next_x = self.x_value[-1] + x_step
next_y = self.y_value[-1] + y_step
self.x_value.append(next_x)
self.y_value.append(next_y)
導入choice隨機選擇走的方向和步數
如果原地踏步,則重新隨機。
繪製漫步圖:
import matplotlib.pyplot as plt
from randomwalk import RandomWalk
while True:
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_value, rw.y_value, s=10)
plt.show()
keep_running = input('Make another walk?(y/n):')
if keep_running == 'n':
break
導入剛纔的類,使用生成的數據繪圖,
rw.fill_walk()生成漫步包含的點、
最後輸入n結束,否則重新生成隨機漫步圖