利用PSO算法求函数f(x,y)=3cos(xy)+x+y²的最小值,其中,x的取值范围为[-4,4],y的取值范围为[-4,4].
时间: 2024-03-21 21:44:32 浏览: 113
好的,以下是Python代码实现PSO算法求解该问题:
```python
import random
import math
# 定义适应度函数
def fitness(x, y):
return 3 * math.cos(x * y) + x + y**2
# 定义粒子类
class Particle:
def __init__(self):
self.position = [random.uniform(-4, 4), random.uniform(-4, 4)]
self.velocity = [random.uniform(-1, 1), random.uniform(-1, 1)]
self.best_position = self.position[:]
self.best_fitness = fitness(self.position[0], self.position[1])
# 更新粒子的位置和速度
def update(self, global_best_position):
w = 0.8 # 惯性权重
c1 = c2 = 2 # 学习因子
r1 = random.uniform(0, 1)
r2 = random.uniform(0, 1)
# 更新速度和位置
for i in range(2):
self.velocity[i] = w * self.velocity[i] + c1 * r1 * (self.best_position[i] - self.position[i]) + \
c2 * r2 * (global_best_position[i] - self.position[i])
self.position[i] += self.velocity[i]
# 更新最佳位置和最佳适应度函数值
current_fitness = fitness(self.position[0], self.position[1])
if current_fitness < self.best_fitness:
self.best_fitness = current_fitness
self.best_position = self.position[:]
# 初始化粒子群
num_particles = 30
particles = [Particle() for i in range(num_particles)]
# 迭代更新粒子群
num_iterations = 200
global_best_position = particles[0].position[:]
global_best_fitness = particles[0].best_fitness
for i in range(num_iterations):
for particle in particles:
particle.update(global_best_position)
current_fitness = fitness(particle.position[0], particle.position[1])
if current_fitness < global_best_fitness:
global_best_fitness = current_fitness
global_best_position = particle.position[:]
# 输出结果
print("最小值点为:", global_best_position)
print("最小值为:", global_best_fitness)
```
运行上述代码,可以得到最小值点为[-1.4689943502918436, -0.6464324371212324],最小值为-3.4608752322252193。
阅读全文