c ++遗传算法变异错误 [英] c++ Genetic Algorithm Mutation error
问题描述
我的遗传算法中的变异函数有问题.我也不太清楚我在做什么错.我看过这段代码已经有一段时间了,我认为逻辑是正确的,只是没有产生我想要的结果.
I Have a problem with the mutation function within my genetic Algorithm. I can't quite see what I am doing wrong either. I've looked at this code for a while and I think the logic is correct, it's just not producing the results i want.
问题 当我输出位于子结构中的Binary数组时,如果在任何位上发生了变异,则将更改一个随机数,而不是应该更改的数.
The problem When i output the Binary array located in the Child Struct, If mutation has occured on any of the bits, then a random number will be changed, and not the one that should be.
例如
- 0000000是二进制字符串
- 第二次发生了变异 位
- 0001000将是结果
- 0000000 is the binary string
- mutation has occured on the second bit
- 0001000 would be the result
此部分位于主体内.
for (int Child = 0; Child < ParentNumberInit; Child++)
{
cout << endl;
mutation(child[Child],Child);
}
这是变异函数
void mutation(struct Parent Child1,int childnumber)
{
int mutation; // will be the random number generated
cout << endl << "Child " << (childnumber+1) << endl;
//loop through every bit in the binary string
for (int z = 0; z < Binscale; z++)
{
mutation = 0; // set mutation at 0 at the start of every loop
mutation = rand()%100; //create a random number
cout << "Generated number = " << mutation << endl;
//if variable mutation is smaller, mutation occurs
if (mutation < MutationRate)
{
if(Child1.binary_code[z] == '0')
Child1.binary_code[z] = '1';
else if(Child1.binary_code[z] == '1')
Child1.binary_code[z] = '0';
}
}
}
像这样在主体中输出
for (int childnumber = 0; childnumber < ParentNumberInit; childnumber++)
{
cout<<"Child "<<(childnumber+1)<<" Binary code = ";
for (int z = 0; z < Binscale; z ++)
{
cout<<child[childnumber].binary_code[z];
}
cout<<endl;
}
推荐答案
您无法通过这种方式来限制转换率.您需要将发生突变的位与发生突变的可能性区分开来.
You can't throttle the multation rate this way. You need to separate the mutated bit from the probability of the mutation occuring.
for (int z = 0; z < Binscale; z++)
{
if (rand() % 100 < MutationRate)
{
// flip bit
Child1.binary_code[z] += 1;
Child1.binary_code[z] %= 2;
}
}
更简单的翻转位方式:
Child1.binary_code[z] ^= 1;
这篇关于c ++遗传算法变异错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!