设计求解下列优化问题的PSO算法:minf(x)=x1**2+x2**2+25*(sin(x1)**2+sin(x2)**2),-3<=xi<=3,
时间: 2023-12-23 13:03:17 浏览: 96
以下是使用粒子群优化算法(PSO)求解优化问题的代码示例:
```python
import numpy as np
def objective_function(x):
return x[0]**2 + x[1]**2 + 25*(np.sin(x[0])**2 + np.sin(x[1])**2)
def pso_algorithm():
# 参数设置
num_particles = 50 # 粒子数量
num_dimensions = 2 # 维度数量
max_iterations = 100 # 最大迭代次数
inertia_weight = 0.7 # 惯性权重
cognitive_weight = 1.4 # 认知权重
social_weight = 1.4 # 社会权重
# 初始化粒子位置和速度
particles_position = np.random.uniform(low=-3, high=3, size=(num_particles, num_dimensions))
particles_velocity = np.zeros((num_particles, num_dimensions))
# 初始化全局最优解和对应的适应度值
global_best_position = np.zeros(num_dimensions)
global_best_fitness = float('inf')
# 迭代优化
for iteration in range(max_iterations):
for i in range(num_particles):
# 计算粒子的适应度值
fitness = objective_function(particles_position[i])
# 更新个体最优解
if fitness < global_best_fitness:
global_best_fitness = fitness
global_best_position = particles_position[i]
# 更新粒子速度和位置
particles_velocity[i] = (inertia_weight * particles_velocity[i] +
cognitive_weight * np.random.rand() * (particles_position[i] - particles_position[i]) +
social_weight * np.random.rand() * (global_best_position - particles_position[i]))
particles_position[i] += particles_velocity[i]
# 限制粒子位置在范围内
particles_position[i] = np.clip(particles_position[i], -3, 3)
return global_best_position, global_best_fitness
# 调用PSO算法求解优化问题
best_position, best_fitness = pso_algorithm()
print("最优解:", best_position)
print("最优解对应的适应度值:", best_fitness)
```
阅读全文