麻省理工的随机走动模块,还不错,三天搞懂了,不过懂得不彻底。
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)
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')
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
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)#酒鬼决定移动
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
f = Field(drunk, Location(0, 0))
distances = performTrial(500, f)
pylab.plot(distances)
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
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)')
记录下修改的代码
import math, random, pylab
class Location(object):
#位置类
class CompassPt(object): #方向类
class Field(object): #场地类
class Drunk(object):
def performTrial(time, f):#测试,输入次数,场地对象
##三次测试结果记录
drunk = Drunk('Homer Simpson')
for i in range(5):
pylab.title('Homer\'s Random Walk')
pylab.xlabel('Time')
pylab.ylabel('Distance from Origin')
def performSim(time, numTrials):
def ansQuest(maxTime, numTrials):
ansQuest(500, 300)
pylab.show()
顺便上两张生成的模拟图