资源描述:
《遗传算法c程序.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、include#include#include#include"graph.c"/*全局变量*/structindividual/*个体*/{unsigned*chrom;/*染色体*/doublefitness;/*个体适应度*/doublevarible;/*个体对应的变量值*/intxsite;/*交叉位置*/intparent[2];/*父个体*/int*utility;/*特定数据指针变量*/};structbestever/*最佳个体*/{unsigned*chrom;/*最佳个体染色体*/doublefitn
2、ess;/*最佳个体适应度*/doublevarible;/*最佳个体对应的变量值*/intgeneration;/*最佳个体生成代*/};structindividual*oldpop;/*当前代种群*/structindividual*newpop;/*新一代种群*/structbesteverbestfit;/*最佳个体*/doublesumfitness;/*种群中个体适应度累计*/doublemax;/*种群中个体最大适应度*/doubleavg;/*种群中个体平均适应度*/doublemin;/*种群中个体最小适应度*/floatpcross;/*交叉概率*/floa
3、tpmutation;/*变异概率*/intpopsize;/*种群大小*/intlchrom;/*染色体长度*/intchromsize;/*存储一染色体所需字节数*/intgen;/*当前世代数*/intmaxgen;/*最大世代数*/intrun;/*当前运行次数*/intmaxruns;/*总运行次数*/intprintstrings;/*输出染色体编码的判断,0--不输出,1--输出*/intnmutation;/*当前代变异发生次数*/intncross;/*当前代交叉发生次数*//*随机数发生器使用的静态变量*/staticdoubleoldrand[55];sta
4、ticintjrand;staticdoublerndx2;staticintrndcalcflag;/*输出文件指针*/FILE*outfp;/*函数定义*/voidadvance_random();intflip(float);rnd(int,int);voidrandomize();doublerandomnormaldeviate();floatrandomperc(),rndreal(float,float);voidwarmup_random(float);voidinitialize(),initdata(),initpop();voidinitreport(),g
5、eneration(),initmalloc();voidfreeall(),nomemory(char*),report();voidwritepop(),writechrom(unsigned*);voidpreselect();voidstatistics(structindividual*);voidtitle(),repchar(FILE*,char*,int);voidskip(FILE*,int);intselect();voidobjfunc(structindividual*);intcrossover(unsigned*,unsigned*,unsigned*
6、,unsigned*);voidmutation(unsigned*);voidinitialize()/*遗传算法初始化*/{/*键盘输入遗传算法参数*/initdata();/*确定染色体的字节长度*/chromsize=(lchrom/(8*sizeof(unsigned)));if(lchrom%(8*sizeof(unsigned)))chromsize++;/*分配给全局数据结构空间*/initmalloc();/*初始化随机数发生器*/randomize();/*初始化全局计数变量和一些数值*/nmutation=0;ncross=0;bestfit.fitness
7、=0.0;bestfit.generation=0;/*初始化种群,并统计计算结果*/initpop();statistics(oldpop);initreport();}voidinitdata()/*遗传算法参数输入*/{charanswer[2];setcolor(9);disp_hz16("种群大小(20-100):",100,150,20);gscanf(320,150,9,15,4,"%d",&popsize);if((popsize%2)!=0){fprintf(o