遗传算法C++例子

来源:互联网 发布:巨化集团待遇知乎 编辑:程序博客网 时间:2024/06/06 13:10

遗传算法的具体已在前面的文章进行阐述,在此补充一个例子进行说明。

求函数极大值

F(X) = X[1]^2 - X[1]*X[2] + X[3]

其中

0 <= X[1] <= 5
0 <= X[2] <= 5
-2 <= X[3] <= 2

正解为[5,0,2]。

txt文本中的内容截图如下:

所表示的是各个变量的取值范围。第一列为所取的最小值,第二列为所取的最大值;每一行对应一个变量。

代码如下所示:

[cpp] view plain copy 在CODE上查看代码片派生到我的代码片
  1. # include <cstdlib>  
  2. #include <stdio.h>   
  3. # include <iostream>  
  4. # include <iomanip>  
  5. # include <fstream>  
  6. # include <iomanip>  
  7. # include <math.h>  
  8. # include <ctime>  
  9. # include <cstring>  
  10.   
  11. using namespace std;  
  12. //    MAXGENS is the maximum number of generations.  
  13. //    NVARS is the number of problem variables.  
  14. //    PMUTATION is the probability of mutation.  
  15. //    POPSIZE is the population size.   
  16. //    PXOVER is the probability of crossover.       
  17. # define POPSIZE 50//种群内个体数量  
  18. # define MAXGENS 1000//最大的迭代次数  
  19. # define NVARS 3//变量个数,即用以表示基因型的bit数  
  20. # define PXOVER 0.8//交换率  
  21. # define PMUTATION 0.15//突变率  
  22. //  
  23. //  Each GENOTYPE is a member of the population, with  
  24. //  gene: a string of variables,  
  25. //  fitness: the fitness  
  26. //  upper: the variable upper bounds,  
  27. //  lower: the variable lower bounds,  
  28. //  rfitness: the relative fitness,  
  29. //  cfitness: the cumulative fitness.  
  30. //  
  31. struct genotype  
  32. {  
  33.     double gene[NVARS];  
  34.     double fitness;  
  35.     double upper[NVARS];  
  36.     double lower[NVARS];  
  37.     double rfitness;  
  38.     double cfitness;  
  39. };  
  40.   
  41. struct genotype population[POPSIZE+1];  
  42. struct genotype newpopulation[POPSIZE+1];   
  43.   
  44. int main ( );  
  45. void crossover ( int &seed );//交叉操作。selects two parents for the single point crossover  
  46. void elitist ( );//stores the best member of the previous generation  
  47. void evaluate ( );//implements the user-defined valuation function  
  48. int i4_uniform_ab ( int a, int b, int &seed );//returns a scaled pseudorandom I4 between A and B  
  49. int Int_uniform_ab(int a, int b);//my own function to get a value between "a" and "b"  
  50. void initialize ( string filename, int &seed );//initializes the genes within the variables bounds  
  51. void keep_the_best ( );//keeps track of the best member of the population  
  52. void mutate ( int &seed );//performs a random uniform mutation  
  53. double r8_uniform_ab ( double a, double b, int &seed );//returns a scaled pseudorandom R8  
  54. double Dou_uniform_ab(double a, double b);//return a double value between "a" and "b"  
  55. void report ( int generation );//reports progress of the simulation  
  56. void selector ( int &seed );// is the selection function  
  57. double round(double number);//returns the integral value that is nearest to x, with halfway cases rounded away from zero  
  58. void timestamp ( );//prints the current YMDHMS date as a time stamp  
  59. void Xover ( int one, int two, int &seed );//performs crossover of the two selected parents  
  60.   
  61. //****************************************************************************80  
  62.   
  63. int main ( )  
  64. //  Discussion:  
  65. //  
  66. //    Each generation involves selecting the best   
  67. //    members, performing crossover & mutation and then   
  68. //    evaluating the resulting population, until the terminating   
  69. //    condition is satisfied     
  70. //  
  71. //    This is a simple genetic algorithm implementation where the   
  72. //    evaluation function takes positive values only and the   
  73. //    fitness of an individual is the same as the value of the   
  74. //    objective function.    
  75. {  
  76.     string filename = "simple_ga_input.txt";  
  77.     int generation;  
  78.     int i;  
  79.     int seed;  
  80.   
  81.     timestamp ( );  
  82.     cout << "\n";  
  83.     cout << "SIMPLE_GA:\n";  
  84.     cout << "  C++ version\n";  
  85.     cout << "  A simple example of a genetic algorithm.\n";  
  86.   
  87.     if ( NVARS < 2 )  
  88.     {  
  89.         cout << "\n";  
  90.         cout << "  The crossover modification will not be available,\n";  
  91.         cout << "  since it requires 2 <= NVARS.\n";  
  92.     }  
  93.   
  94.     seed = 123456789;  
  95.     srand((unsigned)time(NULL));   
  96.     initialize ( filename, seed );  
  97.   
  98.     evaluate ( );  
  99.   
  100.     keep_the_best ( );  
  101.   
  102.     for ( generation = 0; generation < MAXGENS; generation++ )  
  103.     {  
  104.         selector ( seed );  
  105.         crossover ( seed );  
  106.         mutate ( seed );  
  107.         report ( generation );  
  108.         evaluate ( );  
  109.         elitist ( );  
  110.     }  
  111.   
  112.     cout << "\n";  
  113.     cout << "  Best member after " << MAXGENS << " generations:\n";  
  114.     cout << "\n";  
  115.   
  116.     for ( i = 0; i < NVARS; i++ )  
  117.     {  
  118.         cout << "  var(" << i << ") = " << population[POPSIZE].gene[i] << "\n";  
  119.     }  
  120.   
  121.     cout << "\n";  
  122.     cout << "  Best fitness = " << population[POPSIZE].fitness << "\n";  
  123.     //  
  124.     //  Terminate.  
  125.     //  
  126.     cout << "\n";  
  127.     cout << "SIMPLE_GA:\n";  
  128.     cout << "  Normal end of execution.\n";  
  129.     cout << "\n";  
  130.     timestamp ( );  
  131.   
  132.     return 0;  
  133. }  
  134. //****************************************************************************80  
  135.   
  136. void crossover ( int &seed )  
  137. //    CROSSOVER selects two parents for the single point crossover.  
  138. //  Local parameters:  
  139. //  
  140. //    Local, int FIRST, is a count of the number of members chosen.  
  141. //  
  142. //  Parameters:  
  143. //  
  144. //    Input/output, int &SEED, a seed for the random number generator.  
  145. //  
  146. {  
  147.     const double a = 0.0;  
  148.     const double b = 1.0;  
  149.     int mem;  
  150.     int one;  
  151.     int first = 0;  
  152.     double x;  
  153.   
  154.     for ( mem = 0; mem < POPSIZE; ++mem )  
  155.     {  
  156.         //x = r8_uniform_ab ( a, b, seed );  
  157.         x = Dou_uniform_ab( a, b);  
  158.   
  159.         if ( x < PXOVER )  
  160.         {  
  161.             ++first;  
  162.   
  163.             if ( first % 2 == 0 )  
  164.             {  
  165.                 Xover ( one, mem, seed );  
  166.             }  
  167.             else  
  168.             {  
  169.                 one = mem;  
  170.             }  
  171.   
  172.         }  
  173.     }  
  174.     return;  
  175. }  
  176.   
  177. void elitist ( )  
  178. //    ELITIST stores the best member of the previous generation.  
  179. //  
  180. //  Discussion:  
  181. //  
  182. //    The best member of the previous generation is stored as   
  183. //    the last in the array. If the best member of the current   
  184. //    generation is worse then the best member of the previous   
  185. //    generation, the latter one would replace the worst member   
  186. //    of the current population.  
  187. //  Local parameters:  
  188. //  
  189. //    Local, double BEST, the best fitness value.  
  190. //  
  191. //    Local, double WORST, the worst fitness value.  
  192. //  
  193. {  
  194.     int i;  
  195.     double best;  
  196.     int best_mem;  
  197.     double worst;  
  198.     int worst_mem;  
  199.   
  200.     best = population[0].fitness;  
  201.     worst = population[0].fitness;  
  202.   
  203.     for ( i = 0; i < POPSIZE - 1; ++i )  
  204.     {  
  205.         if ( population[i+1].fitness < population[i].fitness )  
  206.         {  
  207.   
  208.             if ( best <= population[i].fitness )  
  209.             {  
  210.                 best = population[i].fitness;  
  211.                 best_mem = i;  
  212.             }  
  213.   
  214.             if ( population[i+1].fitness <= worst )  
  215.             {  
  216.                 worst = population[i+1].fitness;  
  217.                 worst_mem = i + 1;  
  218.             }  
  219.   
  220.         }  
  221.         else  
  222.         {  
  223.   
  224.             if ( population[i].fitness <= worst )  
  225.             {  
  226.                 worst = population[i].fitness;  
  227.                 worst_mem = i;  
  228.             }  
  229.   
  230.             if ( best <= population[i+1].fitness )  
  231.             {  
  232.                 best = population[i+1].fitness;  
  233.                 best_mem = i + 1;  
  234.             }  
  235.   
  236.         }  
  237.   
  238.     }  
  239.     //   
  240.     //  If the best individual from the new population is better than   
  241.     //  the best individual from the previous population, then   
  242.     //  copy the best from the new population; else replace the   
  243.     //  worst individual from the current population with the   
  244.     //  best one from the previous generation                       
  245.     //  
  246.     if ( population[POPSIZE].fitness <= best )  
  247.     {  
  248.         for ( i = 0; i < NVARS; i++ )  
  249.         {  
  250.             population[POPSIZE].gene[i] = population[best_mem].gene[i];  
  251.         }  
  252.         population[POPSIZE].fitness = population[best_mem].fitness;  
  253.     }  
  254.     else  
  255.     {  
  256.         for ( i = 0; i < NVARS; i++ )  
  257.         {  
  258.             population[worst_mem].gene[i] = population[POPSIZE].gene[i];  
  259.         }  
  260.         population[worst_mem].fitness = population[POPSIZE].fitness;  
  261.     }   
  262.   
  263.     return;  
  264. }  
  265.   
  266. void evaluate ( )  
  267. //    EVALUATE implements the user-defined valuation function  
  268. //  Discussion:  
  269. //  
  270. //    Each time this is changed, the code has to be recompiled.  
  271. //    The current function is:  x[1]^2-x[1]*x[2]+x[3]  
  272. {  
  273.     int member;  
  274.     int i;  
  275.     double x[NVARS+1];  
  276.   
  277.     for ( member = 0; member < POPSIZE; member++ )  
  278.     {  
  279.         for ( i = 0; i < NVARS; i++ )  
  280.         {  
  281.             x[i+1] = population[member].gene[i];  
  282.         }   
  283.         population[member].fitness = ( x[1] * x[1] ) - ( x[1] * x[2] ) + x[3];  
  284.     }  
  285.     return;  
  286. }  
  287.   
  288. int i4_uniform_ab ( int a, int b, int &seed )  
  289. //    I4_UNIFORM_AB returns a scaled pseudorandom I4 between A and B.  
  290. //  
  291. //  Discussion:  
  292. //  
  293. //    The pseudorandom number should be uniformly distributed  
  294. //    between A and B.  
  295. //  Parameters:  
  296. //  
  297. //    Input, int A, B, the limits of the interval.  
  298. //  
  299. //    Input/output, int &SEED, the "seed" value, which should NOT be 0.  
  300. //    On output, SEED has been updated.  
  301. //  
  302. //    Output, int I4_UNIFORM, a number between A and B.  
  303. //  
  304. {  
  305.     int c;  
  306.     const int i4_huge = 2147483647;  
  307.     int k;  
  308.     float r;  
  309.     int value;  
  310.   
  311.     if ( seed == 0 )  
  312.     {  
  313.         cerr << "\n";  
  314.         cerr << "I4_UNIFORM_AB - Fatal error!\n";  
  315.         cerr << "  Input value of SEED = 0.\n";  
  316.         exit ( 1 );  
  317.     }  
  318.     //  
  319.     //  Guarantee A <= B.  
  320.     //  
  321.     if ( b < a )  
  322.     {  
  323.         c = a;  
  324.         a = b;  
  325.         b = c;  
  326.     }  
  327.   
  328.     k = seed / 127773;  
  329.   
  330.     seed = 16807 * ( seed - k * 127773 ) - k * 2836;  
  331.   
  332.     if ( seed < 0 )  
  333.     {  
  334.         seed = seed + i4_huge;  
  335.     }  
  336.   
  337.     r = ( float ) ( seed ) * 4.656612875E-10;  
  338.     //  
  339.     //  Scale R to lie between A-0.5 and B+0.5.  
  340.     //  
  341.     r = ( 1.0 - r ) * ( ( float ) a - 0.5 )   
  342.         +         r   * ( ( float ) b + 0.5 );  
  343.     //  
  344.     //  Use rounding to convert R to an integer between A and B.  
  345.     //Returns the integral value that is nearest to x  
  346.     value = round ( r );//Vs2008中并没有此函数,需要自己实现。是最近取整  
  347.     //  
  348.     //  Guarantee A <= VALUE <= B.  
  349.     //  
  350.     if ( value < a )  
  351.     {  
  352.         value = a;  
  353.     }  
  354.     if ( b < value )  
  355.     {  
  356.         value = b;  
  357.     }  
  358.   
  359.     return value;  
  360. }  
  361. //my new design function of the distribution  
  362. int Int_uniform_ab(int a, int b)  
  363. {   int tmp;  
  364.     tmp = (rand() % (b-a+1))+ a;  
  365.     return tmp;  
  366.   
  367. }  
  368. //****************************************************************************80  
  369.   
  370. void initialize ( string filename, int &seed )  
  371. //    INITIALIZE initializes the genes within the variables bounds.   
  372. //  
  373. //  Discussion:  
  374. //  
  375. //    It also initializes (to zero) all fitness values for each  
  376. //    member of the population. It reads upper and lower bounds   
  377. //    of each variable from the input file `gadata.txt'. It   
  378. //    randomly generates values between these bounds for each   
  379. //    gene of each genotype in the population. The format of   
  380. //    the input file `gadata.txt' is   
  381. //      var1_lower_bound var1_upper bound  
  382. //      var2_lower_bound var2_upper bound ...  
  383.   
  384. //  Parameters:  
  385. //    Input, string FILENAME, the name of the input file.  
  386. //    Input/output, int &SEED, a seed for the random number generator.  
  387. {  
  388.     int i;  
  389.     ifstream input;  
  390.     int j;  
  391.     double lbound;  
  392.     double ubound;  
  393.   
  394.     input.open ( filename.c_str ( ) );  
  395.   
  396.     if ( !input )  
  397.     {  
  398.         cerr << "\n";  
  399.         cerr << "INITIALIZE - Fatal error!\n";  
  400.         cerr << "  Cannot open the input file!\n";  
  401.         exit ( 1 );  
  402.     }  
  403.     //   
  404.     //  Initialize variables within the bounds   
  405.     for ( i = 0; i < NVARS; i++ )  
  406.     {  
  407.         input >> lbound >> ubound;  
  408.   
  409.         for ( j = 0; j < POPSIZE; j++ )  
  410.         {  
  411.             population[j].fitness = 0;  
  412.             population[j].rfitness = 0;  
  413.             population[j].cfitness = 0;  
  414.             population[j].lower[i] = lbound;  
  415.             population[j].upper[i]= ubound;  
  416.             //population[j].gene[i] = r8_uniform_ab ( lbound, ubound, seed );  
  417.             population[j].gene[i] = Dou_uniform_ab( lbound, ubound );  
  418.         }  
  419.     }  
  420.   
  421.     input.close ( );  
  422.   
  423.     return;  
  424. }  
  425. //****************************************************************************80  
  426.   
  427. void keep_the_best ( )  
  428. //    KEEP_THE_BEST keeps track of the best member of the population.   
  429. //  
  430. //  Discussion:  
  431. //  
  432. //    Note that the last entry in the array Population holds a   
  433. //    copy of the best individual.  
  434. //  
  435. //  Local parameters:  
  436. //  
  437. //    Local, int CUR_BEST, the index of the best individual.  
  438. //  
  439. {  
  440.     int cur_best;  
  441.     int mem;  
  442.     int i;  
  443.   
  444.     cur_best = 0;  
  445.   
  446.     for ( mem = 0; mem < POPSIZE; mem++ )  
  447.     {  
  448.         if ( population[POPSIZE].fitness < population[mem].fitness )  
  449.         {  
  450.             cur_best = mem;  
  451.             population[POPSIZE].fitness = population[mem].fitness;  
  452.         }  
  453.     }  
  454.     //   
  455.     //  Once the best member in the population is found, copy the genes.  
  456.     //  
  457.     for ( i = 0; i < NVARS; i++ )  
  458.     {  
  459.         population[POPSIZE].gene[i] = population[cur_best].gene[i];  
  460.     }  
  461.   
  462.     return;  
  463. }  
  464. //****************************************************************************80  
  465.   
  466. void mutate ( int &seed )  
  467. //  
  468. //    MUTATE performs a random uniform mutation.   
  469. //  
  470. //  Discussion:  
  471. //  
  472. //    A variable selected for mutation is replaced by a random value   
  473. //    between the lower and upper bounds of this variable.  
  474. //  Parameters:  
  475. //  
  476. //    Input/output, int &SEED, a seed for the random number generator.  
  477. //  
  478. {  
  479.     const double a = 0.0;  
  480.     const double b = 1.0;  
  481.     int i;  
  482.     int j;  
  483.     double lbound;  
  484.     double ubound;  
  485.     double x;  
  486.   
  487.     for ( i = 0; i < POPSIZE; i++ )  
  488.     {  
  489.         for ( j = 0; j < NVARS; j++ )  
  490.         {  
  491.             //x = r8_uniform_ab ( a, b, seed );  
  492.             x = Dou_uniform_ab( a, b);  
  493.             if ( x < PMUTATION )  
  494.             {  
  495.                 lbound = population[i].lower[j];  
  496.                 ubound = population[i].upper[j];    
  497.                 //population[i].gene[j] = r8_uniform_ab ( lbound, ubound, seed );  
  498.                 population[i].gene[j] = Dou_uniform_ab( lbound, ubound );  
  499.             }  
  500.         }  
  501.     }  
  502.   
  503.     return;  
  504. }  
  505. //****************************************************************************80  
  506.   
  507. double r8_uniform_ab ( double a, double b, int &seed )  
  508. //    R8_UNIFORM_AB returns a scaled pseudorandom R8.  
  509. //  
  510. //  Discussion:  
  511. //  
  512. //    The pseudorandom number should be uniformly distributed  
  513. //    between A and B.  
  514. //  
  515. //  Parameters:  
  516. //  
  517. //    Input, double A, B, the limits of the interval.  
  518. //  
  519. //    Input/output, int &SEED, the "seed" value, which should NOT be 0.  
  520. //    On output, SEED has been updated.  
  521. //  
  522. //    Output, double R8_UNIFORM_AB, a number strictly between A and B.  
  523. //  
  524. {  
  525.     int i4_huge = 2147483647;  
  526.     int k;  
  527.     double value;  
  528.   
  529.     if ( seed == 0 )  
  530.     {  
  531.         cerr << "\n";  
  532.         cerr << "R8_UNIFORM_AB - Fatal error!\n";  
  533.         cerr << "  Input value of SEED = 0.\n";  
  534.         exit ( 1 );  
  535.     }  
  536.   
  537.     k = seed / 127773;  
  538.   
  539.     seed = 16807 * ( seed - k * 127773 ) - k * 2836;  
  540.   
  541.     if ( seed < 0 )  
  542.     {  
  543.         seed = seed + i4_huge;  
  544.     }  
  545.   
  546.     value = ( double ) ( seed ) * 4.656612875E-10;  
  547.   
  548.     value = a + ( b - a ) * value;  
  549.   
  550.     return value;  
  551. }  
  552. // my new function of product a value between  "a" and "b"  
  553. double Dou_uniform_ab(double a, double b)  
  554. {  
  555.     double tmp;  
  556.     //rand() / double(RAND_MAX)可以生成0~1之间的浮点数  
  557.     tmp = a + static_cast<double>(rand())/RAND_MAX*(b-a);  
  558.     return tmp;  
  559. }  
  560. void report ( int generation )  
  561. //    REPORT reports progress of the simulation.   
  562.   
  563. //  Local parameters:  
  564. //  
  565. //    Local, double avg, the average population fitness.  
  566. //  
  567. //    Local, best_val, the best population fitness.  
  568. //  
  569. //    Local, double square_sum, square of sum for std calc.  
  570. //  
  571. //    Local, double stddev, standard deviation of population fitness.  
  572. //  
  573. //    Local, double sum, the total population fitness.  
  574. //  
  575. //    Local, double sum_square, sum of squares for std calc.  
  576. //  
  577. {  
  578.     double avg;  
  579.     double best_val;  
  580.     int i;  
  581.     double square_sum;  
  582.     double stddev;  
  583.     double sum;  
  584.     double sum_square;  
  585.   
  586.     if ( generation == 0 )  
  587.     {  
  588.         cout << "\n";  
  589.         cout << "  Generation       Best            Average       Standard \n";  
  590.         cout << "  number           value           fitness       deviation \n";  
  591.         cout << "\n";  
  592.     }  
  593.   
  594.     sum = 0.0;  
  595.     sum_square = 0.0;  
  596.   
  597.     for ( i = 0; i < POPSIZE; i++ )  
  598.     {  
  599.         sum = sum + population[i].fitness;  
  600.         sum_square = sum_square + population[i].fitness * population[i].fitness;  
  601.     }  
  602.   
  603.     avg = sum / ( double ) POPSIZE;  
  604.     square_sum = avg * avg * POPSIZE;  
  605.     stddev = sqrt ( ( sum_square - square_sum ) / ( POPSIZE - 1 ) );  
  606.     best_val = population[POPSIZE].fitness;  
  607.   
  608.     cout << "  " << setw(8) << generation   
  609.         << "  " << setw(14) << best_val   
  610.         << "  " << setw(14) << avg   
  611.         << "  " << setw(14) << stddev << "\n";  
  612.   
  613.     return;  
  614. }  
  615.   
  616. void selector ( int &seed )  
  617. //    SELECTOR is the selection function.  
  618. //  
  619. //  Discussion:  
  620. //  
  621. //    Standard proportional selection for maximization problems incorporating   
  622. //    the elitist model.  This makes sure that the best member always survives.  
  623.   
  624. //  Parameters:  
  625. //  
  626. //    Input/output, int &SEED, a seed for the random number generator.  
  627. //  
  628. {  
  629.     const double a = 0.0;  
  630.     const double b = 1.0;  
  631.     int i;  
  632.     int j;  
  633.     int mem;  
  634.     double p;  
  635.     double sum;  
  636.     //  
  637.     //  Find the total fitness of the population.  
  638.     //  
  639.     sum = 0.0;  
  640.     for ( mem = 0; mem < POPSIZE; mem++ )  
  641.     {  
  642.         sum = sum + population[mem].fitness;  
  643.     }  
  644.     //  
  645.     //  Calculate the relative fitness of each member.  
  646.     //  
  647.     for ( mem = 0; mem < POPSIZE; mem++ )  
  648.     {  
  649.         population[mem].rfitness = population[mem].fitness / sum;  
  650.     }  
  651.     //   
  652.     //  Calculate the cumulative fitness.  
  653.     //  
  654.     population[0].cfitness = population[0].rfitness;  
  655.     for ( mem = 1; mem < POPSIZE; mem++ )  
  656.     {  
  657.         population[mem].cfitness = population[mem-1].cfitness +         
  658.             population[mem].rfitness;  
  659.     }  
  660.     //   
  661.     //  Select survivors using cumulative fitness.   
  662.     //  
  663.     for ( i = 0; i < POPSIZE; i++ )  
  664.     {   
  665.         //p = r8_uniform_ab ( a, b, seed );  
  666.         p = Dou_uniform_ab(a,b);  
  667.         if ( p < population[0].cfitness )  
  668.         {  
  669.             newpopulation[i] = population[0];        
  670.         }  
  671.         else  
  672.         {  
  673.             for ( j = 0; j < POPSIZE; j++ )  
  674.             {   
  675.                 if ( population[j].cfitness <= p && p < population[j+1].cfitness )  
  676.                 {  
  677.                     newpopulation[i] = population[j+1];  
  678.                 }  
  679.             }  
  680.         }  
  681.     }  
  682.     //   
  683.     //  Overwrite the old population with the new one.  
  684.     //  
  685.     for ( i = 0; i < POPSIZE; i++ )  
  686.     {  
  687.         population[i] = newpopulation[i];   
  688.     }  
  689.   
  690.     return;       
  691. }  
  692. //****************************************************************************80  
  693. double round(double number)  
  694. {  
  695.     return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);  
  696. }  
  697. void timestamp ( )  
  698. //    TIMESTAMP prints the current YMDHMS date as a time stamp.  
  699. {  
  700. # define TIME_SIZE 40  
  701.   
  702.     static char time_buffer[TIME_SIZE];  
  703.     const struct tm *tm;  
  704.     size_t len;  
  705.     time_t now;  
  706.   
  707.     now = time ( NULL );  
  708.     tm = localtime ( &now );  
  709.     //将时间格式化  
  710.     len = strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p"tm );  
  711.   
  712.     cout << time_buffer << "\n";  
  713.   
  714.     return;  
  715. # undef TIME_SIZE  
  716. }  
  717. //****************************************************************************80  
  718.   
  719. void Xover ( int one, int two, int &seed )  
  720. //    XOVER performs crossover of the two selected parents.   
  721. //  Local parameters:  
  722. //  
  723. //    Local, int point, the crossover point.  
  724. //  
  725. //  Parameters:  
  726. //  
  727. //    Input, int ONE, TWO, the indices of the two parents.  
  728. //  
  729. //    Input/output, int &SEED, a seed for the random number generator.  
  730. //  
  731. {  
  732.     int i;  
  733.     int point;  
  734.     double t;  
  735.     //  Select the crossover point.  
  736.     //point = i4_uniform_ab ( 0, NVARS - 1, seed );  
  737.     point = Int_uniform_ab(0, NVARS-1);  
  738.     //  
  739.     //  Swap genes in positions 0 through POINT-1.  
  740.     //  
  741.     for ( i = 0; i < point; i++ )  
  742.     {  
  743.         t                       = population[one].gene[i];  
  744.         population[one].gene[i] = population[two].gene[i];  
  745.         population[two].gene[i] = t;  
  746.     }  
  747.   
  748.     return;  
  749. }  

