《遗传算法的C++代码实现教程.doc》由会员分享,可在线阅读,更多相关《遗传算法的C++代码实现教程.doc(13页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、遗传算法的C+代码实现教程此例程总共包含3个文件:main.c(主函数);GA.c(包含3个所用函数);GA.h(头文件),3个文件截图如下:用visual c+或者visual stutio创建工程,然后将上述3个文件包含进工程,编译运行即可。亲测可行!3个文件代码分别如下:1、 main.c:includeiostreamincludeGA.husing namespace std;/* GA demo求函数y=x*sin(10*pai*x)+2.0的最大值编码:浮点数,1位初始群体数:50变异概率:0。8进化代数:100取值范围:0,4变异步长:0.004注:因为是单数浮点数编码,所以未
2、使用基因重组函数*/int main()GenEngine genEngine(50,0。8,0.8,1,100,0,4);genEngine.OnStartGenAlg();getchar();2、 GA。c:#includevectorincludeinclude stdlib。hinclude time.h#includeinclude”GA.husing namespace std;/srand((unsigned) time(NULL));double random()double randNum;randNum=rand()*1。0/RAND_MAX;return randNum;
3、 GenAlg:GenAlg()void GenAlg:init(int popsize, double MutRate, double CrossRate, int GenLenght,double LeftPoint,double RightPoint)popSize = popsize;mutationRate = MutRate;crossoverRate = CrossRate;chromoLength = GenLenght;totalFitness = 0;generation = 0;/fittestGenome = 0;bestFitness = 0.0;worstFitne
4、ss = 99999999;averageFitness = 0;maxPerturbation=0.004;leftPoint=LeftPoint;rightPoint=RightPoint;/清空种群容器,以初始化vecPop.clear();for (int i=0; ipopSize; i+) /类的构造函数已经把适应性评分初始化为0vecPop.push_back(Genome());/把所有的基因编码初始化为函数区间内的随机数。for (int j=0; jchromoLength; j+)vecPopi。vecGenome。push_back(random() (rightPoi
5、nt leftPoint) + leftPoint);void GenAlg:Reset()totalFitness=0;/bestFitness=0; /worstFitness=9999;averageFitness=0;void GenAlg::CalculateBestWorstAvTot()for (int i=0; ipopSize; +i)/累计适应性分数。totalFitness+= vecPopi。fitness;if(vecPopi.fitness=bestFitness)bestFitness=vecPopi.fitness;fittestGenome=vecPopi;i
6、f(vecPopi.fitness=worstFitness)worstFitness=vecPopi.fitness;averageFitness=totalFitness/popSize;Genome GenAlg:: GetChromoRoulette()/产生一个0到人口总适应性评分总和之间的随机数./中m_dTotalFitness记录了整个种群的适应性分数总和)double Slice = (random() totalFitness;/这个基因将承载转盘所选出来的那个个体.Genome TheChosenOne;/累计适应性分数的和。double FitnessSoFar = 0
7、;/遍历总人口里面的每一条染色体.for (int i=0; i chromo)/遵循预定的突变概率,对基因进行突变for (int i=0; ichromo.size(); +i)/如果发生突变的话if (random() mutationRate)/使该权值增加或者减少一个很小的随机数值chromoi += (random()-0。5) maxPerturbation);/限定范围if(chromoi leftPoint)chromoi = rightPoint;else if(chromoi rightPoint)chromoi = leftPoint;/以上代码非基因变异的一般性代码只
8、是用来保证基因编码的可行性。/此函数产生新的一代,见证着整个进化的全过程./以父代种群的基因组容器作为参数传进去,该函数将往该容器里放入新一代的基因组(当然是经过了优胜劣汰的)void GenAlg:Epoch(vector &vecNewPop)/用类的成员变量来储存父代的基因组(在此之前m_vecPop储存的是不带估值的所有基因组)vecPop = vecNewPop;/初始化相关变量Reset();/为相关变量赋值CalculateBestWorstAvTot();/清空装载新种群的容器vecNewPop.clear(); /产生新一代的所有基因组while (vecNewPop.siz
9、e() popSize)/转盘随机抽出两个基因Genome mum = GetChromoRoulette();Genome dad = GetChromoRoulette();/创建两个子代基因组vectordouble baby1, baby2;/先把他们分别设置成父方和母方的基因baby1 = mum.vecGenome;baby2 = dad.vecGenome;/使子代基因发生基因突变Mutate(baby1);Mutate(baby2);/把两个子代基因组放到新的基因组容器里面vecNewPop。push_back( Genome(baby1, 0) );vecNewPop。pus
10、h_back( Genome(baby2, 0) );/子代产生完毕/如果你设置的人口总数非单数的话,就会出现报错if(vecNewPop。size() != popSize)/MessageBox(你的人口数目不是单数!!”);cout”errorendl;return;Genome GenAlg::GetBestFitness()return fittestGenome;double GenAlg:GetAverageFitness()return averageFitness;void GenEngine::report(const int&genNum)cout第genNum”代”en
11、dl; cout”最佳适应度:”bestFitnessendl;cout”最佳适应度基因取值:bestSearchendl;cout”平均适应度:”averageFitnessendlendl;void GenEngine:: OnStartGenAlg()/产生随机数srand( (unsigned)time( NULL ) );/初始化遗传算法引擎genAlg。init(g_popsize, g_dMutationRate, g_dCrossoverRate, g_numGen,g_LeftPoint,g_RightPoint);/清空种群容器m_population。clear();/种
12、群容器装进经过随机初始化的种群m_population = genAlg.vecPop;vector double input;double output;input。push_back(0);for(int Generation = 0;Generation =bestFitness)bestSearch=genAlg。GetBestFitness().vecGenome0;bestFitness=genAlg.GetBestFitness()。fitness;averageFitness=genAlg。GetAverageFitness();/coutbestSearchendl;repo
13、rt(Generation+1);/return bestSearch;3、GA。h:includevectorusing namespace std;const double pai=3.1415926;class Genomepublic: friend class GenAlg; friend class GenEngine; Genome():fitness(0) Genome(vector vec, double f): vecGenome(vec), fitness(f) /类的带参数初始化参数。private: vector double vecGenome; / dFitnes
14、s用于存储对该基因的适应性评估。 double fitness; /类的无参数初始化参数.;/遗传算法class GenAlgpublic:/这个容器将储存每一个个体的染色体vector vecPop;/人口(种群)数量int popSize; /每一条染色体的基因的总数目int chromoLength;/所有个体对应的适应性评分的总和double totalFitness;/在所有个体当中最适应的个体的适应性评分double bestFitness;/所有个体的适应性评分的平均值double averageFitness;/在所有个体当中最不适应的个体的适应性评分double worstF
15、itness;/最适应的个体在m_vecPop容器里面的索引号Genome fittestGenome;/基因突变的概率,一般介于0.05和0。3之间double mutationRate;/基因交叉的概率一般设为0。7double crossoverRate;/代数的记数器int generation;/最大变异步长double maxPerturbation;double leftPoint;double rightPoint;/构造函数GenAlg();/初始化变量void Reset();/初始化函数void init(int popsize, double MutRate, doub
16、le CrossRate, int GenLenght,double LeftPoint,double RightPoint);/计算TotalFitness, BestFitness, WorstFitness, AverageFitness等变量void CalculateBestWorstAvTot();/轮盘赌选择函数Genome GetChromoRoulette();/基因变异函数void Mutate(vectordouble chromo);/这函数产生新一代基因void Epoch(vector &vecNewPop);Genome GetBestFitness();doub
17、le GetAverageFitness();;class Curvepublic:double function(const vector& input)double x=input0; double output;output=xsin(10*paix)+2.0;return output;private:;/遗传运算引擎class GenEnginepublic:GenEngine(const int& popsize,const double mutationRate,const double& crossoverRate,const intnumGen,const intgenera
18、tion,const double leftPoint, const double& rightPoint):genAlg(),curve(),m_population()g_popsize=popsize;g_dMutationRate=mutationRate;g_dCrossoverRate=crossoverRate;g_numGen=numGen;g_Generation=generation;g_LeftPoint=leftPoint;g_RightPoint=rightPoint; bestFitness=0; bestSearch=0;void OnStartGenAlg();/报告每一代的运行情况void report(const intgenNum);private:GenAlg genAlg;Curve curve;vectorGenome m_population;int g_popsize;double g_dMutationRate;double g_dCrossoverRate;int g_numGen;int g_Generation;double g_LeftPoint;double g_RightPoint;double bestFitness; double bestSearch;double averageFitness;