koorio.com
海量文库 文档专家
当前位置:首页 >> 数学 >>

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=x^2函数问题
推荐相关:

y=x^2函数问题

y=x^2函数问题_数学_高中教育_教育专区。遗传算法,解决 y=x^2 x 属于[0,31] 的最大值问题。 C 言语 #include<stdio.h> #include #include<stdlib.h>...


matlab作业题答案

作业题 1 求函数在指定点的导数值 x 0 x2 2 x3 6x f ? x ? ? 1 2...(y) Dy = exp(x)/cos(x) + (exp(x)*sin(x))/cos(x)^2 4)错误!...


函数y=ax^2的图象与性质练习题

函数y=ax^2的图象与性质练习题_数学_初中教育_教育专区。练习二 1、填空: (1)抛物线 y ? y 随 x 的增大而增大, 当x (2)抛物线 y ? ? 函数 y ? a...


matlab课后习题解答第二章

如要投诉违规内容,请到百度文库投诉中心;如要提出功能问题或意见建议,请点击此处...函数 y5=subs(y,x,sym('4.5')) ezplot(y,[0,2*pi]) y = sinint(x...


MATLAB作业2 参考答案

( x ? 5)2 x ?5 y ?2 y ? 0 ( x ? y )e 【求解】极限问题可以...e x , (2) atan y ? ln( x 2 ? y 2 ) x 【求解】由求导函数diff...


MATLAB上级练习题

2 8 4 8 5 0 6 2、有一函数 f(x,y)=x^2+sinxy+2y,写一程序,输入...陈酒出售的最佳时机问题 某酒厂有批新酿的好酒,如果现在就出售,可得总收入 R0...


数学建模选修课第二次作业

用实际问题的实测数据等来检验该数学模型; 、多项式插值由函数 y=sin x 在三点 0,π/4,π/2 处的函数值,构造次插值多项式 P2(x), 计算 sin(π/8)...


二次函数y=a(x-h)2 练习题

_. 1 2 3、 (1)将抛物线 y=- (x-1) 向右平移 2 个单位后,得到的抛物线解析式为 3 1 2 (2)将抛物线 y=- (x-4) 向 3 2 11、 函数 y ...


题目e23b0ad9ad51f01dc281f15b

正确答案 解析 解:∵x>2,∴x-2>0. ∴函数y=x+=(x-2)++2+2=2+2,当且仅当x=+2时取等号. ∴函数y=x+(x>2)的最小值是. 故答案为:.最新...

网站首页 | 网站地图
All rights reserved Powered by 酷我资料网 koorio.com
copyright ©right 2014-2019。
文档资料库内容来自网络,如有侵犯请联系客服。zhit325@126.com