当前位置:首页 >> 数学 >>

y=x^2函数问题


遗传算法,解决 y=x^2 x 属于[0,31] 的最大值问题。 C 言语
#include<stdio.h> #include<time.h> #include<stdlib.h> 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<y.degree) { if(z.degree>=x.degree) //如果新个体不如双亲,淘汰之 x=z; } else { if(z.degree>=y.degree) y=z; } if(x.degree<y.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]);//交叉 } } }

一个非常简单的遗传算法源代码,是由 Denis Cormier (North Carolina State University)开 发的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。代码保证尽可能 少, 实际上也不必查错。 对一特定的应用修正此代码, 用户只需改变常数的定义并且定义“评 价函数”即可。注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体 的适应值之间没有区别。该系统使用比率选择、精华模型、单点杂交和均匀变异。如果用 Gaussian 变异替换均匀变异,可能得到更好的效果。代码没有任何图形,甚至也没有屏幕 输出,主要是保证在平台之间的高可移植性。读者可以从 ftp.uncc.edu,目录 coe/evol 中的 文件 prog.c 中获得。要求输入的文件应该命名为?gadata.txt?;系统产生的输出文件为 ?galog.txt?。输入的文件由几行组成:数目对应于变量数。且每一行提供次序——对应于变 量的上下界。如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。

/**************************************************************************/ /* This is a simple genetic algorithm implementation where the */ /* evaluation function takes positive values only and the /* fitness of an individual is the same as the value of the /* objective function /**************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> /* Change any of these parameters to match your needs */ #define POPSIZE 50 #define MAXGENS 1000 #define NVARS 3 #define PXOVER 0.8 #define PMUTATION 0.15 #define TRUE 1 #define FALSE 0 int generation; int cur_best; FILE *galog; /* current generation no. */ /* best individual */ /* an output file */ /* population size */ /* max. number of generations */ /* no. of problem variables */ /* probability of crossover */ /* probability of mutation */ */ */ */

struct genotype /* genotype (GT), a member of the population */ {

double gene[NVARS]; double fitness; double upper[NVARS]; double lower[NVARS]; double rfitness; double cfitness; };

/* a string of variables */ /* GT's fitness */ /* GT's variables upper bound */ /* GT's variables lower bound */ /* relative fitness */ /* cumulative fitness */

struct genotype population[POPSIZE+1];

/* population */ /* replaces the */ /* old generation */

struct genotype newpopulation[POPSIZE+1]; /* new population; */

/* Declaration of procedures used by this genetic algorithm */ void initialize(void); double rand()val(double, double); void evaluate(void); void keep_the_best(void); void elitist(void); void select()(void); void crossover(void); void Xover(int,int); void swap(double *, double *); void mutate(void); void report(void); /***************************************************************/ /* Initialization function: Initializes the values of genes /* all fitness values for each member of the population. It /* reads upper and lower bounds of each variable from the /* input file `gadata.txt'. It rand()omly generates values /* population. The format of the input file `gadata.txt' is /* var1_lower_bound var1_upper bound /* var2_lower_bound var2_upper bound ... /***************************************************************/ */ */ */ */ */ */ */ /* within the variables bounds. It also initializes (to zero) */

/* between these bounds for each gene of each genotype in the */

void initialize(void) { FILE *infile; int i, j; double lbound, ubound; if ((infile = fopen("gadata.txt","r"))==NULL) { fprintf(galog,"\nCannot open input file!\n"); exit(1); } /* initialize variables within the bounds */ 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] = rand()val(population[j].lower[i], population[j].upper[i]); } } fclose(infile); } /***********************************************************/ /* Random value generator: Generates a value within bounds */ /***********************************************************/

