在python中可视化二维随机游走 [英] Visualizing a 2d random walk in python

查看:946
本文介绍了在python中可视化二维随机游走的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在2d中随机行走,并绘制2d行走. 我已经可以散步了,但情节并不是我想要的. 可以在python中看到走路吗?或者只是在每个点上添加标签,以便您知道哪个点排在第一位,第二个点排在第二位,等等.

I'm trying to make a random walk in 2d, and plot the 2d walk. I've been able to make the walk, but the plot is not exactly what I wanted. Would it be possible to see the walk live in python ? Or just add a label to every point so that you know which point came first and which point came second etc. ?

import numpy as np
import matplotlib.pyplot as plt
import random
def randomWalkb(length):
    steps = []
    x,y = 0,0
    walkx,walky = [x],[y]
    for i in range(length):

        new = random.randint(1,4)
        if new == 1:
            x += 1
        elif new == 2:
            y += 1
        elif new ==3 :
            x += -1
        else :
            y += -1
        walkx.append(x)
        walky.append(y)
    return [walkx,walky]

walk = randomWalkb(25)
print walk
plt.plot(walk[0],walk[1],'b+', label= 'Random walk')
plt.axis([-10,10,-10,10])
plt.show()

编辑我错误地复制了自己的代码,如果您安装了正确的软件包,则它正在编译.

Edit I copied my own code wrong, now it is compiling if you have the right packages installed.

推荐答案

内置的 turtle 模块可用于以可感知的速率绘制路径.

The built-in turtle module could be used to draw the path at a perceptible rate.

import turtle

turtle.speed('slowest')

walk = randomWalkb(25)

for x, y in zip(*walk):
    #multiply by 10, since 1 pixel differences are hard to see
    turtle.goto(x*10,y*10)

turtle.exitonclick()

抽样结果:

这篇关于在python中可视化二维随机游走的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