koorio.com

# y=x^2函数问题

#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]);//交叉 } } }

/**************************************************************************/ /* 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");

### 对于二元函数f(x,y)=x2+y2,原点(0,0)( )。 A.不是驻点 ...

[解析] 二元函数f(x,y)=x2+y2在原点(0,0)处函数值为0,而对任意 (x,y)≠(0,0),有0<x2+y2,所以f(0,0)<f(x,y),即原点(0,0)是极小值点...