练习 15-3:分子运动 —— 修改rw_visual.py,将其中的ax.scatter()替换为ax.plot()。为模拟花粉在水滴表面的运动路径,向plt.plot()传递rw.x_values和rw.y_values,并指定实参linewidth。请使用5000个点而不是50000个点。
原rw_visual.py
import matplotlib.pyplot as plt
from random_walk import RondomWalk
# 只要程序处于活动状态,就不断地模拟随机漫步
while True:
# 创建一个RandomWalk实例
rw = RondomWalk(50_000)
rw.fill_walk()
# 将所有的点都绘制出来
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(8,5), dpi=128)
point_numbers = range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.hsv, edgecolors='none', s=1)
# 突出起点和终点
ax.scatter(0, 0, c='green', edgecolors='none', s=100)
ax.scatter(rw.x_values[-1], rw.y_values[-1], c='black', edgecolors='none', s=100)
# 隐藏坐标轴
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False) # 将坐标轴地可见性设置为False
plt.show()
keeping = input("Make another walk? (y/n):")
if keeping == 'n':
break
修改后的rw_visual.py
# 分子运动:修改rw.visual.py,将其中的ax.scatter()替换为ax.plot()。
# 为模拟花粉在水滴表面的运动路径,向plt.plot()传递rw.x_values,并指定实参linewidth。使用5000个点。
import matplotlib.pyplot as plt
from random_walk import RondomWalk
# 只要程序处于活动状态,就不断地模拟随机漫步
while True:
# 创建一个RandomWalk实例
rw = RondomWalk()
rw.fill_walk()
# 将所有的点都绘制出来
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(8, 5), dpi=128)
point_numbers = range(rw.num_points)
ax.plot(rw.x_values, rw.y_values, 'b')
# 突出起点和终点
ax.plot(0, 0, 'o-g', linewidth=10)
ax.plot(rw.x_values[-1], rw.y_values[-1], 'o-r', linewidth=10)
# 隐藏坐标轴
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False) # 将坐标轴地可见性设置为False
plt.show()
keeping = input("Make another walk? (y/n):")
if keeping == 'n':
break
random_walk.py
from random import choice
class RondomWalk:
""" 一个生成随机漫步数据的类 """
def __init__(self, num_points=5000):
""" 初始化随机漫步的属性 """
self.num_points = num_points
# 所有随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
""" 计算随机漫步包含的所有点 """
# 不断漫步,直到列表达到指定的长度
while len(self.x_values) < 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
# 计算下一个点的x值和y值
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
效果图:
练习 15-4:改进的随机漫步 —— 在类RandomWalk中,x_step和y_step是根据相同的条件生成的:从列表[-1, 1]中随机选择方向,并从列表[0, 1, 2, 3, 4]中随机选择距离。请修改这些列表中的值,看看对随机漫步路径有何影响。尝试使用更长的距离选择列表(如1~8),或者将-1从x或y方向列表中删除。
# 练习 15-4
# 改进的随机漫步: 在类RandomWalk中,x_step和y_step是根据相同的条件生成的:从列表[-1, 1]中随机选择方向,
# 并从列表[0, 1, 2, 3, 4]中随机选择距离。请修改这些列表中的值,看看对随机漫步路径有何影响。
# 尝试使用更长的距离选择列表(如1~8),或者将-1从x或y方向列表中删除。
from random import choice
class RondomWalk:
""" 一个生成随机漫步数据的类 """
def __init__(self, num_points=5000):
""" 初始化随机漫步的属性 """
self.num_points = num_points
# 所有随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
""" 计算随机漫步包含的所有点 """
# 不断漫步,直到列表达到指定的长度
while len(self.x_values) < self.num_points:
# 决定前进方向以及沿这个方向前进的距离
x_direction = choice([1, -1])
# x_distance = choice([0, 1, 2, 3, 4])
x_distance = choice(range(0, 9))
x_step = x_direction * x_distance
# y_direction = choice([1, -1])
y_direction = 1
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# 拒绝原地踏步
if x_step == 0 and y_step == 0:
continue
# 计算下一个点的x值和y值
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
改进后的效果图:
改进前的图:
练习 15-5:重构 —— 方法fill_walk()很长。请新建一个名为get_step()的方法,用于确定每次漫步的距离和方向,并计算每一步。然后,在fill_walk()中调用get_step()两次:
x_step = self.get_step()
y_step = self.get_step()
通过这样的重构,可缩小方法fill_walk(),让它阅读和理解起来更容易。
# 练习15-5: 重构:将fill_walk拆分,新建一个名为get_step()的方法
from random import choice
class RondomWalk:
""" 一个生成随机漫步数据的类 """
def __init__(self, num_points=5000):
""" 初始化随机漫步的属性 """
self.num_points = num_points
# 所有随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
""" 计算随机漫步包含的所有点 """
# 不断漫步,直到列表达到指定的长度
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
# 拒绝原地踏步
if x_step == 0 and y_step == 0:
continue
# 计算下一个点的x值和y值
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
def get_step(self):
""" 决定前进方向以及沿这个方向前进的距离 """
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
self.step = direction * distance
return self.step
关于matplotlib.pyplot的一些基础操作,可以查看