写一段粒子群算法代码
时间: 2023-11-17 13:03:46 浏览: 24
以下是一个简单的粒子群算法的Python代码示例:
```python
import random
# 定义目标函数,这里以 Rosenbrock 函数为例
def rosenbrock(x, y):
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
# 定义粒子类
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.vx = random.uniform(-1, 1)
self.vy = random.uniform(-1, 1)
self.best_x = x
self.best_y = y
self.best_score = rosenbrock(x, y)
def update_velocity(self, global_best_x, global_best_y, w, c1, c2):
r1 = random.random()
r2 = random.random()
self.vx = w * self.vx + c1 * r1 * (self.best_x - self.x) + c2 * r2 * (global_best_x - self.x)
self.vy = w * self.vy + c1 * r1 * (self.best_y - self.y) + c2 * r2 * (global_best_y - self.y)
def update_position(self):
self.x += self.vx
self.y += self.vy
score = rosenbrock(self.x, self.y)
if score < self.best_score:
self.best_x = self.x
self.best_y = self.y
self.best_score = score
# 初始化粒子群
num_particles = 20
particles = [Particle(random.uniform(-5, 5), random.uniform(-5, 5)) for _ in range(num_particles)]
# 迭代优化
num_iterations = 100
global_best_score = float('inf')
global_best_x = None
global_best_y = None
w = 0.5
c1 = 1
c2 = 1
for i in range(num_iterations):
for particle in particles:
particle.update_velocity(global_best_x, global_best_y, w, c1, c2)
particle.update_position()
if particle.best_score < global_best_score:
global_best_score = particle.best_score
global_best_x = particle.best_x
global_best_y = particle.best_y
print("Optimal solution: f({:.6f}, {:.6f}) = {:.6f}".format(global_best_x, global_best_y, global_best_score))
```