遺傳算法C語言代碼_第1頁
遺傳算法C語言代碼_第2頁
遺傳算法C語言代碼_第3頁
遺傳算法C語言代碼_第4頁
遺傳算法C語言代碼_第5頁
已閱讀5頁,還剩1頁未讀 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

//GA.cpp:Definestheentrypointfortheconsoleapplication.///*這是一個非常簡單的遺傳算法源代碼,是由DenisCormier(NorthCarolinaStateUniversity)開發(fā)的,SitaS.Raghavan(UniversityofNorthCarolinaatCharlotte修正。代碼保證盡可能少,實際上也不必查錯。對一特定的應用修正此代碼,用戶只需改變常數(shù)的定義并且定義“評價函數(shù)”即可。注意代碼的設計是求最大值,其中的目標函數(shù)只能取正值;且函數(shù)值和個體的適應值之間沒有區(qū)別。該系統(tǒng)使用比率選擇、精華模型、單點雜交和均勻變異。如果用Gaussian變異替換均勻變異,可能得到更好的效果。代碼沒有任何圖形,甚至也沒有屏幕輸出,主要是保證在平臺之間的高可移植性。讀者可以從,目錄coe/evol中的文件prog.c中獲得。要求輸入的文件應該命名為‘gadata.txt’;系統(tǒng)產(chǎn)生的輸出文件為‘galog.txt’。輸入的文件由幾行組成:數(shù)目對應于變量數(shù)。且每一行提供次序一一對應于變量的上下界。如第一行為第一個變量提供上下界,第二行為第二個變量提供上下界,等等。*/#include<stdio.h>#include<stdlib.h>#include<math.h>/*Changeanyoftheseparameterstomatchyourneeds*/〃請根據(jù)你的需要來修改以下參數(shù)#definePOPSIZE50/*populationsize種群大小*/#defineMAXGENS1000/*max.numberofgenerations最大基因個數(shù)*/constintNVARS=3;/*no.ofproblemvariables問題變量的個數(shù)*/#definePXOVER0.8/*probabilityofcrossover雜交概率*/#definePMUTATION0.15/*probabilityofmutation變異概率*/#defineTRUE1#defineFALSE0intgeneration;/*currentgenerationno.當前基因個數(shù)*/intcur_best;/*bestindividual最優(yōu)個體*/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*///以下是一些函數(shù)聲明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*///隨機數(shù)產(chǎn)生函數(shù)doublerandval(doublelow,doublehigh){doubleval;val=((double)(rand()%1000)/1000.0)*(high-low)+low;return(val);/*Evaluationfunction:Thistakesauserdefinedfunction.*//*Eachtimethisischanged,thecodehastoberecompiled.*//*Thecurrentfunctionis:x[1]A2-x[1]*x[2]+x[3]*///評價函數(shù),可以由用戶自定義,該函數(shù)取得每個基因的適應度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*///搜尋杰出個體函數(shù):找出最好和最壞的個體。//如果某代的最好個體比前一代的最好個體要壞,那么后者將會取代當前種群的最壞個體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*/〃如果新種群中的最好個體比前一代的最好個體要強的話,那么就把新種群的最好個體拷貝出來?!ǚ駝t就用前一代的最好個體取代這次的最壞個體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*///選擇函數(shù):用于最大化合并杰出模型的標準比例選擇,保證最優(yōu)秀的個體得以生存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*///雜交函數(shù):選擇兩個個體來雜交,這里用單點雜交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);elseone=mem;}}}/*Crossover:performscrossoverofthetwoselectedparents.*/voidXover(intone,inttwo){inti;intpoint;/*crossoverpoint*//*selectcrossoverpoint*/if(NVARS>1){if(NVARS==2)point=1;elsepoint=(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*/〃變異函數(shù):被該函數(shù)選中后會使得某一變量被一個隨機的值所取代voidmutate(void){inti,j;doubleIbound,hbound;doublex;for(i=0;i<POPSIZE;i++)for(j=0;j<NVARS;j++){x=rand()%1000/1000.0;if(x<PMUTATION){/*findtheboundsonthevariabletobemutated確定*/Ibound=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平均值的平方乘個數(shù)*/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

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論