一个可视化随机漫步数据的问题

2019-11-08 20:39:59 +08:00
 fengyi0524
在学习《 python 编程 从入门到实践》第 5 章的内容,要求创建一个 RandomWalk ()类,用于生成 5000 个随机坐标点,并将生成点可视化。下面是我照着书敲的代码:

1.RandomWalk 类的代码

from random import choice

class RandomWalk():
#初始化储存生成点坐标的列表,一个储存 x 坐标,另一个储存 y 坐标
def __init__(self,num_points = 5000):
self.num_points = num_points
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_distance*x_direction

y_direction = choice([1,-1])
y_distance = choice([0,1,2,3,4])
y_step = x_distance*x_direction

if x_step==0 and y_step==0:
continue
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step

self.x_values.append(next_x)
self.y_values.append(next_y)


2.生成数据点并可视化的代码:

import matplotlib.pyplot as plt

from random_walk import RandomWalk
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()

结果生成了一条斜率 1 的直线,请问为什么没有生成随机数据点呢?
1971 次点击
所在节点    Python
1 条回复
fengyi0524
2019-11-08 20:54:20 +08:00
对不起,已经发现问题了,请不要回复!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/617744

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX