https://blog.csdn.net/python2014/article/details/21231971

麻省理工的随机走动模块,还不错,三天搞懂了,不过懂得不彻底。

 
记录下修改的代码
import math, random, pylab
class Location(object):  #位置类
    def __init__(self, x, y): #给定坐标,完成初始化
        self.x = float(x)
        self.y = float(y)
    def move(self, xc, yc):#移动,XY方向各变化
        return Location(self.x+float(xc), self.y+float(yc))
    def getCoords(self): #响应,返回当前坐标
        return self.x, self.y
    def getDist(self, other): #响应,计算与给定点的距离。
        ox, oy = other.getCoords()
        xDist = self.x - ox
        yDist = self.y - oy
        return math.sqrt(xDist**2 + yDist**2)
    
class CompassPt(object): #方向类
    possibles = ('N', 'S', 'E', 'W')
    def __init__(self, pt): #PT:方向,只给从NSEW中选择。
        if pt in self.possibles: self.pt = pt
        else: raise ValueError('in CompassPt.__init__')
    def move(self, dist): #移动方向,N,X方向不变,Y增加DIST
        if self.pt == 'N': return (0, dist)
        elif self.pt == 'S': return (0, -dist)
        elif self.pt == 'E': return (dist, 0)
        elif self.pt == 'W': return (-dist, 0)
        else: raise ValueError('in CompassPt.move')
class Field(object): #场地类
    def __init__(self, drunk, loc): #酒鬼名字和起点坐标
        self.drunk = drunk
        self.loc = loc #给定的位置
       
    def move(self, cp, dist): #cp是个对象,待查
        oldLoc = self.loc
        xc, yc = cp.move(dist)
        self.loc = oldLoc.move(xc, yc)
    def getLoc(self):
        return self.loc
    def getDrunk(self):
        return self.drunk
class Drunk(object):
    def __init__(self, name):
        self.name = name
    def move(self, field, time = 1):#好多的move()
        if field.getDrunk() != self:
            raise ValueError('Drunk.move called with drunk not in field')
        for i in range(time):#酒鬼决定方向
            pt = CompassPt(random.choice(CompassPt.possibles))
            field.move(pt, 1)#酒鬼决定移动
def performTrial(time, f):#测试,输入次数,场地对象
    start = f.getLoc() #超点位置
    distances = [0.0]   #起点距离
    for t in range(1, time + 1):
        f.getDrunk().move(f)#从field获得酒鬼对象,再获得他的 move
        newLoc = f.getLoc()#移动后获得再位置
        distance = newLoc.getDist(start)#计算距离,
        distances.append(distance) #将距离追加到列表
    return distances
 
##三次测试结果记录
drunk = Drunk('Homer Simpson')
for i in range(5):
    f = Field(drunk, Location(0, 0))
    distances = performTrial(500, f)
    pylab.plot(distances)
pylab.title('Homer\'s Random Walk')
pylab.xlabel('Time')
pylab.ylabel('Distance from Origin')
 
 
def performSim(time, numTrials):
    distLists = []
    for trial in range(numTrials):
        d = Drunk('Drunk' + str(trial))
        f = Field(d, Location(0, 0))
        distances = performTrial(time, f)
        distLists.append(distances)
    return distLists
def ansQuest(maxTime, numTrials):
    means = []
    distLists = performSim(maxTime, numTrials)
    for t in range(maxTime + 1):
        tot = 0.0
        for distL in distLists:
            tot += distL[t]
        means.append(tot/len(distLists))
    pylab.figure()
    pylab.plot(means)
    pylab.ylabel('distance')
    pylab.xlabel('time')
    pylab.title('Average Distance vs. Time (' + str(len(distLists)) + ' trials)')
ansQuest(500, 300)
pylab.show()
顺便上两张生成的模拟图
 
 
 
 
 
 
###########
 
class oddField(Field):
def move(self,cp,dist):
Field.move(self,cp,dist)
newLoc = self.loc
x,y = newLoc.getCoords()
if math.fabs(x) == math.fabs(y):
self.loc = Location(0,0)

class usualDrunk(Drunk):
def move(self,field,dist=1):
cp = random.choice(CompassPt.possibles)
Drunk.move(self,field,CompassPt(cp),dist)