运行结果截图:

所参考的文档:

http://people.sc.fsu.edu/~jburkardt/cpp_src/simple_ga/simple_ga.html

参考文档


1、遗传算法,核心是达尔文优胜劣汰适者生存的进化理论的思想。一个种群,通过长时间的繁衍,种群的基因会向着更适应环境的趋势进化,适应性强的个体基因被保留,后代越来越多,适应能力低个体的基因被淘汰,后代越来越少。经过几代的繁衍进化,留下来的少数个体,就是相对能力最强的个体了。

那么在解决一些问题的时候,我们所学习的便是这样的思想。比如先随机创造很多很多的解,然后找一个靠谱的评价体系,去筛选适应性高的解再用这些适应性高的解衍生出更好的解,然后再筛选,再衍生。反复迭代一定次数,可以得到近似最优解。

2、首先,我们先看看一个经典组合问题:“背包问题”

“背包问题(Knapsack problem)是一种组合优化的NP完全问题。问题可以描述为:给定一组物品,每种物品都有自己的重量和价格,在限定的总重量内,我们如何选择,才能使得物品的总价格最高。问题的名称来源于如何选择最合适的物品放置于给定背包中。”

这个问题的衍生简化问题“0-1背包问题” 增加了限制条件:每件物品只有一件,可以选择放或者不放,更适合我们来举例
这样的问题如果数量少,当然最好选择穷举法
比如一共3件商品,用0表示不取,1表示取,那么就一共有
000 001 010
011 100 101
110 111
这样8种方案,然后让计算机去累加和,与重量上限比较,留下来的解里取最大即可。
但如果商品数有300,3000,甚至3w种呢,计算量太大穷举法可能就不适用了,这时如果遗传算法使用得当,就能在较短的时间内帮我们找到近似的最优解,我们继续往下看:
新的问题是12件商品的0-1背包问题
我们先让计算机随机产生1000个12位的二进制数。把总重量超过背包上限的解筛掉,剩下的两两一对随机交换“基因片段”产生下一代
交换前:
0000 1100 1101
0011 0101 0101
交换后:
0000 0101 1101
0011 1100 0101
再筛选,再交配,如此反复几代,留下的“基因型“差不多就是最好的了,如此这般与生物进化规律是一样的。
同时,在生物繁殖过程中,新产生的基因是有一定几率突变的,这是很多优良性状的重要来源,遗传算法中可也不能忽略它

比如:

变异前:

000101100101

变异后:

000101110101

产生突变的位置,就是一个概率问题。在设计算法的时候,会给每个基因位设置一个突变概率(当然是非常了)同样的在基因交换阶段交换哪些基因呢,也是一个算法设置问题。

3、总结一下,遗传算法应该有

一个基本函数:适度函数f(x)
三个基本操作:选择,交叉,变异

一.适度函数
适度函数其实就是指解的筛选标准,比如上文所说的把所有超过上限重量的解筛选掉,但是不是有更好的筛选标准呢?这将直接影响最后结果的接近程度以及求解所耗费的时间,所以设置一个好的适度函数很重要

二.选择
在遗传算法中选择也是个概率问题,在解的范围中适应度更高的基因型有更高的概率被选择到。所以,在选择一些解来产生下一代时,一种常用的选择策略是“比例选择”,也就是个体被选中的概率与其适应度函数值成正比。假设群体的个体总数是M,那么那么一个体Xi被选中的概率为f(Xi)/( f(X1) + f(X2) + …….. + f(Xn) )。常用的选择方法――轮盘赌(Roulette Wheel Selection)选择法。

三.交叉
在均等概率下基因位点的交叉,衍生出新的基因型。上述例子中是通过交换两个基因型的部分”基因”,来构造两个子代的基因型。

四.变异
在衍生子代的过程中,新产生的解中的“基因型”会以一定的概率出错,称为变异。变异发生的概率设置为Pm,记住该概率是很小的一个值。因为变异是小概率事件!

五.基本遗传算法优化
为了防止进化过程中产生的最优解被变异和交叉所破坏。《遗传算法原理及应用》介绍的最优保存策略是:即当前种群中适应度最高的个体不参与交叉运算和变异运算,而是用它来替换掉本代群体中经过交叉、变异等遗传操作后所产生的适应度最低的个体。

遗传算法的优点:

1、 与问题领域无关且快速随机的全局搜索能力。传统优化算法是从单个初始值迭代求最优解的;容易误入局部最优解。遗传算法从串集开始搜索,复盖面大,利于全局择优。

2、 搜索从群体出发,具有潜在的并行性,可以进行多个个体的同时比较,鲁棒性高!

3、 搜索使用评价函数启发,过程简单。

4、使用概率机制进行迭代,具有随机性。遗传算法中的选择、交叉和变异都是随机操作,而不是确定的精确规则。这说明遗传算法是采用随机方法进行最优解搜索,选择体现了向最优解迫近,交叉体现了最优解的产生,变异体现了全局最优解的复盖

5、具有可扩展性,容易与其他算法结合。遗传算法求解时使用特定问题的信息极少,仅仅使用适应值这一信息进行搜索,并不需要问题导数等与问题直接相关的信息。遗传算法只需适应值和串编码等通用信息,故几乎可处理任何问题,容易形成通用算法程序。

6、具有极强的容错能力。遗传算法的初始串集本身就带有大量与最优解甚远的信息;通过选择、交叉、变异操作能迅速排除与最优解相差极大的串;这是一个强烈的滤波过程;并且是一个并行滤波机制。故而,遗传算法有很高的容错能力。

遗传算法具有良好的全局搜索能力,可以快速地将解空间中的全体解搜索出,而不会陷入局部最优解的快速下降陷阱;并且利用它的内在并行性,可以方便地进行分布式计算,加快求解速度。

遗传算法的缺点:

1、遗传算法的编程实现比较复杂,首先需要对问题进行编码,找到最优解之后还需要对问题进行解码

2、三个算子的实现也有许多参数,如交叉率和变异率,并且这些参数的选择严重影响解的品质,而目前这些参数的选择大部分是依靠经验

3、没有能够及时利用网络的反馈信息,故算法的搜索速度比较慢,要得要较精确的解需要较多的训练时间

4、算法对初始种群的选择有一定的依赖性(下图所示),能够结合一些启发算法进行改进

5、算法的并行机制的潜在能力没有得到充分的利用,这也是当前遗传算法的一个研究热点方向。

同时,遗传算法的局部搜索能力较差,导致单纯的遗传算法比较费时,在进化后期搜索效率较低。在实际应用中,遗传算法容易产生过早收敛的问题。采用何种选择方法既要使优良个体得以保留,又要维持群体的多样性,一直是遗传算法中较难解决的问题。

