📄 pso.cpp
字号:
// pso.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "PSO.h"
#include <iostream.h>
#include <math.h>
//派生自己的PSO类
class MyPSO : public PSO
{
public:
MyPSO(int d, int n):PSO(d, n){}; //构造函数,给出微粒维数和微粒个数
double GetFit(PARTICLE &p) //适合度计算方法,必须定义
{
//函数:Schaffer's F6
// double f6;
// f6 = 1+0.001*(p.X[0]*p.X[0]+p.X[1]*p.X[1]);
// f6 *= f6;
// f6 = 0.5-(sin(sqrt(p.X[0]*p.X[0]+p.X[1]*p.X[1]))*
// sin(sqrt(p.X[0]*p.X[0]+p.X[1]*p.X[1]))-0.5)/f6;
// return f6;
//函数:Rastrigrin
// double f=0;
// for (int i=0;i<10;i++)
// {
// f+=p.X[i]*p.X[i]-10*cos(2*3.1415926*p.X[i])+10;
// }
// return -1*f;
double f=0;
for (int i=0;i<10;i++)
{
f+=p.X[i]*p.X[i]-10*cos(2*3.1415926*p.X[i])+10;
}
return -1*f;
}
};
//定义通讯函数
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 = 20; //微粒个数
//const int PDim = 2; //微粒维数
// double Xup[] = {100, 100}; //自变量上界
// double Xdown[] = {-100, -100}; //自变量下界
const int PNum = 20; //微粒个数
const int PDim = 10; //微粒维数
double Xup[] = {5.12, 5.12, 5.12, 5.12, 5.12, 5.12, 5.12, 5.12, 5.12, 5.12}; //自变量上界
double Xdown[] = {-5.12, -5.12, -5.12, -5.12, -5.12, -5.12, -5.12, -5.12, -5.12, -5.12}; //自变量下界
//主程序
void main()
{
MyPSO pso(PDim, PNum); //生成微粒群实例
pso.SetXup(Xup); //设置自变量上界
pso.SetXdown(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 + -