【发布时间】:2011-05-25 15:06:13
【问题描述】:
我正在写一小段 python 作为家庭作业,但我没有让它运行!我没有那么多 Python 经验,但我知道很多 Java。 我正在尝试实现粒子群优化算法,这就是我所拥有的:
class Particle:
def __init__(self,domain,ID):
self.ID = ID
self.gbest = None
self.velocity = []
self.current = []
self.pbest = []
for x in range(len(domain)):
self.current.append(random.randint(domain[x][0],domain[x][1]))
self.velocity.append(random.randint(domain[x][0],domain[x][1]))
self.pbestx = self.current
def updateVelocity():
for x in range(0,len(self.velocity)):
self.velocity[x] = 2*random.random()*(self.pbestx[x]-self.current[x]) + 2 * random.random()*(self.gbest[x]-self.current[x])
def updatePosition():
for x in range(0,len(self.current)):
self.current[x] = self.current[x] + self.velocity[x]
def updatePbest():
if costf(self.current) < costf(self.best):
self.best = self.current
def psoOptimize(domain,costf,noOfParticles=20, noOfRuns=30):
particles = []
for i in range(noOfParticles):
particle = Particle(domain,i)
particles.append(particle)
for i in range(noOfRuns):
Globalgbest = []
cost = 9999999999999999999
for i in particles:
if costf(i.pbest) < cost:
cost = costf(i.pbest)
Globalgbest = i.pbest
for particle in particles:
particle.updateVelocity()
particle.updatePosition()
particle.updatePbest(costf)
particle.gbest = Globalgbest
return determineGbest(particles,costf)
现在,我认为这不应该起作用。 但是,当我运行它时,我得到了这个错误:
“TypeError:updateVelocity() 不接受任何参数(给定 1 个)”
我不明白!我没有给它任何论据!
感谢您的帮助,
莱纳斯
【问题讨论】:
-
我的源代码中没有空行,这就是本网站的格式。
-
低质量问题:由于混合的空格和制表符,许多不相关的代码具有许多语法错误。重复更好的问题stackoverflow.com/q/6614123/448474
-
这是一个非常合理的问题!对于 Python 新手来说,产生的错误很常见。这是一个非常令人困惑的问题!您可以很容易地看到程序员在没有任何参数的情况下调用了“particle.updateVelocity()”,这就是应该如何调用它的想法。它是可以解决的,但不使用标准文档!
-
Python 不是自然编译的,而是解释的。 CPython 是解释器,而不是编译器。
-
@J. C. Rocamonde:不,CPython 是a compiler and a bytecode interpreter。
标签: python object methods arguments