转 python 随机走动的模拟

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

 

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

 
记录下修改的代码
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/jsgit

 

 


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)github


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)web

 


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


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’)dom

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库了,安装方式这里就很少讲,方法有不少,给个参考的post

  本文将在已安装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)


随机走动的模拟
相关文章
相关标签/搜索