c++遗传算法变异错误

标签 c++ genetic-algorithm mutation

我的遗传算法中的变异函数有问题。我也不太明白我做错了什么。我看了这段代码一段时间,我认为逻辑是正确的,只是没有产生我想要的结果。

问题 当我输出位于子结构中的二进制数组时,如果任何位发生突变,则将更改一个随机数,而不是应该更改的随机数。

例如

  • 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/

相关文章:

c++ - 如何使用uccp api开发一个lync客户端

matlab - 神经网络优化与遗传算法

algorithm - 逆概率选择(进化算法的逆适应度选择)

javascript - Graphql - 有没有办法同时插入两个表,但第二个表依赖于从第一个表的返回?

python - 在C++ API中加载经过python训练的xgboost,预测结果为空

c++ - std::stringstream 与 std::string 用于连接多个字符串

c++ - 在 Visual Studio 中执行单个 Boost Test 单元测试

genetic-algorithm - 特殊调度算法(模式扩展)

javascript - 如何对字符串进行突变? JavaScript

mutation - PTTest 失败并且未生成突变覆盖率