Domanda

Ho un problema con la funzione mutazioni nel mio algoritmo genetico. Non riesco a vedere quello che sto facendo male neanche. Ho guardato questo codice per un po 'e penso che la logica è corretto, non è solo produrre i risultati che voglio.

Il problema Quando uscita i matrice binaria situato nel Bambino Struct, Se mutazione è verificato su uno dei bit, allora un numero casuale viene cambiata, e non quello che dovrebbe essere.

per esempio

  • 0000000 è la stringa binaria
  • mutazione si è verificato sulla seconda bit
  • 0001000 sarebbe il risultato

In questa sezione si trova all'interno del principale.

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

Questa è la funzione di mutazione

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

E 'in fase di uscita nel complesso come questo

    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;
     }
È stato utile?

Soluzione

Non è possibile strozzare il tasso multation in questo modo. È necessario separare il bit mutato dalla probabilità del verificano mutazione.

for (int z = 0; z < Binscale; z++)     
{         
    if (rand() % 100 < MutationRate)        
    {
        // flip bit             
        Child1.binary_code[z] += 1; 
        Child1.binary_code[z] %= 2;
    }
} 

modo ancora più semplice po 'di vibrazione:

Child1.binary_code[z] ^= 1;

Altri suggerimenti

provare questo:

void mutation(Parent& Child1,int childnumber)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top