用C语言写一段粒子群优化算法
时间: 2023-05-23 11:02:45 浏览: 84
粒子群优化算法
以下是一段用C语言实现的粒子群优化算法的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define DIMENSION 10 // 维度
#define NUM_PARTICLES 20 // 粒子数
#define MAX_ITERATIONS 50 // 迭代次数
#define C1 2.0 // 加速系数1
#define C2 2.0 // 加速系数2
#define W 1.0 // 惯性权重
typedef struct {
double position[DIMENSION]; // 位置
double velocity[DIMENSION]; // 速度
double pbest[DIMENSION]; // 个体最优解
double fitness; // 适应度
} Particle;
double objective_function(double *x)
{
// 目标函数
double sum = 0.0;
for (int i = 0; i < DIMENSION; i++) {
sum += x[i] * x[i];
}
return sum;
}
void initialize_particles(Particle *particles)
{
// 初始化粒子
for (int i = 0; i < NUM_PARTICLES; i++) {
for (int j = 0; j < DIMENSION; j++) {
particles[i].position[j] = (double)rand() / RAND_MAX * 10.0 - 5.0;
particles[i].velocity[j] = (double)rand() / RAND_MAX * 2.0 - 1.0;
particles[i].pbest[j] = particles[i].position[j];
}
particles[i].fitness = objective_function(particles[i].position);
}
}
void update_particle(Particle *particle, double *gbest)
{
// 更新粒子位置和速度
for (int i = 0; i < DIMENSION; i++) {
double r1 = (double)rand() / RAND_MAX;
double r2 = (double)rand() / RAND_MAX;
particle->velocity[i] = W * particle->velocity[i] +
C1 * r1 * (particle->pbest[i] - particle->position[i]) +
C2 * r2 * (*gbest - particle->position[i]);
particle->position[i] += particle->velocity[i];
}
double fitness = objective_function(particle->position);
if (fitness < particle->fitness) {
// 更新个体最优解
particle->fitness = fitness;
for (int i = 0; i < DIMENSION; i++) {
particle->pbest[i] = particle->position[i];
}
}
}
void update_gbest(Particle *particles, double *gbest)
{
// 更新全局最优解
double best_fitness = particles[0].fitness;
int best_index = 0;
for (int i = 1; i < NUM_PARTICLES; i++) {
if (particles[i].fitness < best_fitness) {
best_fitness = particles[i].fitness;
best_index = i;
}
}
if (best_fitness < *gbest) {
*gbest = best_fitness;
for (int i = 0; i < DIMENSION; i++) {
gbest[i] = particles[best_index].position[i];
}
}
}
void optimize()
{
Particle particles[NUM_PARTICLES];
double gbest[DIMENSION];
double best_fitness;
initialize_particles(particles);
best_fitness = particles[0].fitness;
for (int i = 1; i < NUM_PARTICLES; i++) {
if (particles[i].fitness < best_fitness) {
best_fitness = particles[i].fitness;
}
}
for (int i = 0; i < DIMENSION; i++) {
gbest[i] = particles[0].position[i];
}
for (int iter = 0; iter < MAX_ITERATIONS; iter++) {
for (int i = 0; i < NUM_PARTICLES; i++) {
update_particle(&particles[i], gbest);
}
update_gbest(particles, gbest);
printf("iteration %d: best fitness = %lf\n", iter + 1, gbest);
}
}
int main()
{
optimize();
return 0;
}
```
该算法用于求解多维优化问题,在上述代码中,目标函数为 $f(x) = \sum_{i=1}^{10} x_i^2$,算法通过不断跟踪粒子的位置和速度,逐步优化得到最优解,本代码中设定了粒子数、迭代次数、加速系数等参数,可以根据具体问题进行调整。
阅读全文