Pergunta

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.

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.

for example

  • 0000000 is the binary string
  • mutation has occured on the second bit
  • 0001000 would be the result

This section is located within the main.

for (int Child = 0; Child < ParentNumberInit; Child++)
{
    cout << endl;
    mutation(child[Child],Child);
}

This is the mutation function

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';
        }
    }
}

It's being outputted in the main like this

    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;
     }
Foi útil?

Solução

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;
    }
} 

Even simpler way to flip bit:

Child1.binary_code[z] ^= 1;

Outras dicas

try this:

void mutation(Parent& Child1,int childnumber)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top