python随机漫步
2024-10-19 07:37:41
randomwalk.py代码
from random import choice
class RandomWalk():
def __init__(self,points=5000):
self.points=points
self.x=[0]
self.y=[0]
def random_walk(self):
while len(self.x)<self.points: #当x的长度小于5000,也就是没有生成5000点之前都继续循环生成点
x_direction=choice([1,-1]) #通过choice选择-1和1控制方向
x_distance=choice([0,1,2,3,4]) #通过choice选择列表里面的值控制x移动距离
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:#如果x,y移动都为0,我们就跳出本次操作,不加这个没有移动的点,然后继续循环生成存在移动的点再添加到x列表里面
continue
next_x=self.x[-1]+x_step #通过计算得到新点的x值
next_y=self.y[-1]+y_step
self.x.append(next_x)#通过append把新的x值添加到列表x中
self.y.append(next_y)
绘图的代码
import matplotlib.pyplot as plt
from randomwalk import RandomWalk #导入类
m=[2,4]
n=[3,2]
while True:
random=RandomWalk(5000)#创建实例
random.random_walk() #实例调用类方法
plt.figure(dpi=80,figsize=(8,6)) #调整图像查看器的尺寸,dpi是像素大小,默认80
plt.scatter(random.x,random.y,c=random.x,s=1,edgecolor='none',cmap=plt.cm.Blues) # 以x的集合生成循序绘制颜色渐变散点
plt.scatter(random.x,random.y,c=random.y,s=1,edgecolor='none',cmap=plt.cm.Blues) # 以y的集合生成顺序绘制颜色渐变散点
plt.scatter(0,0,c='red',s=40,edgecolor='none') # 重绘起点,通过设置和其它点的不同属性突出起点位置
plt.scatter(random.x[-1],random.y[-1],c='yellow',s=40,edgecolor='none') #重绘终点,通过设置和其它点的不同属性突出终点位置
plt.title('title',fontsize=10)
plt.xlabel('variable',fontsize=10)
plt.ylabel('value',fontsize=10)
plt.tick_params(axis='both',labelsize=10)
#plt.axis([0,5,0,5])
#plt.savefig('imag.png',bbox_inches='tight')
plt.axes().get_xaxis().set_visible(False) #隐藏x坐标轴
plt.axes().get_yaxis().set_visible(False) #隐藏y坐标轴
plt.show()
check=input("你是否要继续查看随机漫步(y/n)") #通过输入函数在关闭图像查看器的时候提示是否重新生成随机漫步
if check=='n':
break
最新文章
- 《分布式事务解决之道》沙龙ppt共享
- js 对cookie 的操作
- 图片在ie8浏览器打不开,其他浏览器都可以打开的问题
- WEBAPP开发技巧(手机网站开发注意事项)
- 51nod 1434 理解lcm
- Lua 栈中元素的位置
- K-Anonymous Sequence(poj 3709)
- directsound 应用实例
- psycopg2接口的基本用法
- java concurrency: daemon线程
- ZUFE OJ 2289 God Wang II
- 2017年9月19日 JavaScript语法操作
- 原生JS实现弹幕效果
- POJ 1860 Currency Exchange(如何Bellman-Ford算法判断图中是否存在正环)
- Java Heap Dump On OutOfMemoryError
- Spring框架学习09——基于AspectJ的AOP开发
- linux du 查看文件及文件夹大小
- sqlserver收缩数据库
- JVM 监控工具 jstack 和 jvisualvm 的使用
- [leetcode tree]96. Unique Binary Search Trees
热门文章
- 5Spring动态代理开发小结
- 变量覆盖-高级篇(动态覆盖,extract综合)
- [bug] Maven:No valid Maven installation found.maven
- Linux下script命令录制、回放和共享终端操作script -t 2>; timing.log -a output.session # 开始录制
- Linux 部署 iSCSI 客户端配置(Windows)
- 11.14 mii-tool:管理网络接口的状态
- Linux中级之负载均衡(lvs,nginx,haproxy)、中间件
- 技术干货 | 源码解析 Github 上 14.1k Star 的 RocketMQ
- java命令的本质逻辑揭秘
- DHCP与DHCP中继