首页 遗传算法C语言代码

遗传算法C语言代码

举报
开通vip

遗传算法C语言代码//GA.cpp:Definestheentrypointfortheconsoleapplication.///*这是一个非常简单的遗传算法源代码,是由DenisCormier(NorthCarolinaStateUniversity)开发的,SitaS.Raghavan(UniversityofNorthCarolinaatCharlotte)修正。代码保证尽可能少,实际上也不必查错。对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。注意代码的设计是求最大值,其中...

遗传算法C语言代码
//GA.cpp:Definestheentrypointfortheconsoleapplication.///*这是一个非常简单的遗传算法源代码,是由DenisCormier(NorthCarolinaStateUniversity)开发的,SitaS.Raghavan(UniversityofNorthCarolinaatCharlotte)修正。代码保证尽可能少,实际上也不必查错。对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价 关于工期滞后的函关于工程严重滞后的函关于工程进度滞后的回复函关于征求同志党风廉政意见的函关于征求廉洁自律情况的复函 数”即可。注意代码的 设计 领导形象设计圆作业设计ao工艺污水处理厂设计附属工程施工组织设计清扫机器人结构设计 是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。该系统使用比率选择、精华模型、单点杂交和均匀变异。如果用Gaussian变异替换均匀变异,可能得到更好的效果。代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。读者可以从ftp.uncc.edu,目录coe/evol中的文件prog.c中获得。要求输入的文件应该命名为‘gadata.txt’;系统产生的输出文件为‘galog.txt’。输入的文件由几行组成:数目对应于变量数。且每一行提供次序——对应于变量的上下界。如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。*/#include<stdio.h>#include<stdlib.h>#include<math.h>/*Changeanyoftheseparameterstomatchyourneeds*///请根据你的需要来修改以下参数#definePOPSIZE50/*populationsize种群大小*/#defineMAXGENS1000/*max.numberofgenerations最大基因个数*/constintNVARS=3;/*no.ofproblemvariables问题变量的个数*/#definePXOVER0.8/*probabilityofcrossover杂交概率*/#definePMUTATION0.15/*probabilityofmutation变异概率*/#defineTRUE1#defineFALSE0intgeneration;/*currentgenerationno.当前基因个数*/intcur_best;/*bestindividual最优个体*/FILE*galog;/*anoutputfile输出文件指针*/structgenotype/*genotype(GT),amemberofthepopulation种群的一个基因的结构体类型*/{ doublegene[NVARS];/*astringofvariables变量*/ doublefitness;/*GT'sfitness基因的适应度*/ doubleupper[NVARS];/*GT'svariablesupperbound基因变量的上界*/ doublelower[NVARS];/*GT'svariableslowerbound基因变量的下界*/ doublerfitness;/*relativefitness比较适应度*/ doublecfitness;/*cumulativefitness积累适应度*/};structgenotypepopulation[POPSIZE+1];/*population种群*/structgenotypenewpopulation[POPSIZE+1];/*newpopulation;新种群*//*replacestheoldgeneration*///取代旧的基因/*Declarationofproceduresusedbythisgeneticalgorithm*///以下是一些函数声明voidinitialize(void);doublerandval(double,double);voidevaluate(void);voidkeep_the_best(void);voidelitist(void);voidselect(void);voidcrossover(void);voidXover(int,int);voidswap(double*,double*);voidmutate(void);voidreport(void);/***************************************************************//*Initializationfunction:Initializesthevaluesofgenes*//*withinthevariablesbounds.Italsoinitializes(tozero)*//*allfitnessvaluesforeachmemberofthepopulation.It*//*readsupperandlowerboundsofeachvariablefromthe*//*inputfile`gadata.txt'.Itrandomlygeneratesvalues*//*betweentheseboundsforeachgeneofeachgenotypeinthe*//*population.Theformatoftheinputfile`gadata.txt'is*//*var1_lower_boundvar1_upperbound*//*var2_lower_boundvar2_upperbound...*//***************************************************************/voidinitialize(void){ FILE*infile; inti,j; doublelbound,ubound; if((infile=fopen("gadata.txt","r"))==NULL) { fprintf(galog,"\nCannotopeninputfile!\n"); exit(1); } /*initializevariableswithinthebounds*/ //把输入文件的变量界限输入到基因结构体中 for(i=0;i<NVARS;i++) { fscanf(infile,"%lf",&lbound); fscanf(infile,"%lf",&ubound); for(j=0;j<POPSIZE;j++) { population[j].fitness=0; population[j].rfitness=0; population[j].cfitness=0; population[j].lower[i]=lbound; population[j].upper[i]=ubound; population[j].gene[i]=randval(population[j].lower[i], population[j].upper[i]); } } fclose(infile);}/***********************************************************//*Randomvaluegenerator:Generatesavaluewithinbounds*//***********************************************************///随机数产生函数doublerandval(doublelow,doublehigh){ doubleval; val=((double)(rand()%1000)/1000.0)*(high-low)+low; return(val);}/*************************************************************//*Evaluationfunction:Thistakesauserdefinedfunction.*//*Eachtimethisischanged,thecodehastoberecompiled.*//*Thecurrentfunctionis:x[1]^2-x[1]*x[2]+x[3]*//*************************************************************///评价函数,可以由用户自定义,该函数取得每个基因的适应度voidevaluate(void){ intmem; inti; doublex[NVARS+1]; for(mem=0;mem<POPSIZE;mem++) { for(i=0;i<NVARS;i++) x[i+1]=population[mem].gene[i]; population[mem].fitness=(x[1]*x[1])-(x[1]*x[2])+x[3]; }}/***************************************************************//*Keep_the_bestfunction:Thisfunctionkeepstrackofthe*//*bestmemberofthepopulation.Notethatthelastentryin*//*thearrayPopulationholdsacopyofthebestindividual*//***************************************************************///保存每次遗传后的最佳基因voidkeep_the_best(){ intmem; inti; cur_best=0; /*storestheindexofthebestindividual*/ //保存最佳个体的索引 for(mem=0;mem<POPSIZE;mem++) { if(population[mem].fitness>population[POPSIZE].fitness) { cur_best=mem; population[POPSIZE].fitness=population[mem].fitness; } } /*oncethebestmemberinthepopulationisfound,copythegenes*/ //一旦找到种群的最佳个体,就拷贝他的基因 for(i=0;i<NVARS;i++) population[POPSIZE].gene[i]=population[cur_best].gene[i];}/****************************************************************//*Elitistfunction:Thebestmemberofthepreviousgeneration*//*isstoredasthelastinthearray.Ifthebestmemberof*//*thecurrentgenerationisworsethenthebestmemberofthe*//*previousgeneration,thelatteronewouldreplacetheworst*//*memberofthecurrentpopulation*//****************************************************************///搜寻杰出个体函数:找出最好和最坏的个体。//如果某代的最好个体比前一代的最好个体要坏,那么后者将会取代当前种群的最坏个体voidelitist(){ inti; doublebest,worst;/*bestandworstfitnessvalues最好和最坏个体的适应度值*/ intbest_mem,worst_mem;/*indexesofthebestandworstmember最好和最坏个体的索引*/ best=population[0].fitness; worst=population[0].fitness; for(i=0;i<POPSIZE-1;++i) { if(population[i].fitness>population[i+1].fitness) { if(population[i].fitness>=best) { best=population[i].fitness; best_mem=i; } if(population[i+1].fitness<=worst) { worst=population[i+1].fitness; worst_mem=i+1; } } else { if(population[i].fitness<=worst) { worst=population[i].fitness; worst_mem=i; } if(population[i+1].fitness>=best) { best=population[i+1].fitness; best_mem=i+1; } } } /*ifbestindividualfromthenewpopulationisbetterthan*/ /*thebestindividualfromthepreviouspopulation,then*/ /*copythebestfromthenewpopulation;elsereplacethe*/ /*worstindividualfromthecurrentpopulationwiththe*/ /*bestonefromthepreviousgeneration*/ //如果新种群中的最好个体比前一代的最好个体要强的话,那么就把新种群的最好个体拷贝出来。 //否则就用前一代的最好个体取代这次的最坏个体 if(best>=population[POPSIZE].fitness) { for(i=0;i<NVARS;i++) population[POPSIZE].gene[i]=population[best_mem].gene[i]; population[POPSIZE].fitness=population[best_mem].fitness; } else { for(i=0;i<NVARS;i++) population[worst_mem].gene[i]=population[POPSIZE].gene[i]; population[worst_mem].fitness=population[POPSIZE].fitness; }}/**************************************************************//*Selectionfunction:Standardproportionalselectionfor*//*maximizationproblemsincorporatingelitistmodel-makes*//*surethatthebestmembersurvives*//**************************************************************///选择函数:用于最大化合并杰出模型的 标准 excel标准偏差excel标准偏差函数exl标准差函数国标检验抽样标准表免费下载红头文件格式标准下载 比例选择,保证最优秀的个体得以生存voidselect(void){ intmem,j,i; doublesum=0; doublep; /*findtotalfitnessofthepopulation*/ //找出种群的适应度之和 for(mem=0;mem<POPSIZE;mem++) { sum+=population[mem].fitness; } /*calculaterelativefitness*/ //计算相对适应度 for(mem=0;mem<POPSIZE;mem++) { population[mem].rfitness=population[mem].fitness/sum; } population[0].cfitness=population[0].rfitness; /*calculatecumulativefitness*/ //计算累加适应度 for(mem=1;mem<POPSIZE;mem++) { population[mem].cfitness=population[mem-1].cfitness+ population[mem].rfitness; } /*finallyselectsurvivorsusingcumulativefitness.*/ //用累加适应度作出选择 for(i=0;i<POPSIZE;i++) { p=rand()%1000/1000.0; if(p<population[0].cfitness) newpopulation[i]=population[0]; else { for(j=0;j<POPSIZE;j++) if(p>=population[j].cfitness&& p<population[j+1].cfitness) newpopulation[i]=population[j+1]; } } /*onceanewpopulationiscreated,copyitback*/ //当一个新种群建立的时候,将其拷贝回去 for(i=0;i<POPSIZE;i++) population[i]=newpopulation[i];}/***************************************************************//*Crossoverselection:selectstwoparentsthattakepartin*//*thecrossover.Implementsasinglepointcrossover*//***************************************************************///杂交函数:选择两个个体来杂交,这里用单点杂交voidcrossover(void){ intmem,one; intfirst=0;/*countofthenumberofmemberschosen*/ doublex; for(mem=0;mem<POPSIZE;++mem) { x=rand()%1000/1000.0; if(x<PXOVER) { ++first; if(first%2==0) Xover(one,mem); else one=mem; } }}/**************************************************************//*Crossover:performscrossoverofthetwoselectedparents.*//**************************************************************/voidXover(intone,inttwo){ inti; intpoint;/*crossoverpoint*/ /*selectcrossoverpoint*/ if(NVARS>1) { if(NVARS==2) point=1; else point=(rand()%(NVARS-1))+1; for(i=0;i<point;i++) swap(&population[one].gene[i],&population[two].gene[i]); }}/*************************************************************//*Swap:Aswapprocedurethathelpsinswapping2variables*//*************************************************************/voidswap(double*x,double*y){ doubletemp; temp=*x; *x=*y; *y=temp; }/**************************************************************//*Mutation:Randomuniformmutation.Avariableselectedfor*//*mutationisreplacedbyarandomvaluebetweenlowerand*//*upperboundsofthisvariable*//**************************************************************///变异函数:被该函数选中后会使得某一变量被一个随机的值所取代voidmutate(void){ inti,j; doublelbound,hbound; doublex; for(i=0;i<POPSIZE;i++) for(j=0;j<NVARS;j++) { x=rand()%1000/1000.0; if(x<PMUTATION) { /*findtheboundsonthevariabletobemutated确定*/ lbound=population[i].lower[j]; hbound=population[i].upper[j]; population[i].gene[j]=randval(lbound,hbound); } }}/***************************************************************//*Reportfunction:Reportsprogressofthesimulation.Data*//*dumpedintotheoutputfileareseparatedbycommas*//***************************************************************/voidreport(void){ inti; doublebest_val;/*bestpopulationfitness最佳种群适应度*/ doubleavg;/*avgpopulationfitness平均种群适应度*/ doublestddev;/*std.deviationofpopulationfitness*/ doublesum_square;/*sumofsquareforstd.calc各个个体平方之和*/ doublesquare_sum;/*squareofsumforstd.calc平均值的平方乘个数*/ doublesum;/*totalpopulationfitness所有种群适应度之和*/ sum=0.0; sum_square=0.0; for(i=0;i<POPSIZE;i++) { sum+=population[i].fitness; sum_square+=population[i].fitness*population[i].fitness; } avg=sum/(double)POPSIZE; square_sum=avg*avg*POPSIZE; stddev=sqrt((sum_square-square_sum)/(POPSIZE-1)); best_val=population[POPSIZE].fitness; fprintf(galog,"\n%5d,%6.3f,%6.3f,%6.3f\n\n",generation, best_val,avg,stddev);}/**************************************************************//*Mainfunction:Eachgenerationinvolvesselectingthebest*//*members,performingcrossover&mutationandthen*//*evaluatingtheresultingpopulation,untiltheterminating*//*conditionissatisfied*//**************************************************************/voidmain(void){ inti; if((galog=fopen("galog.txt","w"))==NULL) { exit(1); } generation=0; fprintf(galog,"\ngenerationbestaveragestandard\n"); fprintf(galog,"numbervaluefitnessdeviation\n"); initialize(); evaluate(); keep_the_best(); while(generation<MAXGENS) { generation++; select(); crossover(); mutate(); report(); evaluate(); elitist(); } fprintf(galog,"\n\nSimulationcompleted\n"); fprintf(galog,"\nBestmember:\n"); for(i=0;i<NVARS;i++) { fprintf(galog,"\nvar(%d)=%3.3f",i,population[POPSIZE].gene[i]); } fprintf(galog,"\n\nBestfitness=%3.3f",population[POPSIZE].fitness); fclose(galog); printf("Success\n");}/***************************************************************/
本文档为【遗传算法C语言代码】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_350459
暂无简介~
格式:doc
大小:20KB
软件:Word
页数:11
分类:工学
上传时间:2013-05-13
浏览量:147