求解一个简单的函数
def function(x):
y=(x-1)**2+2
return y
实现
import random
particle_num = 10
position = [random.uniform(0, 5) for i in range(particle_num)]
velocity = [random.uniform(0, 1) for i in range(particle_num)]
particle_best = [0.0 for i in range(particle_num)]
global_best = 0.0
def update(position,velocity,particle_best,global_best,iter_num,W,n1,n2,max_velocity):
"""
状态更新
"""
for j in range(iter_num):
for i in range(len(position)):
if function(position[i]) < function(particle_best[i]):
particle_best[i] = position[i]
if function(position[i]) < function(global_best):
global_best = position[i]
velocity[i] = W * velocity[i] + n1 * random.random() * (particle_best[i] - position[i]) \
+ n2 * random.random() * (global_best - position[i])
if velocity[i] > max_velocity:
velocity[i] = max_velocity
elif velocity[i] < -max_velocity:
velocity[i] = -max_velocity
position[i] = position[i] + velocity[i]
return global_best
W = 1
n1 = 2
n2 = 2
max_velocity = 0.05
iter_num = 100
result=update(position,velocity,particle_best,global_best,iter_num,W,n1,n2,max_velocity)
print(result)