MIT的python课的第十七课,一个简单的随机走动模型

qq_32874397 2016-03-16 03:36:09
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):

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

if pt in self.possibles: self.pt = pt

else: raise ValueError('in CompassPt.__init__')

def move(self, 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):

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

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)

newLoc = f.getLoc()

distance = newLoc.getDist(start)

distances.append(distance)

return distances

drunk = Drunk('Homer Simpson')

for i in range(3):

f = Field(drunk, Location(0, 0))

distances = performTrial(500, f)

pylab.plot(distances)
print distances

pylab.title('Homer\'s Random Walk')

pylab.xlabel('Time')

pylab.ylabel('Distance from Origin')

不太了解第93行的函数是怎么调用的,而且为什么不用继承啊
...全文
123 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

37,737

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