我的遗传算法中的变异函数有问题。我也不太明白我做错了什么。我看了这段代码一段时间,我认为逻辑是正确的,只是没有产生我想要的结果。
问题 当我输出位于子结构中的二进制数组时,如果任何位发生突变,则将更改一个随机数,而不是应该更改的随机数。
例如
- 0000000为二进制串
- 突变发生在第二个 位
- 0001000 将是结果
此部分位于主目录中。
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';
}
}
}
在main中是这样输出的
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;
}
最佳答案
您不能通过这种方式限制变异率。您需要将变异位与变异发生的概率分开。
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++遗传算法变异错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4725515/