class coldDrunk(Drunk):
def move(self,field,dist=1):
cp = random.choice(CompassPt.possibles)
if cp == S:
Drunk.move(self,field,CompassPt(cp),2*dist)
else:
Drunk.move(self,field,CompassPt(cp),dist)

class ewDrunk(Drunk):
def move(self,field,dist=1):
cp = random.choice(CompassPt.possibles)
while cp != E and cp!=W:
cp = random.choice(CompassPt.possibles)
Drunk.move(self,field,CompassPt(cp),dist)

 
 
 
 
####python 代码格式化
 

http://tool.oschina.net/codeformat/js

class Drunk(object);
def __init__(self, name);
self.name = name def move(self, field, cp, dist = 1);
if field.getDrunk().name != self.name;
raise ValueError('Drunk.move called with drunk not in field')
for i in range(dist);
field.move(cp, 1)

class ColdDrunk(Drunk);
def move(self, field, dist = 1);
cp = random.choice(CompassPt.possibles)
if cp == 'S';
Drunk.move(self, field, CompassPt(cp), 2 * dist)
else;
Drunk.move(self, field, CompassPt(cp), dist)

class UsualDrunk(Drunk);
def move(self, field, dist = 1);
cp = random.choice(CompassPt.possibles)
Drunk.move(self, field, CompassPt(cp), dist)

class EWDrunk(Drunk);
def move(self, field, time = 1);
cp = random.choice(CompassPt.possibles)
while cp != 'E'and cp != 'W';
cp = random.choice(CompassPt.possibles)
Drunk.move(self, field, CompassPt(cp), time) def performSim(time, numTrials, drunkType);
distLists = []
for trial in range(numTrials);
d = drunkType('Drunk' + str(trial))…def ansQuest(maxTime, numTrials, drunkType, title);
means = [] distLists = performSim(maxTime, numTrials, drunkType)…ansQuest(500, 100, UsualDrunk, ‘UsualDrunk’)

class oddField(Field);
def isChute(self);
x,
y = self.loc.getCoords() return abs(x) - abs(y) == 0 def move(self, cp, dist);
Field.move(self, cp, dist) if self.isChute();
self.loc = Location(0, 0)""

 
###########2
https://www.cnblogs.com/webary/p/5813855.html
 

【python笔记】使用matplotlib,pylab进行python绘图

 

一提到python绘图,matplotlib是不得不提的python最著名的绘图库,它里面包含了类似matlab的一整套绘图的API。因此,作为想要学习python绘图的童鞋们就得在自己的python环境中安装matplotlib库了,安装方式这里就不多讲,方法有很多,给个参考的

  本文将在已安装matplotlib的环境中教新手如何快速使用其中的接口进行绘图操作,并展现一个非常直观的绘图例子,以及控制绘图中的一些细节的方法。

  既然绘图要用matplotlib的包,并且我们也已经安装了,那么首先肯定是要引入这个包了: import matplotlib.pyplot as plt

  当然也可以替换为引入pylab(是matplotlib的一个子包,非常适合于进行交互式绘图,本文将以这个为例): import pylab as pl

  接下来,就是对具体数据进行绘图了。比如我们要绘制一条y=x^2的曲线,可这样写代码:

x = range(10)  # 横轴的数据
y = [i*i for i in x] # 纵轴的数据
pl.plot(x, y) # 调用pylab的plot函数绘制曲线
pl.show() # 显示绘制出的图

  执行之后就可以看到绘制出来的图了:

  

  可以看到,要显示一个图非常简单,只要有了两个list作为输入数据,先后调用plot和show函数就可以了。一定要记得只有调用了show之后才会显示出来!只有plot是不行的!

  在实际运用中,可能这样一条简单粗暴的线可能并不是我们想要的最好的结果,比如,想要在图形上显示原始数据点,很简单,只要在plot函数中加上一个参数即可: pl.plot(x, y, 'ob-') # 显示数据点,并用蓝色(blue)实现绘制该图形

  这个参数用法比较灵活,可以从下面的值中组合选择:

