我在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);
}}}
输出返回一个或没有选择的染色体,这不是预期的结果。如果这是一种可靠的方法,那么我会想到它吗?
提前致谢。
答案 0 :(得分:3)
当您选择染色体时,您应该只确定一次随机数,然后累积偏移量,以便您考虑所有范围:
| 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);