#include<iostream.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
#define PNum 20 //粒子数目
#define Dim 1
#define LowLimit 0 //搜索域范围
#define HighLimit 2*3.1415926
#define MaxIteration 60
#define VLimit 20 //速度范围
struct PARTICLE
{
double Code[Dim]; //粒子向量,代表一个解
double BestCode[Dim]; //粒子的局部最优向量
double Vel[Dim]; //粒子速度数组
double Fit; //粒子适应度
double BestFit; //粒子的局部最优适应度
};
PARTICLE par[PNum];
double GBestCode[Dim]; //全局最优向量
double GBestFitness; //全局最优适应度
void GetLocalBest();
void GetGlobalBest();
double CalFitness(double x[]);
void Initialize();
void RenewParticles(int CurIteration);
double CalFitness(double x[])
{
double fit = 0.0;
fit = 11*sin(x[0]*6)+7*cos(x[0]*5);
return fit;
}
void GetLocalBest()
{
unsigned int i, j;
//更新个体局部最优值
for(i=0; i<PNum; i++)
{
par[i].Fit = CalFitness(par[i].Code);//计算每个粒子的适应度
if(par[i].Fit > par[i].BestFit)
{
par[i].BestFit = par[i].Fit;
for(j=0; j<Dim; j++) // 更新局部最优向量
{
par[i].BestCode[j] = par[i].Code[j];
}
}
}
}
void GetGlobalBest()
{
unsigned int i;
//找出全局最优
GBestFitness = par[0].BestFit;
int maxIndex=-1;//标记最大index
for(i=0; i<PNum; i++)
{
if(par[i].BestFit > GBestFitness)
{
GBestFitness = par[i].BestFit;
maxIndex = i;
}
}
if (maxIndex != -1)//全局最优向量
{
for(i=0; i<Dim; i++)
{
GBestCode[i] = par[maxIndex].BestCode[i];
}
}
}
void Initialize()
{
//生成粒子
unsigned int i,j;
for(i=0; i<PNum; i++)
{
for(j=0; j<Dim; j++)
{
par[i].Code[j] = LowLimit+(HighLimit-LowLimit)*1.0*rand()/RAND_MAX; //初始化群体
par[i].BestCode[j] = par[i].Code[j]; //将当前最优结果写入局部最优集合
par[i].Vel[j] = -VLimit+2*VLimit*1.0*rand()/RAND_MAX; //随机速度
}
}
//计算初始每个粒子的适应度
for(i=0; i<PNum; i++)
{
par[i].Fit = CalFitness(par[i].Code);
par[i].BestFit = par[i].Fit;//初始化局部最优适应度
}
GetGlobalBest();//初始化全局最优
}
void RenewParticles(int CurIteration)
{
unsigned int i,j;
//更新参数
//惯性权重
//通常weight=1,较大的w有较好的全局收敛能力,较小的w则有较强的局部收敛能力
double weight = 0.9-0.5*CurIteration/MaxIteration;
//收缩因子,通常shrinkage=0.729
double shrinkage = 0.729;
double c1=2;
double c2=2;
double alp=1;
//更新粒子位置
for(i=0; i<PNum; i++)
{
for(j=0; j<Dim; j++)
{
par[i].Code[j] += alp*par[i].Vel[j];
if(par[i].Code[j] > HighLimit)
{
par[i].Code[j] = HighLimit;
}
if(par[i].Code[j] < LowLimit)
{
par[i].Code[j] = LowLimit;
}
}
}
GetLocalBest();
GetGlobalBest();
//更新粒子速度
for(i=0; i<PNum; i++)
{
for(j=0; j<Dim; j++)
{
par[i].Vel[j] = weight*par[i].Vel[j]
+c1*1.0*rand()/RAND_MAX*(par[i].BestCode[j]-par[i].Code[j])
+c2*1.0*rand()/RAND_MAX*(GBestCode[j]-par[i].Code[j]);
par[i].Vel[j] = shrinkage*par[i].Vel[j];
/*
if(par[i].Vel[j] > VLimit)
{
par[i].Vel[j] = VLimit;
}
if(par[i].Vel[j] < -VLimit)
{
par[i].Vel[j] = -VLimit;
}
*/
}
}
}
int main()
{
int i=0;
srand((unsigned)time(NULL));
Initialize();
cout<<GBestCode[0]<<" "<<GBestFitness<<endl;
while(i < MaxIteration)
{
RenewParticles(i);
cout<<GBestCode[0]<<" "<<GBestFitness<<endl;
i++;
}
return 0;
}