颜色(color 简写为 c):
蓝色: 'b' (blue)
绿色: 'g' (green)
红色: 'r' (red)
蓝绿色(墨绿色): 'c' (cyan)
红紫色(洋红): 'm' (magenta)
黄色: 'y' (yellow)
黑色: 'k' (black)
白色: 'w' (white) 线型(linestyle 简写为 ls):
实线: '-'
虚线: '--'
虚点线: '-.'
点线: ':'
点: '.' 点型(标记marker):
像素: ','
圆形: 'o'
上三角: '^'
下三角: 'v'
左三角: '<'
右三角: '>'
方形: 's'
加号: '+'
叉形: 'x'
棱形: 'D'
细棱形: 'd'
三脚架朝下: '1'(像'丫')
三脚架朝上: '2'
三脚架朝左: '3'
三脚架朝右: '4'
六角形: 'h'
旋转六角形: 'H'
五角形: 'p'
垂直线: '|'
水平线: '_'

  线是调好了,可是还想加上横纵坐标的说明呢?也很简单,在调用show函数之前添加如下代码:

pl.xlabel(u"我是横轴")
pl.ylabel(u"我是纵轴")

  效果如下:

  

  这里一定要记住,传递的字符串一定要是Unicode编码,如果是直接传入字符串,形式如 u'这里是要写的字符串' 即可。

  现在就直观多了吧,终于像一个正常的图了,不过,还想再在图里加个图例该咋办?也不难,继续给plot传参数:

pl.plot(x, y, 'ob-', label=u'y=x^2曲线图')  # 加上label参数添加图例
pl.legend() # 让图例生效

  这里也是一样,label字符串参数务必加上u''声明为unicode编码,否则图例将会添加失败。效果图如下:

  

  oh,看到图像上面光秃秃的,就好想给它加个标题: pl.title(u'图像标题') # 字符串也需要是unicode编码

  有时候,我们的数据可能分布并没有这么集中,比如我们想要对项目中的某些数据进行绘图观察时发现,大量数据聚集在0附近,而少量很大的数据会导致图像显示效果很不好,比如:  

x = range(10)+[100]
y = [i*i for i in x]
pl.plot(x, y, 'ob-', label=u'y=x^2曲线图')

  

  这时,我们想要限制需要显示的坐标范围:

