粒子群算法的介绍和原理见最优化算法之粒子群算法(PSO)
优化目标函数如下:
该目标函数可改为其他函数,设定的粒子数N=3,迭代次数400次,惯性因子ω=0.9,学习因子c=2,参数可调。
使用C++优雅 实现该算法:
/**
An elegant implementation of pso(Particle Swarm Optimization) using C++11
Author@Larry King
*/
#include <vector>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
// declaration
class pos;
class velocity;
float randomGenerator(float lowerBound, float upperBound);
int MAX_ITER = 400;
const int N = 3;
const float c = 2.0;
const float w = 0.9;
const float maxX1 = 10.0;
const float minX1 = -10.0;
const float maxX2 = 10.0;
const float minX2 = -10.0;
const float minV = -2;
const float maxV = 4;
//float initV;
//pos initPos;
class pos {
public:
friend ostream& operator<<(ostream &os, const pos &p) {
os << "(" << p.x1 << ", " << p.x2 << ")";
return os;
}
pos():x1(0.0), x2(0.0) {}
pos(float x1, float x2):x1(x1), x2(x2) {}
pos(const pos &p):x1(p.x1), x2(p.x2) {} // copy ctr
pos& operator=(const pos &rhs) {
if (this == &rhs) return *this;
this->x1 = rhs.x1;
this->x2 = rhs.x2;
return *this;
}
void setX1(float x1) {this->x1 = x1;}
void setX2(float x2) {this->x2 = x2;}
float getX1() {return x1;}
float getX2() {return x2;}
float getX1() const {return x1;}
float getX2() const {return x2;}
private:
float x1;
float x2;
};
class velocity {
public:
// to see the details of velocity class, download the source code from the link below
private:
float v1;
float v2;
};
float f(const pos &p)
{
return p.getX1() * p.getX1() + p.getX2() * p.getX2();
}
void updateParas(velocity &vOrig, pos &pOrig, const pos &pBi, const pos &gBest)
{
// to see the details of update function, download the source code from the link below
float randomGenerator(float lowerBound, float upperBound)
{
static default_random_engine e(time(0));
static uniform_real_distribution<float> u(lowerBound, upperBound);
// cout << u(e) << endl;
return u(e);
}
int main()
{
vector<velocity> vs(N);
vector<pos> ps(N);
vector<pos> pBest(N);
pos gBest;
for (int i = 0; i != N; ++i) {
vs[i].setV1(randomGenerator(minV, maxV));
vs[i].setV2(randomGenerator(minV, maxV));
ps[i].setX1(randomGenerator(minX1, maxX2));
ps[i].setX2(randomGenerator(minX2, maxX2));
pBest[i] = ps[i];
// cout << "pBest: " << pBest[i] << endl;
}
gBest = pBest[0];
// cout << "gBest: " << gBest << endl;
for (int i = 1; i != N; ++i) {
if (f(pBest[i]) < f(gBest))
gBest = pBest[i]; // initialize the gBest as the minmum pBest
}
while (MAX_ITER-- != 0) {
for (int i = 0; i != N; ++i) {
// to see the details of iterations, download the source code from the link below
}
}
cout << "best global: " << gBest << endl;
cout << "final answer: " << f(gBest) << endl;
}
运行结果如下:
(缺C币,想恰饭)完整代码请到我的CSDN资源下载