📄 pso.cpp
字号:
// PSO.cpp
//
#include <stdafx.h>
#include "Particle.h"
#include "ParSwarm.h"
class MyPSO : public CParSwarm
{
public:
MyPSO(int d, int n):CParSwarm(d, n){}; //构造函数,给出微粒维数和微粒个数
double GetFit(CParticle &p) //适合度计算方法,必须定义
{
//函数:Schaffer's F6
double f6;
f6 = 1+0.001*(p.Pos[0]*p.Pos[0]+p.Pos[1]*p.Pos[1]);
f6 *= f6;
f6 = 0.5-(sin(sqrt(p.Pos[0]*p.Pos[0]+p.Pos[1]*p.Pos[1]))*
sin(sqrt(p.Pos[0]*p.Pos[0]+p.Pos[1]*p.Pos[1]))-0.5)/f6;
return f6;
}
};
bool MyCom(double fit, double *op, double**,int)
{
static long sn=1;
cout<<"\rNo="<<sn++<<"\tFun="<<fit;
for(int i=0; i<2; i++)
cout<<"\tX("<<i<<")="<<op[i];
return true;
}
const int PNum = 50; //微粒个数
const int PDim = 3; //微粒维数
double Xup[] = {100, 100}; //自变量上界
double Xdown[] = {-100, -100}; //自变量下界
void main()
{
MyPSO pso(PDim, PNum); //生成微粒群实例
pso.SetPosUp(Xup); //设置自变量上界
pso.SetPosDown(Xdown); //设置自变量下界
pso.SetVmax(0.2); //设置最大速度
pso.SetCom(MyCom); //设置通讯函数
cout<<"\nRun Now:\n";
pso.Run(2000); //运行微粒群
cout<<"\nThe Result is:\t"<<pso.GetBest(Xup)<<"\n"; //输出结果
pso.Run(0.999); //运行微粒群
cout<<"\nThe Result is:\t"<<pso.GetBest(Xup)<<"\n"; //输出结果
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -