C + + Genetic algorithm class file instance analysis _c language

Source: Internet
Author: User
Tags diff rand

A class file instance of a genetic algorithm implemented by C + + is described in this paper. In general, genetic algorithm can solve many problems, I hope this article in the C + + genetic algorithm class file, can help you solve more problems, and the code in order to facilitate the reader better understanding, but added a rich annotation content, is a novice learning genetic algorithm rare reference code.

The specific code looks like this:

#include "stdafx.h" #include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #
include<ctime>//converts the date and time to a string using namespace std; 
Parametes setting #define popsize//population size #define Maxgens 1000//max number of generation #define NVARS 2//no problem variables #define PXOVER 0.75//probalility of crossover #define Pmutation 0.15//p Robalility of mutation #define TRUE 1 #define FALSE 0 #define LBOUND 0 #define UBOUND #define STOP 0.001 int ge     Neration;      Current generation no int cur_best;      
Best individual double diff;      FILE *galog;   An output file struct genotype {double gene[nvars];  A string of variables gene variable double upper[nvars];  Individual ' s variables upper bound gene variable value on the correct boundary double lower[nvars];     Individual ' s batiables lower bound gene variables were evaluated by double fitness;    Individual ' s fitness individual adaptive value double rfitness; Relative fitness individual adaptive value proportional to population adaptation double CFitness;
Curmulation Fitness The cumulative proportion of individual adaptation values}; 
struct genotype population[popsize+1]; Population Current Population population[popsize] is used to store individual optimal values and to assume that the optimal individual can survive//in some genetic algorithms the optimal value individual does not necessarily survive struct genotype newpopulation[ POPSIZE+1]; New population replaces the old generation population/*declaration of procedures used by the gentic algorithm*/void initial          Ize (void);      initialization function Double randval (double,double);  Random function Double funtion (double x1,double x2);          The objective function void evaluate (void);        evaluation function void keep_the_best (void);            Preserving the optimal individual void elitist (void);
 The optimal value of current population and descendant population is void select (void);          void crossover (void);      Gene recombination function void swap (double *,double *);            commutative function void mutate (void);          Gene mutation function double (void);
   Data logging function void Initialize (void) {int i,j; 
        for (i=0;i<nvars;i++) {for (j=0;j<popsize+1;j++) {if (!i) {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]=randval (Population[j].lower[i],population[j].upper[i]); }}//***************************************************************************//Random value generator: Generates a value within bounds//*************************************************************************** double
   Randval (double low,double high) {double Val;
  Val= (Double) (rand ()%10000)/10000) * (high-low) +low;
 return Val; //target function double funtion (double x,double y) {double result1=sqrt (x*x+y*y) +sqrt ((x-12) * (x-12) +y*y) +sqrt ((x-8) * (x-8) + (y
  6) * (y-6));
return RESULT1; }//***************************************************************************//Evaluation Function:evaluate the Individual ' s fitness. The evaluation function gives the individual adaptive value//each time the function is changes,the code has to be Recompl//***********************
  void Evaluate (void) {int mem; INT I;
  Double X[nvars];
    for (mem=0;mem<popsize;mem++) {for (i=0;i<nvars;i++) x[i]=population[mem].gene[i]; Population[mem].fitness=funtion (x[0],x[1]);//target function value as adaptive value}}//************************************************** Keep_the_best function:this function keeps track of the best member of the Popula
tion.
 Find the individual optimal value in a population and move it to the last//***************************************************************************************
   void Keep_the_best () {int mem;
   int i;
   cur_best=0;
       for (mem=0;mem<popsize;mem++)//Find the highest fit value individual {if (population[mem].fitness<population[cur_best].fitness) {      
    Cur_best=mem; }///Copy the best individual to population[posize] if (population[cur_best].fitness<=population[popsize].fitness| | POPULATION[POPSIZE].FITNESS&LT;1)//To prevent the occurrence of genetic degeneration of the population so as to preserve the historical optimal individual {population[popsize].fitness=population[cur_best].
    Fitness for (i=0;i<nvars;i++) population[popsize].gene[i]=population[Cur_best].gene[i]; }//***************************************************************************//last in the array.  If the best individual from the new populatin are 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 FR
 Om the previous generation. To prevent the degradation of population optimal value//***************************************************************************
  void elitist () {int i;
  Double best,worst;//Adaptive value int best_mem,worst_mem;//serial number best_mem=worst_mem=0; best=population[best_mem].fitness;//Maximum Adaptive value initialization worst=population[worst_mem].fitness;//minimum adaptive value initialization for (i=1;i<popsize
      i++)//Find the highest and lowest adaptive value algorithm to be improved {if (population[i].fitness<best) {best=population[i].fitness;
     Best_mem=i;
      } if (Population[i].fitness>worst) {worst=population[i].fitness;
    Worst_mem=i; } if (best<=population[popsize). Fitness)//assignment {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; }}//***************************************************************************//Select Function:Standard Proportional selection for maximization problems//incorporating elitist model--makes sure. Select the function and produce a descendant//*************************************************************************** void select (void) {int mem,i
   , J;
   Double sum=0;
   Double p;
   for (mem=0;mem<popsize;mem++)//all fit values sum {sum+=population[mem].fitness; for (mem=0;mem<popsize;mem++) {population[mem].rfitness=population[mem].fitness/sum;//personally think it's better to build a population class to see sum as a class Member} POPULATION[0].CFITNESS=POPULATION[0].RFITNEss
  for (mem=1;mem<popsize;mem++) {population[mem].cfitness=population[mem-1].cfitness+population[mem].rfitness;
     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].c
     Fitness) newpopulation[i]=population[j+1];
The for (i=0;i<popsize;i++)//descendant becomes the parent generation Population[i]=newpopulation[i]; }//***************************************************************************//Crossover:performs Crossover of
 The selected parents.
   void Xover (int one,int two)//gene recombination function {
  int i;
  int point;
    if (nvars>1) {if (nvars==2) point=1;
    Else point= (rand ()% (NVARS-1)) +1;//two all reorganized? for (i=0;i<point;i++)//Only the first gene recombination needs to be improved swap (&population[one].genE[i],&population[two].gene[i]); }//***************************************************************************//swapp:a Swap procedure The helps In swappling 2 variables//*************************************************************************** void swap (
  Double *x,double *y) {Double temp;
  Temp=*x;
  *x=*y;
*y=temp; }//***************************************************************************//Crossover Function:select two
 Parents that take part in the crossover. Implements a single point corssover. Hybridization function//**********************************************************************
   void Crossover (void) {int mem,one;
   int first=0;
  Double X;
    for (Mem=0;mem<popsize;++mem) {X=rand ()%1000/1000.0;
      if (x<pxover) {++first;
      if (first%2==0)//select hybrid individual to be improved on hybridization in fact, it is often the strong and the strong hybridization here did not consider the selection of male and female and hybrid objects xover (ONE,MEM);
 else One=mem; }
  }
 }
//**********************************************************************Mutation function:random Uniform mutation.a variable selected for Mutation//mutation function The fact gene mutation often has some localized//is replace
 D by a random value between lower and upper bounds of the variables.
   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) {lbound=population[i].lower[j];
         HBOUND=POPULATION[I].UPPER[J];
       Population[i].gene[j]=randval (Lbound,hbound); }}}//***************************************************************************//Report function:Reports progr
 ESS of the simulation.
  Double (void) {int i;
  The optimal adaptive value of double best_val;//population avg;//Average individual adaptive value//double StdDev;
  The individual adaptive value of double sum_square;//population was squared and//double square_sum;The population adaptation value of double sum;//sum=0.0;
  sum_square=0.0;
     for (i=0;i<popsize;i++) {sum+=population[i].fitness;
   sum_square+=population[i].fitness*population[i].fitness;
   avg=sum/(double) popsize;
   square_sum=avg*avg* (double) popsize;
  Stddev=sqrt ((sum_square-square_sum)/(POPSIZE-1));
  best_val=population[popsize].fitness; fprintf (Galog,%6d%6.3f%6.3f%6.3f%6.3f%6.3f\n), generation,best_val,population[popsize].gene[0],population[
  Popsize].gene[1],avg,sum);
 return avg; }//***************************************************************************//main Function:Each generation Involves selecting the best members,performing//crossover & mutation and then evaluating the resulting
 Til the//terminating condition is satisfied.
   void Main (void) {int i;
   Double temp;
   Double Temp1;
   if ((Galog=fopen ("Data.txt", "W")) ==null) {exit (1); } generation=1;
  Srand (Time (NULL));//Generate random number fprintf (Galog, "value x1 x2 avg sum_value\n");
  printf ("Generation best Average standard\n");
  Initialize ();
  Evaluate ();
  Keep_the_best (); Temp=report ()//record, the average adaptive value of the previous generation to do {select ();//filter crossover ()//hybrid mutate ();//Variation Evalua
     TE ()///Evaluate Keep_the_best ();//elitist ();
     Temp1=report ();
     Diff=fabs (TEMP-TEMP1);//Find the absolute value temp=temp1 of the floating-point number x;
   generation++;
   }while (Generation<maxgens&&diff>=stop);
   fprintf (Galog, "N ' simulation completed\n");
   fprintf (Galog, "best member:\n");
   printf ("\nbest member:\ngeneration:%d\n", Generation);
     for (i=0;i<nvars;i++) {//fprintf (galog, "\ n var (%d) =%3.3f", I,population[popsize].gene[i]);
   printf ("x%d=%3.3f\n", I,population[popsize].gene[i]);
   }//fprintf (Galog, "Best fitness=%3.3f", population[popsize].fitness);
   Fclose (Galog);
 printf ("\nbest fitness=%3.3f\n", population[popsize].fitness);

 }

Interested readers can test the code, hoping to learn from the C + + algorithm can help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.