Genetic Algorithm pseudo code:
Problem: Solve 2x+1 = 7 (we know the answer is 3, but work with me)
Step #1 Generate a Random population of numbers:
Population = 1, 6, 8, 4
Step #2 Chose a fitness function. Ours will be Error = ABS(1-(2x +
1)/7)
Error(1) = ABS(1-(2x1+1/7)) = 0.57 Error(6) = ABS(1-(2x6+1/7)) = 0.86 Error(8) = ABS(1-(2x8+1/7)) = 1.43 Error(4) = ABS(1-(2x4+1/7)) = 0.29
The number with the smallest Error is closest to the answer. (Still with me?)
Step #3 Repopulate your population based on your fitness function results. This is the tough part to grasp. We need to normalize all of the errors so we can get a repopulation percentage. This will help us get the new population of numbers.
Take the total of the error 0.57 + 0.86 + 1.43 + 0.29 = 3.15
3.15/0.57 = 5.53 3.15/0.86 = 3.66 3.15/1.43 = 2.20 3.15/0.29 = 10.86
Take the total of the normalized error = 5.53 + 3.66 + 2.20 + 10.86 =22.25
Repopulation percentage for 1 = 5.53/22.25 = 25% Repopulation percentage for 6 = 3.66/22.25 = 16% Repopulation percentage for 8 = 2.20/22.25 = 10% Repopulation percentage for 4 = 10.86/22.25 = 49 %
So now you repopulation your population, this means if you were generating a random number from 0-100, if the number was 0-24 the answer would be 1. if the number was 25-41(25+16) the answer would be 6 if the number was 42-52(42+10) the answer would be 8 if the number was 53-100 the answer would be 4
So you can see the smaller the Error the greater chance the new population will include that number
New Repopulation = 4, 4, 4, 1 So if you kept on repeating step 2 eventually you would have a population of all 4's, but 4 is not the answer. So how do we get the answer in our population if we don't have 3 in the initial population?
The answer is step #4.
Step #4 mutation / crossover. In this example we'll just do mutation. Just generate a random number and replace it in the population.
New population after mutation 4, 4, 4, 9
Step #5 repeat steps 2 - 4 until total Error is acceptable. In this case until you get an Error of 0.
Kind of make sense???
I can give you sample code but it won't make sense unless you understand the concept of evolutionary codes.
Eric