📄 pso.cpp
字号:
// pso.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "PSO.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;
}
};
//定义通讯函数
bool MyCom(const PARTICLE *op,const int Index)
{
static long sn=1;
printf("%d,%f\t",sn++,op[Index].FitBest);
for(int i=0; i<2; i++)
printf("%d,%f\t",i,op[Index].XBest);
return true;
}
//声明相关数据
const int PNum = 20; //微粒个数
const int PDim = 2; //微粒维数
double Xup[] = {100, 100}; //自变量上界
double Xdown[] = {-100, -100}; //自变量下界
const int MAXG=10000; //最大允许进化代数
//主程序
void main()
{
MyPSO pso(PDim, PNum); //生成微粒群实例
pso.SetXup(Xup); //设置自变量上界
pso.SetXdown(Xdown); //设置自变量下界
double *tempV = new double[PDim];
pso.SetVmax(0.2,tempV); //设置最大速度
pso.SetCom(MyCom); //设置通讯函数
printf("\nRun Now:\n");
// pso.Run(MAXG,56); //运行微粒群
// printf("\nThe Result is: %f\t\n",pso.GetBest(Xup)); //输出结果
pso.Run(0.99999,0,100); //运行微粒群
printf("\nThe Result is: %f\t\n",pso.GetBest(Xup)); //输出结果
pso.SetW(1);//W还原 每次开始新的计算时有很多参数要重新赋值的 参看37-51行变量 和头文件的137-161行变量
while(pso.Run(MAXG,0).FitBest<0.99999)
{
//iter++;
//weight_up = (weight-0.4) * (MAXITER - iter) /MAXITER +0.4;
}
printf("\nThe Result is: %f\t\n",pso.GetBest(Xup));
delete []tempV;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -