#include <iostream> #include <math.h> #include <time.h> using namespace std; #define M 50 //群体数目50 #define N 4 //每个粒子的维数4 #define NN 100 //迭代次数 //测试类 class TestFunction { public: double resen(double x1,double x2,double x3,double x4) { double s=0; s=100*(x2-x1*x1)*(x2-x1*x1)+(1-x1)*(1-x1)+s; s=100*(x3-x2*x2)*(x3-x2*x2)+(1-x2)*(1-x2)+s; s=100*(x4-x3*x3)*(x4-x3*x3)+(1-x3)*(1-x3)+s; return s; } }; class CQPSO { private: double (*w)[N];// = new double[50][4]; //总体粒子 double *f;//=new double[M];//适应度值 double *ff;//=new double[M];//相对f的比较值 double (*p)[N];//=new double[M][N]; double (*v)[N];//粒子更新速度 double *g;//=new double[N]; double c1; double c2; TestFunction *tf;// = new TestFunction; double random() { double s; s=(abs(rand())%10000+10000)/10000.0-1.0; return s; } public: CQPSO( ) { int i,j; w=new double[M][N]; v=new double[M][N]; f=new double[M]; ff=new double[M]; p=new double[M][N]; g=new double[N]; tf=new TestFunction; for(i=0;i<M;i++) { for(j=0;j<N;j++) { w[i][j]=random(); v[i][j]=random(); } } c1=2; c2=2; } void CQPSOmethod(int count) { int i,j; if(count==1) { for(i=0;i<M;i++) { for(j=0;j<N;j++) { p[i][j]=w[i][j]; } f[i]=tf->resen(w[i][0],w[i][1],w[i][2],w[i][3]); } cqpso_p();//得出全局最优 } if(count>1) { cqpso_update(count); for(i=0;i<M;i++) { ff[i]=tf->resen(w[i][0],w[i][1],w[i][2],w[i][3]); if(ff[i]<f[i]) { f[i]=ff[i]; for(j=0;j<N;j++) p[i][j]=w[i][j]; } } cqpso_p(); } cout<<(tf->resen(g[0],g[1],g[2],g[3]))<<endl; } double ww(int count) { double wmax=0.9; double wmin=0.1; double wx=0.9-count*(0.8/NN); return wx; } void cqpso_p()//得到个体最优中最小值——全局最优 { double temp=f[0]; int i,j; for(i=1;i<M;i++) { if(f[i]<temp) { temp=f[i]; } } for(i=0;i<M;i++) { if(temp==f[i]) { for(j=0;j<N;j++) { g[j]=p[i][j]; } break; } } } void cqpso_update(int count ) { int i,j; for(i=0;i<M;i++) { for(j=0;j<N;j++) v[i][j]=ww(count)*v[i][j]+c1*random()*(p[i][j]-w[i][j])+c2*random()*(g[j]-w[i][j]); } for(i=0;i<M;i++) { for(j=0;j<N;j++) w[i][j]=w[i][j]+v[i][j]; } } }; int main() { int i; srand((unsigned)time(0)); CQPSO *qo = new CQPSO(); for(i=1;i<NN;i++) qo->CQPSOmethod(i); }