版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
一個(gè)簡(jiǎn)單實(shí)用的遺傳算法c程序(轉(zhuǎn)載)C++2009-07-2823:09:03閱讀418評(píng)論0字號(hào):大中小這是一個(gè)非常簡(jiǎn)單的遺傳算法源代碼,是由 DenisCormier(NorthCarolinaStateUniversity)開(kāi)發(fā)的,SitaS.Raghavan(UniversityofNorthCarolinaatCharlotte)修正。代碼保證盡可能少,實(shí)際上也不必查錯(cuò)。 對(duì)一特定的應(yīng)用修正此代碼, 用戶只需改變常數(shù)的定義并且定義評(píng)價(jià)函數(shù)”即可。注意代碼的設(shè)計(jì)是求最大值, 其中的目標(biāo)函數(shù)只能取正值; 且函數(shù)值和個(gè)體的適應(yīng)值之間沒(méi)有區(qū)別。 該系統(tǒng)使用比率選擇、精華模型、單點(diǎn)雜交和均勻變異。如果用Gaussian變異替換均勻變異,可能得到更好的效果。代碼沒(méi)有任何圖形,甚至也沒(méi)有屏幕輸出,主要是保證在平臺(tái)之間的高可移植性。 讀者可以從,目錄coe/evol中的文件prog.c中獲得。要求輸入的文件應(yīng)該命名為 ,gadata.txt?;系統(tǒng)產(chǎn)生的輸出文件為,galog.txt?。輸入的文件由幾行組成:數(shù)目對(duì)應(yīng)于變量數(shù)。且每一行提供次序 對(duì)應(yīng)于變量的上下界。如第一行為第一個(gè)變量提供上下界,第二行為第二個(gè)變量提供上下界,等等。/**************************************************************************//*Thisisasimplegeneticalgorithmimplementationwherethe*/TOC\o"1-5"\h\z/*evaluationfunctiontakespositivevaluesonlyandthe *//*fitnessofanindividualisthesameasthevalueofthe *//*objectivefunction *//**************************************************************************/#include<stdio.h>#include<stdlib.h>#include<math.h>/*Changeanyoftheseparameterstomatchyourneeds*/#definePOPSIZE50 /*populationsize*/#definePOPSIZE50 /*populationsize*//*max.numberofgenerations*//*max.numberofgenerations*//*no.ofproblemvariables*//*probabilityofcrossover*//*probabilityofmutation*/#defineMAXGENS1000#defineNVARS3#definePXOVER0.8#definePMUTATION0.15#defineTRUE1#defineFALSE0intgeneration;intcur_best;FILE*galog;/*currentgenerationno.*//*bestindividual*//*anoutputfile*/structgenotype/*genotype(GT),amemberofthepopulation*/{doublegene[NVARS];/*astringofvariables 一個(gè)變量字符串 */doublefitness;/*GT'sfitness適應(yīng)度*/doubleupper[NVARS];/*GT'svariablesupperbound 變量的上限*/doublelower[NVARS];/*GT'svariableslowerbound 變量的下限*/doublerfitness;/*relativefitness 相對(duì)適應(yīng)度*/doublecfitness;/*cumulativefitness 累計(jì)適應(yīng)度*/structgenotypepopulation[POPSIZE+1]; /*population*/structgenotypenewpopulation[POPSIZE+1];/*newpopulation;*//*replacesthe*//*oldgeneration*//*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);/***************************************************************/TOC\o"1-5"\h\z/*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]=Ibound;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[1F2-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[O].fitness;worst=population[O].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*/**********************************************************voidselect(void){intmem,i,j,k;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[O].cfitness=population[O].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[O].cfitness)newpopulation[i]=population[0];else{for(j=0;j<POPSIZE;j++)if(p>=population[j].cfitness&&
pvpopulation[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)inti,mem,one;intfirst0;/*countofthenumberofmemberschosen*/intfirstdoublex;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*/*//**************************************************************/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)doublesum; /*totalpopulationfitness*/doublesum; /*totalpopulationfitness*//*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*/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*//*conditionis
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024年財(cái)產(chǎn)分配:離婚股權(quán)清晰分割協(xié)議
- 蘇北四市(徐州、宿遷、淮安、連云港)2025屆高三第一次調(diào)研考試(一模)生物試卷(含答案)
- 2024移動(dòng)醫(yī)療APP開(kāi)發(fā)與推廣合同
- 2025年度博物館樓頂觀光平臺(tái)租賃合同3篇
- 2025年度夜店娛樂(lè)DJ藝人簽約管理合同3篇
- 2025年水電站行業(yè)發(fā)展前景分析:我國(guó)共有水電站8600余座
- 2024版家庭護(hù)理保姆雇傭合同樣本
- 2024環(huán)境檢測(cè)合同
- 2024年學(xué)生宿舍消防安全管理協(xié)議3篇
- 2024年車站自助咖啡機(jī)投放與運(yùn)營(yíng)合同3篇
- 2024時(shí)事政治考試題庫(kù)附參考答案(黃金題型)
- 中華人民共和國(guó)勞動(dòng)合同法全文下載
- GIS設(shè)備帶電補(bǔ)氣作業(yè)指導(dǎo)書
- 產(chǎn)品銷售合同的簽署方式
- 小學(xué)二年級(jí)除法口算1200道(81以內(nèi)整除)
- 2024年新“國(guó)九條”及配套政策要點(diǎn)解讀分析報(bào)告
- 2024-2029年中國(guó)大健康行業(yè)市場(chǎng)發(fā)展現(xiàn)狀分析及發(fā)展趨勢(shì)與投資戰(zhàn)略規(guī)劃報(bào)告
- 全國(guó)醫(yī)院數(shù)量統(tǒng)計(jì)
- 浙教版八年級(jí)上數(shù)學(xué)易錯(cuò)題
- 【基于雙因素理論的滴滴出行員工績(jī)效考核機(jī)制探析18000字(論文)】
- 2024水質(zhì)自動(dòng)監(jiān)測(cè)系統(tǒng)智慧站房建設(shè)技術(shù)指南
評(píng)論
0/150
提交評(píng)論