double randval(double low, double high) { double val; val = ((double)(rand()%1000)/1000.0)*(high - low) + low; return(val); } /*************************************************************/ /* Evaluation function: This takes a user defined function. */ /* Each time this is changed, the code has to be recompiled. */ /* The current function is: x[1]^2-x[1]*x[2]+x[3] /*************************************************************/ void evaluate(void) { int mem; int i; double x[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_best function: This function keeps track of the /* best member of the population. Note that the last entry in */ /* the array Population holds a copy of the best individual /***************************************************************/ void keep_the_best() { int mem; */ */ */

int i; cur_best = 0; /* stores the index of the best individual */ for (mem = 0; mem < POPSIZE; mem++) { if (population[mem].fitness > population[POPSIZE].fitness) { cur_best = mem; population[POPSIZE].fitness = population[mem].fitness; } } /* once the best member in the population is found, copy the genes */ for (i = 0; i < NVARS; i++) population[POPSIZE].gene[i] = population[cur_best].gene[i]; } /****************************************************************/ /* Elitist function: The best member of the previous generation */ /* is stored as the last in the array. If the best member of */ /* the current generation is worse then the best member of the */ /* previous generation, the latter one would replace the worst */ /* member of the current population /****************************************************************/ void elitist() { int i; double best, worst; /* best and worst fitness values */ int best_mem, worst_mem; /* indexes of the best and worst member */ 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; } } } /* if best individual from the new population is better than */ /* the best individual from the previous population, then /* copy the best from the new population; else replace the /* worst individual from the current population with the /* best one from the previous generation 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; } } /**************************************************************/ /* Selection function: Standard proportional select()ion for /* sure that the best member survives /**************************************************************/ void select()(void) { int mem, i, j, k; double sum = 0; double p; /* find total fitness of the population */ for (mem = 0; mem < POPSIZE; mem++) { sum += population[mem].fitness; } /* calculate relative fitness */ for (mem = 0; mem < POPSIZE; mem++) { population[mem].rfitness = population[mem].fitness/sum; } population[0].cfitness = population[0].rfitness; /* calculate cumulative fitness */ for (mem = 1; mem < POPSIZE; mem++) { population[mem].cfitness = population[mem-1].cfitness + population[mem].rfitness; } /* finally select survivors using cumulative fitness. */ */ */ /* maximization problems incorporating elitist model - makes */

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]; } } /* once a new population is created, copy it back */ for (i = 0; i < POPSIZE; i++) population[i] = newpopulation[i]; } /***************************************************************/ /* Crossover selection: selects two parents that take part in */ /* the crossover. Implements a single point crossover /***************************************************************/ void crossover(void) { int i, mem, one; int first = 0; /* count of the number of members chosen */ double x; 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: performs crossover of the two selected parents. */ /**************************************************************/ void Xover(int one, int two) { int i; int point; /* crossover point */ /* select crossover point */ 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: A swap procedure that helps in swapping 2 variables */ /*************************************************************/ void swap(double *x, double *y) { double temp; temp = *x; *x = *y;

*y = temp; } /**************************************************************/ /* Mutation: Random uniform mutation. A variable selected for */ /* mutation is replaced by a random value between lower and /* upper bounds of this variable /**************************************************************/ void mutate(void) { int i, j; double lbound, hbound; double x; for (i = 0; i < POPSIZE; i++) for (j = 0; j < NVARS; j++) { x = rand()%1000/1000.0; if (x < PMUTATION) { /* find the bounds on the variable to be mutated */ lbound = population[i].lower[j]; hbound = population[i].upper[j]; population[i].gene[j] = randval(lbound, hbound); } } } /***************************************************************/ /* Report function: Reports progress of the simulation. Data /* dumped into the output file are separated by commas /***************************************************************/ 。。。。。 代码太多 你到下面呢个网站看看吧 */ */ */ */

void main(void)

{ int i; if ((galog = fopen("galog.txt","w"))==NULL) { exit(1); } generation = 0; fprintf(galog, "\n generation best average standard \n"); fprintf(galog, " number initialize(); evaluate(); keep_the_best(); while(generation<MAXGENS) { generation++; select(); crossover(); mutate(); report(); evaluate(); elitist(); } fprintf(galog,"\n\n Simulation completed\n"); fprintf(galog,"\n Best member: \n"); for (i = 0; i < NVARS; i++) { fprintf (galog,"\n var(%d) = %3.3f",i,population[POPSIZE].gene[i]); } fprintf(galog,"\n\n Best fitness = %3.3f",population[POPSIZE].fitness); fclose(galog); printf("Success\n"); } value fitness deviation \n");


相关文章:
...学习时遇到这样一个问题:定义:如果二次函数y=a1x2+b...
小明在课外学习时遇到这样一个问题:定义:如果二次函数y=a1x2+b1x+c1(a1≠0,a1,b1,c1是常数)与y=a2x2+b2x+c2(a2≠0,a2,b2,c2是常数)满足a1+a2=0,...
Matlab上机练习二答案
(提示: 用 polyval 函数) >> x=linspace(2,8,100); >> y=polyval([1 ...关于排序问题 a=rand(4,5); 随机生成 4*5 的矩阵 sort(a); 按列排序,...
函数y=x2的图象
函数y=x2的图象_数学_自然科学_专业资料。函数 y=x2 的图象甲、乙两位同学在学习函数的图象之前有这样一段对话 .甲:我 能猜出 y=x2 的图象的大致形...
遗传算法求解y=x2 - 副本
下面我以一个实例来详细表述遗传算法的过程 例:求下述二元函数的最大值: y ? x2 x ?[0,31] 1、编码: 用遗传算法求解问题时,不是对所求解问题的实际决策...
函数y=ax^2+c的图象与性质练习题
函数y=ax^2+c的图象与性质练习题_数学_高中教育_教育专区。练习三 1、抛物线 y ? ?2x 2 ? 3 的开口 大而增大, 当 x 2、将抛物线 y ? 线的解析式为...
当x___时,函数y=x2+2随x的增大而增大,当x___时,函数y=x...
填空题 数学 函数的性质 当x___时,函数y=x2+2随x的增大而增大,当x___时,函数y=x2+2随x的增大而减小. 正确答案及...
函数y=x(x2++)的导数为___._答案_百度高考
函数y=x(x2++)的导数为___. 正确答案及相关解析 正确答案 y′=3x2- 解析 解:由于函数y=x(x2++)=x3+1+ 则该函数的导数为y′=3x2-. 故答案...
Matlab习题与答案2
(x); plot(x,y1,x,y2) plot 函数还可以为 plot(x,y1,x,y2,x,y3,...曲面的网格图最突出的优点是:它较 好地解决了实验数据在三维空间的可视化问题。...
作函数y=x2的图象
如要投诉违规内容,请到百度文库投诉中心;如要提出功能问题或意见建议,请点击此处进行反馈。 作函数y=x2的图象 作函数y=x2的图象作函数y=x2的图象隐藏>> 备课...
§2.2.3 二次函数y=a(x-h)^2的图象和性质
… 根据 y=(x+2) 的图象回答下列问题: (1)开口方向向___; (2)对称轴为___; (3)顶点坐标为___; (4)当 x___时,函数 y 有最___值为___; (...
更多相关标签: