0

我正在用 C 语言从头开始编写遗传算法,我陷入了轮盘赌的实现,这里我是如何编码的:

void selection(Chromosome * chromosome){

double totalFitness=0;
double totalProbability=0;
double probability=0;
double rndNumber;
double min,max;
int i;

min=0.0;
max=1.0;

for(i=0;i<POPULATION_SIZE;i++){
 totalFitness += chromosome[i].fitness;
  }

  for(i=0;i<POPULATION_SIZE;i++){
   chromosome[i].probability = (chromosome[i].fitness)/totalFitness;
   printf("Chromosome %d with probability %f\n",i, chromosome[i].probability);
  }
 srand((unsigned)time(NULL));
 for(i=0;i<POPULATION_SIZE;i++){
  rndNumber = ((double)rand()/(double)RAND_MAX);
  if(chromosome[i].probability >= rndNumber){
  printf("Chromosome %d selected \n",i);




}}}

输出返回一个或没有选择的染色体,这不是预期的结果。我想知道这是否是正确的点缀方式?

提前致谢。

4

1 回答 1

4

当您选择一条染色体时,您应该只确定一次随机数,然后累积偏移量,以便您考虑所有范围:

                       | random number 
                       |
                       X
    +--------------+-----+----+--+--++---+-----+
    |              |     |    |  |  ||   |     |
    +--------------+-----+----+--+--++---+-----+
   0.0            p0   p0+p1                  1.0 == sum(p[i])

在代码中:

double rndNumber = rand() / (double) RAND_MAX;
double offset = 0.0;
int pick = 0;

for (i = 0; i < POPULATION_SIZE; i++) {
    offset += chromosome[i].probability;
    if (rndNumber < offset) {
        pick = i;
        break;
    }
}

printf("Chromosome %d selected.\n", pick);
于 2014-07-07T11:29:51.187 回答