Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include <iomanip>
- using namespace std;
- int main()
- {
- int population,iteration;
- float weight,c1,c2;
- int i,j;
- float x[2][100],v[2][100];
- float fitness[100];
- float pbest[100],gbest=0;
- float precord[2][100],grecord[2];
- int count=0;
- float tempV[2];
- float check[2][100];
- float k=1,kmax=0;
- //輸入參數
- cout<<"粒子群演算法PSO\n請輸入母體個數:";
- cin>>population;
- cout<<"請輸入迭代次數:";
- cin>>iteration;
- cout<<"請輸入慣性權重:";
- cin>>weight;
- cout<<"請輸入學習因子C1:";
- cin>>c1;
- cout<<"請輸入學習因子C2:";
- cin>>c2;
- //隨機產生S0、V0
- srand(time(NULL));
- for(i=0;i<population;i++)
- { rands:
- x[0][i]=(rand()%401+200)*0.01; //x1=2~6
- x[1][i]=(rand()%201)*0.01; //x2=0~2
- if(6*x[0][i]+4*x[1][i]>24 || x[0][i]+2*x[1][i]>6 || -x[0][i]+x[1][i]>1 || x[1][i]>2 || x[1][i]<0 || x[0][i]<0)
- { goto rands;
- }
- }
- for(i=0;i<2;i++)
- { for(j=0;j<population;j++)
- { randv0:
- v[i][j]=(rand()%601+1-300)*0.01; //v=-3~3
- if(v[i][j]==0)
- {goto randv0;}
- }
- }
- do{
- //評估各粒子適應函數值、記錄pbest&gbest
- for(i=0;i<2;i++)
- { for(j=0;j<population;j++)
- { fitness[j]=5*x[0][j]+4*x[1][j];
- if(fitness[j]>pbest[j])
- { pbest[j]=fitness[j];
- precord[0][j]=x[0][j];
- precord[1][j]=x[1][j];
- }
- if(fitness[j]>gbest)
- { gbest=fitness[j];
- grecord[0]=x[0][j];
- grecord[1]=x[1][j];
- }
- }
- }
- //印出表格
- cout<<"x1\tx2\tv1\tv2\tfitness\tpbest\n";
- for(i=0;i<population;i++)
- { cout<<x[0][i]<<"\t"<<x[1][i]<<"\t"<<v[0][i]<<"\t"<<v[1][i]<<"\t"
- <<fitness[i]<<"\t"<<pbest[i]<<endl;
- }
- cout<<"第"<<count<<"代 gbest = "<<gbest<<endl<<endl;
- //更新速度、位置
- for(i=0;i<population;i++)
- { decrease:
- tempV[0]=((weight*v[0][i])+
- (c1*((rand()%10000)*0.0001)*(precord[0][i]-x[0][i]))+
- (c2*((rand()%10000)*0.0001)*(grecord[0]-x[0][i]))
- )/k;
- tempV[1]=((weight*v[1][i])+
- (c1*((rand()%10000)*0.0001)*(precord[1][i]-x[1][i]))+
- (c2*((rand()%10000)*0.0001)*(grecord[1]-x[1][i]))
- )/k;
- check[0][i]=x[0][i]+tempV[0];
- check[1][i]=x[1][i]+tempV[1];
- if(6*check[0][i]+4*check[1][i]<=24 && check[0][i]+2*check[1][i]<=6 && -check[0][i]+check[1][i]<=1 && check[1][i]<=2 && check[1][i]>=0 && check[0][i]>=0)
- { x[0][i]=check[0][i];
- x[1][i]=check[1][i];
- v[0][i]=tempV[0];
- v[1][i]=tempV[1];
- }
- else
- { k++;
- if(k>kmax)
- {kmax=k;}
- goto decrease;
- }
- k=1;
- }
- count++;
- }while(count<=iteration);
- cout<<"kmax="<<kmax<<endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement