1

I am writing an application working with binaryNumber objects of a certain bit size and objects that hold an array of these binaryNumber objects.

The code looks somewhat right, however even when I try the mutate function with even 1000 iterations in some cases no bits get flipped at all.... which is strange because according to normal distribution shouldn't and average of 1 bit get flipped?

What I basically want to do, is have a piece of code that determines whether or not to flip a single bit of a binary string based on a low probability (for example I want a probability of 0.001 - which is 1 in 1000 -or- 0.1% probability)

Note: the probability must be checked for every bit individually (every bit should have a 0.1% chance of being flipped/inverted.

Right now my function looks like this: Thanks in advance.

void Organism::mutate()
{
    // this function forces chance mutation based on a predetermined probability: 0.001 chance, which is 0.1 % = 1 in a thousand
    // iterate through the bits, generate a random number between 0-1000 and if it is 1, then perform a mutation/flip.
    for (int i = 0; i < chromosomeLength; i++)
        for (int k = 0; k < chromosome[0].numBits; k++)
        {
            srand(time(NULL)); // seed based on time.
            //check the probability:
            bool doMut = (rand() % 1000) <= 1;
            if (doMut == 1) //if the generated number is within probability
            {
                chromosome[i][k] = !chromosome[i][k];
                cout << "A MUTATION OCCURED!!!" << endl;
                exit(EXIT_FAILURE);
            }

        }


}
James
  • 133
  • 2
  • 3
  • 9
  • 2
    Get that `srand()` out of the loops. It should be invoked at the beginning of `main()` and *never* again during your program runtime. That said, if you have statistical needs (like a normal or poisson distribution of your values, or even a uniform distribution to be honest) I *highly* recommend [``](http://en.cppreference.com/w/cpp/numeric/random) use in your C++ program. The C++11 guys really went all-out with their PRNG library. Its *amazing*. – WhozCraig Sep 20 '13 at 22:21
  • [rand() considered harmful](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – TemplateRex Sep 20 '13 at 22:36

0 Answers0