pl.xlim(-1, 11)  # 限定横轴的范围
pl.ylim(-1, 110) # 限定纵轴的范围

  再上效果图:

  


  好了,到这里plot的常用绘图用法就讲完了,另外,如果需要在一幅图中显示多条线,可以在show函数调用前继续调用plot函数,传入需要绘制的数据和图形显示要求。

  matplotlib是个非常好用的库,不管是对于需要写论文画图,还是数据调研中看数据相关性,都是一个得力助手。写这篇文章的背景是我之前在项目中也使用这个做了一个特征与结果之间的相关性调研中使用到了绘图,就学习了一下,下面是对真实数据进行屏蔽改写之后的一个很像的示意图(感兴趣的可以到我github中看源码,本文的完整代码及注释也可在本链接只中找到):

    


  本文简要介绍了下python绘图入门的一些用法,如有不对之处,欢迎大家指正。我也是不久前才开始真正使用python,这个强大而方便的语言会让我们能更快地实现自己的想法,大家有比较好的python资料也欢迎留言,共同学习,谢谢!

  转载请注明出处:使用matplotlib,pylab进行python绘图(http://www.cnblogs.com/webary/p/5813855.html)

转 python 随机走动的模拟的更多相关文章

  1. Python使用mechanize模拟浏览器

    Python使用mechanize模拟浏览器 之前我使用自带的urllib2模拟浏览器去进行訪问网页等操作,非常多站点都会出错误,还会返回乱码.之后使用了 mechanize模拟浏览器,这些情况都没出 ...

  2. 测试开发Python培训:模拟登录新浪微博-技术篇

    测试开发Python培训:模拟登录新浪微博-技术篇   一般一个初学者项目的起点就是登陆功能的自动化,而面临的项目不同实现的技术难度是不一样的,poptest在做测试开发培训中更加关注技术难点,掌握技 ...

  3. Python爬虫之模拟登录微信wechat

    不知何时,微信已经成为我们不可缺少的一部分了,我们的社交圈.关注的新闻或是公众号.还有个人信息或是隐私都被绑定在了一起.既然它这么重要,如果我们可以利用爬虫模拟登录,是不是就意味着我们可以获取这些信息 ...

  4. Python实现网站模拟登陆

    一.实验简介 1.1 基本介绍 本实验中我们将通过分析登陆流程并使用 Python 实现模拟登陆到一个实验提供的网站,在实验过程中将学习并实践 Python 的网络编程,Python 实现模拟登陆的方 ...

  5. 利用Python中的mock库对Python代码进行模拟测试

    这篇文章主要介绍了利用Python中的mock库对Python代码进行模拟测试,mock库自从Python3.3依赖成为了Python的内置库,本文也等于介绍了该库的用法,需要的朋友可以参考下     ...

  6. python入门:模拟简单用户登录(自写)

    #!/usr/bin/env python # -*- coding: utf-8 -*- #模拟简单用户登录(自写) import getpass a = raw_input("Pleas ...

  7. python初体验 ——>>> 模拟体育竞技

    python初体验 ——>>> 模拟体育竞技 一.排球训练营 1. 简介: 模拟不同的两个队伍进行排球的模拟比赛. 2. 模拟原理: 通过输入各自的能力值(Ⅰ),模拟比赛的进行( P ...

  8. Python爬虫-百度模拟登录(二)

    上一篇-Python爬虫-百度模拟登录(一) 接上一篇的继续 参数 codestring codestring jxG9506c1811b44e2fd0220153643013f7e6b1898075 ...

  9. Python+Selenium自动化-模拟键盘操作

    Python+Selenium自动化-模拟键盘操作   0.导入键盘类Keys() selenium中的Keys()类提供了大部分的键盘操作方法:通过send_keys()方法来模拟键盘上的按键. # ...

随机推荐

  1. linux文件夹删除、创建

    一.删除文件夹 rm -rf ./html2imag 二.创建文件夹 mkdir html2image

  2. mono-3.0.2安装指南

     install-mono.sh.zip   mono-3.0.2安装指南.pdf   mod_mono.diff.zip mono-3.0.2安装指南 一见 2012/12/27 目录 1. 前言 ...

  3. [转载]Redhat Enterprise 6.1 如何使用免费的CentOS的yum源

    Redhat Enterprise 6.1 如何使用免费的CentOS的yum源 graybull posted @ 2013年2月18日 22:29 in Unix/Linux with tags  ...

  4. Servlet视频-开发第一个java web(最简单的java web程序)(二)

    web项目有目录结构要求 WEB-INFO 文件夹 是一个Servlet规范,必须要这么命名,在换个文件夹里面如果创建一个jsp文件是不能直接访问的,在WEB-INfO文件夹之外创建的jsp可以直接访 ...

  5. Zinterstore 命令

    先来看一下这个命令的定义: Redis Zinterstore 命令计算给定的一个或多个有序集的交集,其中给定 key 的数量必须以 numkeys 参数指定,并将该交集(结果集)储存到 destin ...

  6. Date的转换输出

    public static void main(String[] args) { // TODO Auto-generated method stub //20131111怎么格式化成2013年11月 ...

  7. c#设计模式-单例模式【转】

    单例模式三种写法: 第一种最简单,但没有考虑线程安全,在多线程时可能会出问题 public class Singleton { private static Singleton _instance = ...

  8. Rabbitmq——实现消费端限流 --NACK重回队列

    如果是高并发下,rabbitmq服务器上收到成千上万条消息,那么当打开消费端时,这些消息必定喷涌而来,导致消费端消费不过来甚至挂掉都有可能. 在非自动确认的模式下,可以采用限流模式,rabbitmq ...

  9. java读取 500M 以上文件,java读取大文件

    java 读取txt,java读取大文件 设置缓存大小BUFFER_SIZE ,Config.tempdatafile是文件地址 来源博客http://yijianfengvip.blog.163.c ...

  10. DP【洛谷P4290】 [HAOI2008]玩具取名

    P4290 [HAOI2008]玩具取名 某人有一套玩具,并想法给玩具命名.首先他选择WING四个字母中的任意一个字母作为玩具的基本名字.然后他会根据自己的喜好,将名字中任意一个字母用"WI ...