算法框架:
1. GenerateInitialPopulation();//生成初代种群
2. EvaluatePopulation();//评估种群
3. GenerateNextPopulation();//产生下一代
1).SelectionOperator();//选择
2).CrossoverOperator();//交叉
RandomDisorder();//随机乱序个体
3).MutationOperator();//变异
4. EvaluatePopulation();//评估种群
以求f(x1,x2)=100*(x1^2-x2)^2+(1-x1)^2的最大值为例
运行环境 VS 2010
// GeneticAlforith.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdlib.h"
#include <time.h>
#include <math.h>
#define CHROMLENGTH 24 //染色体长度
#define POPSIZE 80 //种群大小
#define MaxGeneration 200 //最大进化代数
#define Pc 0.6 //交叉概率
#define Pm 0.001 //变异概率
struct individual{
int chrom[CHROMLENGTH];
double fitness;
double nfitness;
};
struct individual population[POPSIZE],temppop[POPSIZE],bestchrom;
void GenerateInitialPopulation(){
for(int i=0;i<POPSIZE;i++){
for(int j=0;j<CHROMLENGTH;j++)
population[i].chrom[j]=rand()%2;
}
}
double func(double x1,double x2){
/* 定义函数表达式 */
double s;
s=100*pow((x1*x1-x2),2)+pow(1-x1,2);
return s;