yx2函数问题.docx

上传人:b****5 文档编号:7331888 上传时间:2023-01-23 格式:DOCX 页数:11 大小:19.03KB
下载 相关 举报
yx2函数问题.docx_第1页
第1页 / 共11页
yx2函数问题.docx_第2页
第2页 / 共11页
yx2函数问题.docx_第3页
第3页 / 共11页
yx2函数问题.docx_第4页
第4页 / 共11页
yx2函数问题.docx_第5页
第5页 / 共11页
点击查看更多>>
下载资源
资源描述

yx2函数问题.docx

《yx2函数问题.docx》由会员分享,可在线阅读,更多相关《yx2函数问题.docx(11页珍藏版)》请在冰豆网上搜索。

yx2函数问题.docx

yx2函数问题

遗传算法,解决y=x^2x属于[0,31]的最大值问题。

C言语

#include

#include

#include

typedef struct 

{

 int code;  //染色体

 int degree;//适应度

}Indi;

Indi group[40];//种群规模为40

void Judge(Indi &x)

{

  x.degree=x.code*x.code;

}

int happened(double p)//发生一个p=0~1间概率的事件

{

 return rand()<(int)(p*RAND_MAX);

}

void Cross(Indi &x,Indi &y)//交叉操作

{

 Indi z,z1;

 int temp,temp1;

 temp=x.code&0x3;

 temp1=y.code&0x3;

 z.code=x.code-temp+temp1;

 z1.code=y.code-temp1+temp;

 Judge(z);

 Judge(z1); 

 if(x.degree

 {

  if(z.degree>=x.degree) //如果新个体不如双亲,淘汰之

      x=z;

 }

 else

 {

  if(z.degree>=y.degree)

  y=z;

 }

  if(x.degree

 {

  if(z1.degree>=x.degree) //如果新个体不如双亲,淘汰之

      x=z1;

 }

 else

 {

  if(z1.degree>=y.degree)

  y=z1;

 }

}

void main()

{

 Indi indidest;

 int i,j,best,x,y,c;

 int sum,strick,SUM=0;

 static int n=0;

 srand(time(NULL));

 for(i=0;i<40;++i)//随机得到初始种群

 {

  group[i].code=rand()%32;

  Judge(group[i]);

 }

 for(i=1;i<=10;++i)//固定进化10代

 {

  for(sum=0,best=0,j=0;j<40;++j)

  {

   sum+=group[j].degree;//求总的适应度sum

   if(group[j].degree>group[best].degree)

   {

     best=j;//求当前最优个体

   }

  }

  printf("第%2d代中 最优个体为 %d  (%d) 平均适应度为 %10f\n",

   i,group[best].code,group[best].degree,sum/40.0);

  for(c=40;c;--c)

  {

   strick=(int)((float)rand()/RAND_MAX*sum);  //赌盘中的色子,选择个体x,y

   for(x=0;x<40&&strick>=group[x].degree;++x)

    strick-=group[x].degree;

   strick=(int)((float)rand()/RAND_MAX*sum);

   for(y=0;y<40&&strick>=group[y].degree;++y)

    strick-=group[y].degree;

   if(happened(0.9))

    Cross(group[x],group[y]);//交叉

  }

 }

}

一个非常简单的遗传算法源代码,是由DenisCormier(NorthCarolinaStateUniversity)开发的,SitaS.Raghavan(UniversityofNorthCarolinaatCharlotte)修正。

代码保证尽可能少,实际上也不必查错。

对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。

注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。

该系统使用比率选择、精华模型、单点杂交和均匀变异。

如果用Gaussian变异替换均匀变异,可能得到更好的效果。

代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。

读者可以从ftp.uncc.edu,目录coe/evol中的文件prog.c中获得。

要求输入的文件应该命名为‘gadata.txt’;系统产生的输出文件为‘galog.txt’。

输入的文件由几行组成:

数目对应于变量数。

且每一行提供次序——对应于变量的上下界。

如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。

/**************************************************************************/

/*Thisisasimplegeneticalgorithmimplementationwherethe*/

/*evaluationfunctiontakespositivevaluesonlyandthe*/

/*fitnessofanindividualisthesameasthevalueofthe*/

/*objectivefunction*/

/**************************************************************************/

#include

#include

#include

/*Changeanyoftheseparameterstomatchyourneeds*/

#definePOPSIZE50/*populationsize*/

#defineMAXGENS1000/*max.numberofgenerations*/

#defineNVARS3/*no.ofproblemvariables*/

#definePXOVER0.8/*probabilityofcrossover*/

#definePMUTATION0.15/*probabilityofmutation*/

#defineTRUE1

#defineFALSE0

intgeneration;/*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;*/

/*replacesthe*/

/*oldgeneration*/

/*Declarationofproceduresusedbythisgeneticalgorithm*/

voidinitialize(void);

doublerand()val(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'.Itrand()omlygeneratesvalues*/

/*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

{

fscanf(infile,"%lf",&lbound);

fscanf(infile,"%lf",&ubound);

for(j=0;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]=rand()val(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

{

for(i=0;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

{

if(population[mem].fitness>population[POPSIZE].fitness)

{

cur_best=mem;

population[POPSIZE].fitness=population[mem].fitness;

}

}

/*oncethebestmemberinthepopulationisfound,copythegenes*/

for(i=0;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

{

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

population[POPSIZE].gene[i]=population[best_mem].gene[i];

population[POPSIZE].fitness=population[best_mem].fitness;

}

else

{

for(i=0;i

population[worst_mem].gene[i]=population[POPSIZE].gene[i];

population[worst_mem].fitness=population[POPSIZE].fitness;

}

}

/**************************************************************/

/*Selectionfunction:

Standardproportionalselect()ionfor*/

/*maximizationproblemsincorporatingelitistmodel-makes*/

/*surethatthebestmembersurvives*/

/**************************************************************/

voidselect()(void)

{

intmem,i,j,k;

doublesum=0;

doublep;

/*findtotalfitnessofthepopulation*/

for(mem=0;mem

{

sum+=population[mem].fitness;

}

/*calculaterelativefitness*/

for(mem=0;mem

{

population[mem].rfitness=population[mem].fitness/sum;

}

population[0].cfitness=population[0].rfitness;

/*calculatecumulativefitness*/

for(mem=1;mem

{

population[mem].cfitness=population[mem-1].cfitness+

population[mem].rfitness;

}

/*finallyselectsurvivorsusingcumulativefitness.*/

for(i=0;i

{

p=rand()%1000/1000.0;

if(p

newpopulation[i]=population[0];

else

{

for(j=0;j

if(p>=population[j].cfitness&&

p

newpopulation[i]=population[j+1];

}

}

/*onceanewpopul

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 经管营销 > 销售营销

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1