V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fengyi0524
V2EX  ›  Python

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

  •  
  •   fengyi0524 · 2019-11-08 20:39:59 +08:00 · 1937 次点击
    这是一个创建于 1601 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在学习《 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 的直线,请问为什么没有生成随机数据点呢?
    fengyi0524
        1
    fengyi0524  
    OP
       2019-11-08 20:54:20 +08:00
    对不起,已经发现问题了,请不要回复!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3235 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:08 · PVG 20:08 · LAX 05:08 · JFK 08:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.