粒子群算法c++代码
时间: 2023-12-06 12:36:33 浏览: 30
以下是一个简单的粒子群算法的C++代码示例:
```c++
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MAX_ITERATIONS = 1000; // 最大迭代次数
const int POPULATION_SIZE = 20; // 种群大小
const int DIMENSIONS = 2; // 搜索空间的维度
const double C1 = 2.0; // 学习因子1
const double C2 = 2.0; // 学习因子2
const double W = 0.7; // 惯性权重
// 粒子结构体
struct Particle {
double position[DIMENSIONS]; // 粒子的位置
double velocity[DIMENSIONS]; // 粒子的速度
double fitness; // 粒子的适应度
double bestPosition[DIMENSIONS]; // 粒子历史最佳位置
double bestFitness; // 粒子历史最佳适应度
};
// 计算粒子的适应度
double evaluateFitness(double position[]) {
double x = position[0];
double y = position[1];
return sin(x) * cos(y) - (x / (y * y + 1));
}
// 初始化粒子群
void initialize(Particle population[]) {
srand(time(NULL));
for (int i = 0; i < POPULATION_SIZE; i++) {
for (int j = 0; j < DIMENSIONS; j++) {
population[i].position[j] = (double)rand() / RAND_MAX * 10 - 5; // 随机初始化位置
population[i].velocity[j] = (double)rand() / RAND_MAX * 2 - 1; // 随机初始化速度
}
population[i].fitness = evaluateFitness(population[i].position); // 计算适应度
for (int j = 0; j < DIMENSIONS; j++) {
population[i].bestPosition[j] = population[i].position[j]; // 初始化历史最佳位置
}
population[i].bestFitness = population[i].fitness; // 初始化历史最佳适应度
}
}
// 更新粒子的速度和位置
void update(Particle &particle, double globalBestPosition[]) {
for (int i = 0; i < DIMENSIONS; i++) {
double r1 = (double)rand() / RAND_MAX;
double r2 = (double)rand() / RAND_MAX;
particle.velocity[i] = W * particle.velocity[i] + C1 * r1 * (particle.bestPosition[i] - particle.position[i]) + C2 * r2 * (globalBestPosition[i] - particle.position[i]); // 更新速度
particle.position[i] += particle.velocity[i]; // 更新位置
}
particle.fitness = evaluateFitness(particle.position); // 计算适应度
if (particle.fitness < particle.bestFitness) { // 更新历史最佳位置和适应度
for (int i = 0; i < DIMENSIONS; i++) {
particle.bestPosition[i] = particle.position[i];
}
particle.bestFitness = particle.fitness;
}
}
// 执行粒子群算法
void execute() {
Particle population[POPULATION_SIZE];
double globalBestPosition[DIMENSIONS];
double globalBestFitness = INFINITY;
initialize(population);
for (int i = 0; i < MAX_ITERATIONS; i++) {
for (int j = 0; j < POPULATION_SIZE; j++) {
if (population[j].fitness < globalBestFitness) { // 更新全局最佳位置和适应度
globalBestFitness = population[j].fitness;
for (int k = 0; k < DIMENSIONS; k++) {
globalBestPosition[k] = population[j].bestPosition[k];
}
}
update(population[j], globalBestPosition); // 更新粒子的速度和位置
}
}
cout << "Global best position: (" << globalBestPosition[0] << ", " << globalBestPosition[1] << ")" << endl;
cout << "Global best fitness: " << globalBestFitness << endl;
}
int main() {
execute();
return 0;
}
```