时间:2021-03-29来源:www.pcxitongcheng.com作者:电脑系统城
注:需要python的内置函数random,不需安装,直接导入即可
import random
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
- * - coding: utf - 8 - * - import matplotlib.pyplot as plt import random position = 0 #设置初始位置 walk = [] #保存位置 steps = 500 #设置步数为500步 for i in range (steps): step = 1 if random.randint( 0 , 1 ) else - 1 #如果随机值等于0则step为1,反之为0 position + = step #改变位置(正,负) walk.append(position) fig = plt.figure() #生成窗口 ax = fig.add_subplot( 211 ) #返回一个axes对象,里面的参数abc表示在一个figure窗口中,有a行b列个小窗口,然后本次plot在第c个窗口中 ax.plot(walk) ax = fig.add_subplot( 223 ) ax.plot(walk) ax = fig.add_subplot( 224 ) ax.plot(walk) plt.show() #print walk#打印每一次的累积步数 |
运行如下:
需要用到numpy库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#-*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np nwalks = 8 nsteps = 500 draws = np.random.randint( 0 , 2 , size = (nwalks, nsteps)) # 0 or 1 steps = np.where(draws > 0 , 1 , - 1 ) #每一次的步长 walks = steps.cumsum( 1 ) #累积步数 fig = plt.figure() ax = fig.add_subplot( 111 ) for i in range (nwalks): ax.plot(walks[i]) plt.show() |
到此这篇关于Python实现随机游走的详细解释的文章就介绍到这了
2023-03-17
python flask项目打包成docker镜像发布的过程2023-03-17
python调试模块ipdb详解2023-03-17
python使用openai生成图像的超详细教程python cron定时任务触发接口自动化巡检 apscheduler报错:Run time of job …… next run at: ……)” was missed by misfire_grace_time参数 找到任务超时的根本原因...
2023-03-15