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结束,否则重新生成随机漫步图