-------------------------我------是------分------割--------线------------------------------------------------------------

下面举例来说明遗传算法用以求函数最大值

函数为y = -x2+ 5的最大值,-32<=x<=31

一、编码以及初始种群的产生

编码采用二进制编码,初始种群采用矩阵的形式,每一行表示一个染色体,每一个染色体由若干个基因位组成。关于染色体的长度(即基因位的个数)可根据具体情况而定。比如说根据要求极值的函数的情况,本文-32<=X<=31,该范围内的整数有64个,所以可以取染色体长度为6,(26=64)。综上所述,取染色体长度为6,前5个二进制构成该染色体的值(十进制),第6个表示该染色体的适应度值。若是所取得染色体长度越长,表示解空间搜索范围越大,对应的是待搜索的X范围越大。关于如何将二进制转换为十进制,文后的C代码中函数x即为转换函数。

初始种群结构如下图所示:

该初始种群共有4个染色体,第1列表示各个染色体的编号,第2列表示该染色体值的正负号,0表示正,1表示负。第3列到第7列为二进制编码,第8列表示各个染色体的适应度值。第2列到第7列的0-1值都是随机产生的。

二、适应度函数

一般情况下,染色体(也叫个体,或一个解)的适应度函数为目标函数的线性组合。本文直接以目标函数作为适应度函数。即每个染色体的适应度值就是它的目标函数值,f(x)=-x^2+ 5。

三、选择算子

初始种群产生后,要从种群中选出若干个体进行交叉、变异,那么如何选择这些个体呢?选择方法就叫做选择算子。一般有轮盘赌选择法、锦标赛选择法、排序法等。本文采用排序法来选择,即每次选择都选出适应度最高的两个个体。那么执行一次选择操作后,得到的新种群的一部分为下图所示:

四、交叉算子

那么接下来就要对新种群中选出的两个个体进行交叉操作,一般的交叉方法有单点交叉、两点交叉、多点交叉、均匀交叉、融合交叉。方法不同,效果不同。本文采用最简单的单点交叉。交叉点随机产生。但是交叉操作要在一定的概率下进行,这个概率称为交叉率,一般设置为0.5到0.95之间。通过交叉操作,衍生出子代,以补充被淘汰掉的个体。交叉后产生的新个体组成的新种群如下:

黑体字表示子代染色体继承父代个体的基因。

五、变异

变异就是对染色体的基因进行变异,使其改变原来的结构(适应值也就改变),达到突变进化的目的。变异操作也要遵从一定的概率来进行,一般设置为0到0.5之间,即以小概率进行基因突变。这符合自然规律。本文的变异方法直接采取基因位反转变异法,即0变为1,1变为0。要进行变异的基因位的选取也是随机的。

六、终止规则

遗传算法是要一代一代更替的,那么什么时候停止迭代呢?这个规则就叫终止规则。一般常用的终止规则有:若干代后终止,得到的解达到一定目标后终止,计算时间达到一定限度后终止等方法。本文采用迭代数来限制。


代码如下所示:

