我的遗传算法中的变异函数有问题。我也看不出我做错了什么。我已经查看了这段代码一段时间,我认为逻辑是正确的,它只是没有产生我想要的结果。
问题当我输出位于子结构中的二进制数组时,如果任何位发生突变,那么随机数将被更改,而不是应该更改的那个。
例如
- 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;
}