Search code examples
c#bit-manipulationgenetic-algorithmmutation

How to perform crossover of double numbers in my GA implementation?


In a few words, how do I:

  • go from double to bits,
  • then do the crossover (one point, two point),
  • and go back to double

I can develop the roulette wheel selection. What I don't see clearly is how mixing two doubles might give me a "better" double. Is that completely random? If the "fittest" of my doubles and my "weakest" one combine, won't they produce a mid-point double?

Elaboration: Shortest distance from a point to this curve

EDIT 1: Without slowing down the program too much.

EDIT 2: I considered using a byte[], but I don't know if that would go against the genetic algorithm part.


Solution

  • This worked for me:

    BitArray BAA1 = new BitArray(BitConverter.GetBytes(a1));
    BitArray BAA2 = new BitArray(BitConverter.GetBytes(a2));
    
        for (int i = r.Next(0, 64); i > 0; i--)
                {
                    temp = BAA1.Get(i);
                    temp2 = BAA2.Get(i);
    
                    BAA1.Set(i, temp2);
                    BAA2.Set(i, temp);
    
    
                    temp = BAB1.Get(i);
                    temp2 = BAB2.Get(i);
    
                    BAB1.Set(i, temp2);
                    BAB2.Set(i, temp);
                }
    
            byte[] tempbytes = new byte[BAA1.Length];
    
            BAA1.CopyTo(tempbytes, 0);
            double baa1 = BitConverter.ToDouble(tempbytes, 0);
    
            BAA2.CopyTo(tempbytes, 0);
            double baa2 = BitConverter.ToDouble(tempbytes, 0);
    

    baa1 and baa2 are the end products of the cross.