1. 云栖社区>
2. 量子那些事儿>
3. 博客>
4. 正文

## 量子粒子群优化算法

```#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;

#define M 50  //群体数目50
#define N 4   //每个粒子的维数4
//测试类
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 delta;
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 *g;//=new double[N];
double *c;//=new double[N];
TestFunction *tf;// = new TestFunction;
double random()
{
double s;
s=(abs(rand())%10000+10000)/10000.0-1.0;
return s;
}
public:
CQPSO(double delta)
{
int i,j;
this->delta=delta;
w=new double[M][N];
f=new double[M];
ff=new double[M];
p=new double[M][N];
g=new double[N];
c=new double[N];
tf=new TestFunction;
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
w[i][j]=random();
}
}

}

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(f);//得出全局最优
}

if(count>1)
{
cqpso_update( w );
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(f);
}
cout<<(tf->resen(g[0],g[1],g[2],g[3]))<<endl;
}

void cqpso_p(double *f)//得到个体最优中最小值——全局最优
{
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_c(double (*p)[N])
{
int i,j;
for(i=0;i<N;i++)  c[i]=0;
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
c[i]=c[i]+p[j][i];
}
}
for(i=0;i<N;i++) c[i]=c[i]/M;
}

void cqpso_update( double (*w)[N] )
{
int i,j;
double *fai=new double[N];
double (*u)[N]=new double[M][N];
double (*pp)[N]=new double[M][N];
for(i=0;i<N;i++)
{
fai[i]=random();
}
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
u[i][j]=random();
}
cqpso_c( p );
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
pp[i][j]=fai[j]*p[i][j]+g[j]*(1-fai[j]);
}
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
w[i][j]=pp[i][j]+delta*(abs(c[j]-w[i][j]))*log(1/u[i][j]);
}
}

};

int main()
{
int i;
srand((unsigned)time(0));
CQPSO *qo = new CQPSO(0.5);
//qo->w=new double[M][N];
for(i=1;i<100;i++)
qo->CQPSOmethod(i);
}```

【云栖快讯】云栖社区技术交流群汇总，阿里巴巴技术专家及云栖社区专家等你加入互动，老铁，了解一下？  详情请点击