#include <stdio.h>
#include "math.h"
#include <stdlib.h>
#include <string.h>
#define ACC_1 1.49445
#define ACC_2 1.49445
#define MAXCNT 300
#define popNum 20
#define Vmax 0.5
#define Vmin -0.5
#define VIM 2
#define PI 3.1415926
#define popMax 2
#define popMin -2
typedef struct{
double popu[VIM];
double itrV[VIM];
double pbest[VIM];
double fitnesspbest;
double fitness;
}TPSOITRDATA;
typedef struct
{
double itrRlt;
double gblRlt[VIM];
}TPSOResult;
double psoFitCalc(double *arr);
void popInit(void);
TPSOITRDATA psoData[popNum];
TPSOResult psoResult[MAXCNT];
double psoBestLocat[VIM];
double psoBestValue;
void popInit(void){
for(int i=0;i<popNum;i++)
{
for(int j=0;j<VIM;j++)
{
psoData[i].popu[j] = (((double)rand())/RAND_MAX-0.5)*4;
psoData[i].itrV[j] = ((double)rand())/RAND_MAX-0.5;
}
psoData[i].fitness = psoFitCalc(&psoData[i].popu[0]);
}
}
double psoFitCalc(double *arr){
double x = *arr;
double y = *(arr+1);
double fitness = sin(sqrt(x*x+y*y))/(sqrt(x*x+y*y)) + exp((cos(2*PI*x)+cos(2*PI*y))/2) - 2.71289;
return fitness;
}
double * psoRltMax(double *fitness,int length){
int index = 0;
double max = *fitness;
static double best_fit_index[2];
for(int i=1;i<length;i++)
{
if(*(fitness+i) > max)
max = *(fitness+i);
index = i;
}
best_fit_index[0] = index;
best_fit_index[1] = max;
return best_fit_index;
}
double findPsoOptValue(){
}
void PSOItrCore(){
int Index;
double * psoItrIndex;
double * best_fit_index;
popInit();
best_fit_index = psoRltMax(&psoData[0].fitness, popNum);
Index = (int)(*best_fit_index);
memcpy(psoBestLocat,psoData[Index].popu,VIM);
for(int i=0; i<popNum; i++){
memcpy(psoData[i].pbest,psoData[i].popu,VIM);
psoData[i].fitnesspbest = psoData[i].fitness;
}
psoBestValue = *(best_fit_index+1);
for(int i=0;i<MAXCNT;i++){
for(int j=0;j<popNum;j++){
for(int k=0;k<VIM;k++){
double rand1 = (double)rand()/RAND_MAX;
double rand2 = (double)rand()/RAND_MAX;
psoData[j].itrV[k] = psoData[j].itrV[k] + \
ACC_1*rand1*(psoData[j].pbest[k]-psoData[j].popu[k]) + ACC_2*rand2*(psoBestLocat[k]-psoData[j].popu[k]);
if(psoData[j].itrV[k] > Vmax) psoData[j].itrV[k] = Vmax;
if(psoData[j].itrV[k] < Vmin) psoData[j].itrV[k] = Vmin;
psoData[j].popu[k] = psoData[j].popu[k] + psoData[j].itrV[k];
if(psoData[j].popu[k] > popMax) psoData[j].popu[k] = popMax;
if(psoData[j].popu[k] < popMin) psoData[j].popu[k] = popMin;
}
psoData[j].fitness = psoFitCalc(psoData[j].popu);
}
for(int j=0;j<popNum;j++){
if(psoData[j].fitness > psoData[j].fitnesspbest ){
memcpy(psoData[i].pbest,psoData[j].popu,VIM);
psoData[i].fitnesspbest = psoData[j].fitness;
}
if(psoData[j].fitness > psoBestValue ){
memcpy(psoBestLocat,psoData[j].popu,VIM);
psoBestValue = psoData[j].fitness;
}
}
memcpy(psoResult[i].gblRlt,psoBestLocat,VIM);
psoResult[i].itrRlt = psoBestValue;
}
}
void main(){
PSOItrCore();
double * best_arr;
best_arr = psoRltMax(&psoData[0].fitness,popNum);
int best_gen_number = *best_arr;
double best = *(best_arr+1);
printf("迭代了%d次,在第%d次取到最优值,最优值为:%lf.\n",MAXCNT,best_gen_number+1,best);
}