我通过看麻省理工学院的公开课来学习python,在关于随机行走模拟模型的第17课之后,我写了一段简单的代码,但是没有用,并且显示了这样一个错误:“TypeError:'dunked'object is not callable”。希望有人能帮我找出哪里出了问题。在
from math import*
import random,pylab
class location(object):
def __init__(self,x,y):
self.x=x
self.y=y
def move(self,xc,yc):
return location(self.x+float(xc),self.y+float(yc))
def getCoordinates(self):
return self.x,self.y
def getDistance(self,other):
ox,oy=other.getCoordinates()
x=fabs(other.x-self.x)
y=fabs(other.y-self.y)
return sqrt(x**2+y**2)
class compasspt(object):
possibles=('n','s','e','w')
def __init__(self,pt):
if pt in self.possibles:
self.pt=pt
else:
raise ValueError
def move(self,dist):
if self.pt=='n':return (0,dist)
elif self.pt=='s':return (0,-dist)
elif self.pt=='w':return (dist,0)
elif self.pt=='e':return (-dist,0)
else:raise ValueError
class field(object):
def __init__(self,drunk,location):
self.drunk=drunk
self.location=location
def move(self,cp,dist):
oldLocation=self.location
xc,yc=cp.move(dist) # shadowing
self.location=oldLocation.move(xc,yc)
def getLocation(self):
return self.location
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('the drunk is not in the field.')
for i in range(time):
pt=compasspt(random.choice(compasspt.possibles)) # random walk
field.move(pt,1) # shadowing
def performTrial(time,f):
start=f.getLocation()
distances=[0.0]
for t in range(1,time+1):
f.getDrunk().move(f)
newLocation=f.getLocation()
distance=newLocation.getDistance(start)
distances.append(distance)
return distances
drunk=drunk('Alexander')
for i in range(3):
f=field(drunk,location(0,0))
distances=performTrial(1000,f)
pylab.plot(distances)
pylab.title('Alexander\'s random walk')
pylab.xlabel('Time')
pylab.ylabel('Distance from Origin')
def performSimulation(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=performSimulation(maxTime,numTrials)
for t in range(maxTime+1):
tot=0.0
for distL in distLists:
tot+=distL[t]
means.append(tot/len(distL))
pylab.figure()
pylab.plot(means)
pylab.ylabel('distance')
pylab.xlabel('time')
pylab.title('Average Distance vs. Time('+str(len(distLists))+'trials)')
ansQuest(1000,300)
pylab.show()
我认为你的问题来自于对类名和实例名都使用dunk。。。试着把你的课改成醉酒然后
还有。。。在
^{pr2}$我没有安装pylab,所以我删除了所有这些行,它运行得很干净(尽管没有输出)
我正在和o'Reilly一起学习Python,并试图在作业中回答问题,所以我希望这对你有所帮助。在
相关问题 更多 >
编程相关推荐