// gafx.cpp : 定义控制台应用程序的入口点。 //本程序试用遗传算法来解决Rosenbrock函数的全局最大值计算问题: //max f(x1,x2)=100(x1^2-x2^2)^2+(1-x1)^2 //定义域 -2.048<=xi<=2.048 ///执行了串行GA与并行GA,并进行了比较 #include "stdafx.h" #include "omp.h" #include #include #include #include #include using namespace std; #define T 200 //最大迭代次数 #define N 30 //种群大小 #define Pc 0.6 //交叉概率 #define Pm 0.02 //变异概率 struct population{ int x[20]; double x1,x2; double fit; double cfit; }p[N],p_para[N],pbest,p_para_best;//pbest记录具有最高适应值的个体 void initial(population *p); void decode(population *p); void evaluatefit(population *p); void select(population *p); void cross(population *p); void mutate(population *p); void nextgeneration(population *p); void print(population *p,int t,int pattern); void evaluatefit_para(population *p); void mutate_para(population *p); void nextgeneration_para(population *p); //-------------------------------------------------------------- //-------------------------------------------------------------- int rand01() {//随机产生或 int r; double q; q=rand()/(RAND_MAX+0.0); if(q<0.5) r=0; else r=1; return r; } double randxy(double x,double y) {//生成(x,y)内一随机数 double c,r; c=y-x; r=x+c*rand()/(RAND_MAX+1.0); return r; } int find_the_best(population *p) {//返回p中适应度最大的下标 int mem,cur_best = 0; for (mem = 0; mem < N; mem++) if (p[mem].fit >p[cur_best].fit) cur_best= mem; return cur_best; } int find_the_worst(population *p) {//返回p中适应度最小的下标 int mem,cur_worst = 0; for (mem = 0; mem < N; mem++) if (p[mem].fit < p[cur_worst].fit) cur_worst= mem; return cur_worst; } void keep_the_best(population *p) {//用pbest记录适应度最高的个体 int cur_best=find_the_best(p); // 复制最优个体至pbest for (int i = 0; ...