用c语言写粒子群优化算法
时间: 2023-08-18 15:09:19 浏览: 92
粒子群优化算法 (Particle Swarm Optimization, PSO) 是一种基于群体智能的优化算法,可以应用于多种问题的求解。下面是用 C 语言实现 PSO 算法的简单示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define SWARM_SIZE 20
#define MAX_ITERATIONS 100
#define DIMENSIONS 2
#define INF 1e9
double rand_double(double a, double b) {
return a + (b - a) * ((double) rand() / RAND_MAX);
}
double objective_function(double x[DIMENSIONS]) {
// TODO: 定义要优化的目标函数
return pow(x[0], 2) + pow(x[1], 2);
}
void pso(double swarm[SWARM_SIZE][DIMENSIONS], double pbest[SWARM_SIZE][DIMENSIONS], double gbest[DIMENSIONS]) {
double w = 0.7; // 惯性权重
double c1 = 1.4; // 自我认知因子
double c2 = 1.4; // 社会经验因子
double vmax = 0.1; // 最大速度
double v[SWARM_SIZE][DIMENSIONS] = {0}; // 粒子速度
// 初始化 pbest 和 gbest
for (int i = 0; i < SWARM_SIZE; i++) {
double *x = swarm[i];
double f = objective_function(x);
if (f < objective_function(pbest[i])) {
for (int j = 0; j < DIMENSIONS; j++) {
pbest[i][j] = x[j];
}
}
if (f < objective_function(gbest)) {
for (int j = 0; j < DIMENSIONS; j++) {
gbest[j] = x[j];
}
}
}
// 迭代优化
for (int t = 0; t < MAX_ITERATIONS; t++) {
for (int i = 0; i < SWARM_SIZE; i++) {
double *x = swarm[i];
double *v_i = v[i];
double *pbest_i = pbest[i];
for (int j = 0; j < DIMENSIONS; j++) {
double r1 = rand_double(0, 1);
double r2 = rand_double(0, 1);
v_i[j] = w * v_i[j] + c1 * r1 * (pbest_i[j] - x[j]) + c2 * r2 * (gbest[j] - x[j]);
v_i[j] = fmin(v_i[j], vmax);
v_i[j] = fmax(v_i[j], -vmax);
x[j] += v_i[j];
}
double f = objective_function(x);
if (f < objective_function(pbest[i])) {
for (int j = 0; j < DIMENSIONS; j++) {
pbest[i][j] = x[j];
}
}
if (f < objective_function(gbest)) {
for (int j = 0; j < DIMENSIONS; j++) {
gbest[j] = x[j];
}
}
}
}
}
int main() {
srand(time(NULL));
double swarm[SWARM_SIZE][DIMENSIONS]; // 粒子群
double pbest[SWARM_SIZE][DIMENSIONS]; // 每个粒子的历史最优解
double gbest[DIMENSIONS] = {INF}; // 全局最优解
// 初始化粒子群
for (int i = 0; i < SWARM_SIZE; i++) {
for (int j = 0; j < DIMENSIONS; j++) {
swarm[i][j] = rand_double(-5, 5);
pbest[i][j] = swarm[i][j];
}
}
// 运行 PSO 算法
pso(swarm, pbest, gbest);
// 输出结果
printf("Global best solution: ");
for (int j = 0; j < DIMENSIONS; j++) {
printf("%lf ", gbest[j]);
}
printf("\n");
printf("Objective function value: %lf\n", objective_function(gbest));
return 0;
}
```
在 main 函数中,我们首先初始化粒子群,然后调用 pso 函数运行 PSO 算法,最后输出全局最优解和目标函数的值。
PSO 算法的核心在于粒子的速度和位置的更新,具体的公式可以参考上面的代码。需要注意的是,为了避免速度过大,我们限制了粒子的最大速度 vmax。此外,我们还使用了惯性权重 w、自我认知因子 c1 和社会经验因子 c2 来控制粒子的搜索行为。
在实际应用中,需要根据具体的问题调整 PSO 算法的参数,以获得更好的优化效果。
阅读全文
相关推荐















