11 #define c1 1.49445 //加速度因子一般是根据大量实验所得 13 #define maxgen 1001 // 迭代次数 14 #define sizepop 20 // 种群规模 15 #define popmax 5.12 // 个体最大取值 16 #define popmin -5.12 // 个体最小取值 17 #define Vmax 1 // 速度最大值 18 #define Vmin -1 //速度最小值 19 #define dim 2 // 粒子的维数 20 #define PI 3.1415926 //圆周率 37 double fitness = -(20+x*x+y*y-10*cos(2*
PI*x)-10*cos(2*
PI*y));
46 for(
int j=0;j<
dim;j++)
48 pop[i][j] = (((double)rand())/RAND_MAX-0.5)*4;
49 V[i][j] = ((double)rand())/RAND_MAX-0.5;
55 double *
max(
double * fit,
int size)
59 static double best_fit_index[2];
60 for(
int i=1;i<size;i++)
66 best_fit_index[0] = index;
67 best_fit_index[1] =
max;
68 return best_fit_index;
75 double * best_fit_index;
77 int index = (int)(*best_fit_index);
79 for(
int i=0;i<
dim;i++)
86 for(
int j=0;j<
dim;j++)
97 double bestfitness = *(best_fit_index+1);
106 for(
int k=0;k<
dim;k++)
109 double rand1 = (double)rand()/RAND_MAX;
110 double rand2 = (double)rand()/RAND_MAX;
117 pop[j][k] =
pop[j][k] +
V[j][k];
134 for(
int k=0;k<
dim;k++)
143 for(
int k=0;k<
dim;k++)
148 for(
int k=0;k<
dim;k++)
160 clock_t
start,finish;
162 srand((
unsigned)time(NULL));
166 int best_gen_number = *best_arr;
167 double best = *(best_arr+1);
168 printf(
"迭代了%d次,在第%d次取到最优值,最优值为:%lf.\n",
maxgen,best_gen_number+1,best);
169 printf(
"取到最优值的位置为(%lf,%lf).\n",
genbest[best_gen_number][0],
genbest[best_gen_number][1]);
171 double duration = (double)(finish - start)/CLOCKS_PER_SEC;
172 printf(
"程序运行耗时:%lf\n",duration);
double genbest[maxgen][dim]
double pbest[sizepop][dim]
double * max(double *fit, int size)
double fitnesspbest[sizepop]