[cpp] view plain copy 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #include <stdlib.h>  
  4. #include <time.h>  
  5. #include <iostream>  
  6.   
  7. typedef struct Chrom                           // 结构体类型,为单个染色体的结构;  
  8. {  
  9.     short int bit[6];//一共6bit来对染色体进行编码,其中1位为符号位。取值范围-64~+64  
  10.     int fit ;//适应值  
  11.     double rfit;//相对的fit值,即所占的百分比  
  12.     double cfit;//积累概率  
  13. }chrom;                                         
  14. //定义将会用到的几个函数;  
  15. void *evpop (chrom popcurrent[4]);//进行种群的初始化  
  16. int x (chrom popcurrent);  
  17. int y (int x);  
  18. void *pickchroms (chrom popcurrent[4]);//选择操作  
  19. void *pickchroms_new (chrom popcurrent[4]); // 基于概率分布  
  20. void *crossover (chrom popnext[4]);//交叉操作  
  21. void *mutation (chrom popnext[4]);//突变  
  22. double r8_uniform_ab ( double a, double b, int &seed );//生成a~b之间均匀分布的数字  
  23. chrom popcurrent [4];                        // 初始种群规模为;  
  24. chrom popnext [4];                           // 更新后种群规模仍为;  
  25. void main ()                                    // 主函数;  
  26. {  
  27.     int num ;                                    // 迭代次数;  
  28.     int i ,j, l,Max ,k;  
  29.     Max=0;                                      // 函数最大值  
  30.   
  31.     printf("\nWelcome to the Genetic Algorithm!\n");  //   
  32.     printf("The Algorithm is based on the function y = -x^2 + 5 to find the maximum value of the function.\n");  
  33.   
  34. enter:printf ("\nPlease enter the no. of iterations\n请输入您要设定的迭代数 : ");  
  35.     scanf("%d" ,&num);                           // 输入迭代次数,传送给参数 num;  
  36.   
  37.     if(num <1)                                    
  38.         goto enter ;                                 // 判断输入的迭代次数是否为负或零,是的话重新输入;  
  39.     //不同的随机数可能结果不同??那是当所设置的迭代次数过少时,染色体的基因型过早地陷入局部最优  
  40.     srand(time(0));    
  41.     evpop(popcurrent );    // 随机产生初始种群;  
  42.     //是否需要指定x的取值范围呢?6bit来表示数字,第一位为符号位,5bit表示数字大小。所以,取值范围为-32~+31  
  43.     Max = popcurrent[0].fit;//对Max值进行初始化  
  44.   
  45.     for(i =0;i< num;i ++)                          // 开始迭代;  
  46.     {  
  47.   
  48.         printf("\ni = %d\n" ,i);                 // 输出当前迭代次数;  
  49.   
  50.         for(j =0;j<4; j++)  
  51.         {  
  52.             popnext[j ]=popcurrent[ j];           // 更新种群;  
  53.         }  
  54.   
  55.         pickchroms(popnext );                    // 挑选优秀个体;  
  56.         crossover(popnext );                     // 交叉得到新个体;  
  57.         mutation(popnext );                      // 变异得到新个体;  
  58.   
  59.         for(j =0;j<4; j++)   
  60.         {  
  61.             popcurrent[j ]=popnext[ j];              // 种群更替;  
  62.         }  
  63.   
  64.     }  // 等待迭代终止;  
  65. //对于真正随机数是需要注意取较大的迭代次数  
  66.     for(l =0;l<3; l++)  
  67.     {  
  68.         if(popcurrent [l]. fit > Max )  
  69.         {  
  70.             Max=popcurrent [l]. fit;  
  71.             k=x(popcurrent [l]);//此时的value即为所求的x值  
  72.         }  
  73.   
  74.     }  
  75.     printf("\n 当x等于 %d时,函数得到最大值为: %d ",k ,Max);  
  76.     printf("\nPress any key to end ! " );  
  77.   
  78.     flushall();                                 // 清除所有缓冲区;  
  79.     getche();                                   // 从控制台取字符,不以回车为结束;  
  80.   
  81. }                                               
  82.   
  83.   
  84.   
  85. void *evpop (chrom popcurrent[4])   // 函数:随机生成初始种群;  
  86. {  
  87.     int i ,j, value1;  
  88.     int random ;  
  89.     double sum=0;  
  90.       
  91.     for(j =0;j<4; j++)                            // 从种群中的第1个染色体到第4个染色体  
  92.     {  
  93.         for(i =0;i<6; i++)                       // 从染色体的第1个基因位到第6个基因位  
  94.         {  
  95.             random=rand ();                     // 产生一个随机值  
  96.             random=(random %2);                 // 随机产生0或者1  
  97.             popcurrent[j ].bit[ i]=random ;       // 随机产生染色体上每一个基因位的值,或;  
  98.         }    
  99.   
  100.         value1=x (popcurrent[ j]);                // 将二进制换算为十进制,得到一个整数值;  
  101.         popcurrent[j ].fit= y(value1); // 计算染色体的适应度值  
  102.         sum = sum + popcurrent[j ].fit;  
  103.         printf("\n popcurrent[%d]=%d%d%d%d%d%d  value=%d  fitness = %d",j, popcurrent[j ].bit[5], popcurrent[j ].bit[4], popcurrent[j ].bit[3], popcurrent[j ].bit[2], popcurrent[j ].bit[1], popcurrent[j ].bit[0], value1,popcurrent [j]. fit);   
  104.         // 输出整条染色体的编码情况,  
  105.     }  
  106.     //计算适应值得百分比,该参数是在用轮盘赌选择法时需要用到的  
  107.     for (j = 0; j < 4; j++)  
  108.     {  
  109.         popcurrent[j].rfit = popcurrent[j].fit/sum;  
  110.         popcurrent[j].cfit = 0;//将其初始化为0  
  111.     }  
  112.     return(0);                  
  113. }                                         
  114.   
  115.   
  116. int x (chrom popcurrent)  // 函数:将二进制换算为十进制;  
  117. {//此处的染色体长度为,其中个表示符号位  
  118.       
  119.     int z ;  
  120.     z=(popcurrent .bit[0]*1)+( popcurrent.bit [1]*2)+(popcurrent. bit[2]*4)+(popcurrent .bit[3]*8)+( popcurrent.bit [4]*16);  
  121.   
  122.     if(popcurrent .bit[5]==1)  // 考虑到符号;  
  123.     {  
  124.         z=z *(-1);                               
  125.     }  
  126.   
  127.     return(z );                             
  128. }                                       
  129. //需要能能够从外部直接传输函数,加强鲁棒性  
  130. int y (int x)// 函数:求个体的适应度;  
  131. {  
  132.     int y ;  
  133.     y=-(x *x)+5;                                // 目标函数:y= - ( x^ 2 ) +5;  
  134.     return(y );               
  135. }   
  136. //基于轮盘赌选择方法,进行基因型的选择  
  137. void *pickchroms_new (chrom popnext[4])//计算概率  
  138. {  
  139.     int men;  
  140.     int i;int j;  
  141.     double p;  
  142.     double sum=0.0;  
  143.     //find the total fitness of the population  
  144.     for (men = 0; men < 4; men++ )  
  145.     {  
  146.         sum = sum + popnext[men].fit;  
  147.     }  
  148.     //calculate the relative fitness of each member  
  149.     for (men = 0; men < 4; men++ )  
  150.     {  
  151.         popnext[men].rfit = popnext[men].fit / sum;  
  152.     }  
  153.     //calculate the cumulative fitness,即计算积累概率  
  154.     popcurrent[0].cfit = popcurrent[0].rfit;  
  155.     for ( men = 1; men < 4; men++)  
  156.     {  
  157.         popnext[men].cfit = popnext[men-1].cfit + popnext[men].rfit;  
  158.     }  
  159.       
  160.     for ( i = 0; i < 4; i++ )  
  161.     {//产生0~1之间的随机数  
  162.         //p = r8_uniform_ab ( 0, 1, seed );//通过函数生成0~1之间均匀分布的数字  
  163.         p =rand()%10;//  
  164.         p = p/10;  
  165.         if ( p < popnext[0].cfit )  
  166.         {  
  167.             popcurrent[i] = popnext[0];        
  168.         }  
  169.         else  
  170.         {  
  171.             for ( j = 0; j < 4; j++ )  
  172.             {   
  173.                 if ( popnext[j].cfit <= p && p < popnext[j+1].cfit )  
  174.                 {  
  175.                     popcurrent[i] = popcurrent[j+1];  
  176.                 }  
  177.             }  
  178.         }  
  179.     }  
  180.     //  Overwrite the old population with the new one.  
  181.     //  
  182.     for ( i = 0; i < 4; i++ )  
  183.     {  
  184.         popnext[i] = popcurrent[i];   
  185.     }  
  186.     return(0);  
  187. }  
  188. void *pickchroms (chrom popnext[4])          // 函数:选择个体;  
  189. {  
  190.     int i ,j;  
  191.     chrom temp ;                                // 中间变量  
  192.     //因此此处设计的是个个体,所以参数是  
  193.     for(i =0;i<3; i++)                           // 根据个体适应度来排序;(冒泡法)  
  194.     {  
  195.         for(j =0;j<3-i; j++)  
  196.         {  
  197.             if(popnext [j+1]. fit>popnext [j]. fit)  
  198.             {  
  199.                 temp=popnext [j+1];  
  200.                 popnext[j +1]=popnext[ j];  
  201.                 popnext[j ]=temp;  
  202.   
  203.             }    
  204.         }                 
  205.     }  
  206.     for(i =0;i<4; i++)  
  207.     {  
  208.         printf("\nSorting:popnext[%d] fitness=%d" ,i, popnext[i ].fit);  
  209.         printf("\n" );                       
  210.     }  
  211.     flushall();/* 清除所有缓冲区 */                        
  212.     return(0);  
  213. }     
  214. double r8_uniform_ab( double a, double b, int &seed )  
  215. {  
  216.     {  
  217.         int i4_huge = 2147483647;  
  218.         int k;  
  219.         double value;  
  220.   
  221.         if ( seed == 0 )  
  222.         {  
  223.             std::cerr << "\n";  
  224.             std::cerr << "R8_UNIFORM_AB - Fatal error!\n";  
  225.             std::cerr << "  Input value of SEED = 0.\n";  
  226.             exit ( 1 );  
  227.         }  
  228.   
  229.         k = seed / 127773;  
  230.   
  231.         seed = 16807 * ( seed - k * 127773 ) - k * 2836;  
  232.   
  233.         if ( seed < 0 )  
  234.         {  
  235.             seed = seed + i4_huge;  
  236.         }  
  237.   
  238.         value = ( double ) ( seed ) * 4.656612875E-10;  
  239.   
  240.         value = a + ( b - a ) * value;  
  241.   
  242.         return value;  
  243.     }  
  244. }  
  245. void *crossover (chrom popnext[4])              // 函数:交叉操作;  
  246. {  
  247.   
  248.     int random ;  
  249.     int i ;  
  250.     //srand(time(0));   
  251.     random=rand ();                             // 随机产生交叉点;  
  252.     random=((random %5)+1);                     // 交叉点控制在0到5之间;  
  253.     for(i =0;i< random;i ++)                     
  254.     {  
  255.         popnext[2].bit [i]= popnext[0].bit [i];   // child 1 cross over  
  256.         popnext[3].bit [i]= popnext[1].bit [i];   // child 2 cross over  
  257.     }  
  258.   
  259.     for(i =random; i<6;i ++)                      // crossing the bits beyond the cross point index  
  260.     {  
  261.         popnext[2].bit [i]= popnext[1].bit [i];    // child 1 cross over  
  262.         popnext[3].bit [i]= popnext[0].bit [i];    // chlid 2 cross over  
  263.     }    
  264.   
  265.     for(i =0;i<4; i++)  
  266.     {  
  267.         popnext[i ].fit= y(x (popnext[ i]));        // 为新个体计算适应度值;  
  268.     }  
  269.   
  270.     for(i =0;i<4; i++)  
  271.     {  
  272.         printf("\nCrossOver popnext[%d]=%d%d%d%d%d%d    value=%d    fitness = %d",i, popnext[i ].bit[5], popnext[i ].bit[4], popnext[i ].bit[3], popnext[i ].bit[2], popnext[i ].bit[1], popnext[i ].bit[0], x(popnext [i]), popnext[i ].fit);   
  273.         // 输出新个体;  
  274.     }  
  275.     return(0);  
  276. }                                            
  277.   
  278. void *mutation (chrom popnext[4])               // 函数:变异操作;  
  279. {  
  280.   
  281.     int random ;  
  282.     int row ,col, value;  
  283.     //srand(time(0));   
  284.     random=rand ()%50;  // 随机产生到之间的数;  
  285.     //变异操作也要遵从一定的概率来进行,一般设置为0到0.5之间  
  286.     //  
  287.     if(random ==25)                              // random==25的概率只有2%,即变异率为,所以是以小概率进行变异!!  
  288.     {  
  289.         col=rand ()%6;                            // 随机产生要变异的基因位号;  
  290.         row=rand ()%4;                            // 随机产生要变异的染色体号;  
  291.   
  292.         if(popnext [row]. bit[col ]==0)             // 1变为;  
  293.         {  
  294.             popnext[row ].bit[ col]=1 ;  
  295.         }  
  296.         else if (popnext[ row].bit [col]==1)        // 0变为;  
  297.         {  
  298.             popnext[row ].bit[ col]=0;  
  299.         }  
  300.         popnext[row ].fit= y(x (popnext[ row]));     // 计算变异后的适应度值;  
  301.         value=x (popnext[ row]);  
  302.         printf("\nMutation occured in popnext[%d] bit[%d]:=%d%d%d%d%d%d    value=%d   fitness=%d", row,col ,popnext[ row].bit [5],popnext[ row].bit [4],popnext[ row].bit [3],popnext[ row].bit [2],popnext[ row].bit [1],popnext[ row].bit [0],value, popnext[row ].fit);  
  303.   
  304.         // 输出变异后的新个体;  
  305.     }                                            
  306.   
  307.     return(0);  
  308. }     

同时需要注意的是在利用遗传算法过程中需要较大的种群数量或者设置较高的迭代次数,否则容易过早地到达稳态。

如在计算方程y=-x^2+5的最大值时,所选择的是以6bit来对个体进行编码,其中1bit为符号位。所以,基因型的范围为-32~+31。

而且选择的个体数量为4个,易于过早到达平衡。如下图所示,所设置的迭代次数为20,但是在迭代两次就已经使得个体无差异,无法再继续以交叉组合出更高适应性的基因型。唯一可以期望的是基因突变,但是突变所设置的是小概率事件,本文所设置的约为2%。那么需要增大迭代次数,以增大基因突变的次数,以避免过早陷入最优。


本文参考:

http://www.codeproject.com/Articles/10417/Genetic-Algorithm

http://blog.csdn.NET/xujinpeng99/article/details/6211597



原文地址:http://blog.csdn.net/ljp1919/article/details/42488935

http://blog.csdn.net/ljp1919/article/details/42425281

0 0