C ++遗传算法突变误差
-
12-10-2019 - |
题
我的遗传算法中的突变功能有问题。我也看不到我在做什么错。我已经看了一段时间了,我认为逻辑是正确的,只是没有产生我想要的结果。
当我输出位于子结构中的二进制阵列时,如果在任何位上发生了突变,则将更改随机数,而不是应该的一个问题。
例如
- 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';
}
}
}
这样的主要是这样
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;
其他提示
尝试这个:
void mutation(Parent& Child1,int childnumber)
不隶属于 StackOverflow