Values change when they're not supposed to
One of my methods (actualy the workhorse method) from my genetic algorithm is doing something funky, and not in a good way. What I'm doing, is recording the best solution found and copying it directly into the new generation (elitism). But with a few System.out.println()'s I found that my best solution gets overwritten by a worse solution, even when my comparison returns false. Here's the code:
Code:
//in SolutionSet class
public void newGeneration() {
Solution[] newGen = new Solution[solutions.length];
if(bestSoFar == null) {
Solution[] fittest2 = find2Fittest();
newGen[0] = fittest2[0];
newGen[1] = fittest2[1];
bestSoFar = fittest2[0];
}
else {
newGen[0] = bestSoFar; //first we add the best solution yet
newGen[1] = findFittest(); //next we add the best of this generation
}
for(int i = 2; i < newGen.length; i+=2) {
int parent1 = selectRoulette(); //selection of parents for crossover
int parent2;
int counter = 0;
do {
counter++;
parent2 = selectRoulette();
if(counter > 15) {
parent2 = (parent1+1)%solutions.length;
break;
}
} while(parent1 == parent2);
Solution[] offspring = solutions[parent1].crossover(solutions[parent2]);
newGen[i] = offspring[0];
newGen[i].mutate();
newGen[i].calcFitness();
newGen[i+1] = offspring[1];
newGen[i+1].mutate();
newGen[i+1].calcFitness();
}
numGens++;
solutions = newGen; //the new generation is set as the current
Solution candidate = findFittest(); //get the best solution
System.out.println(bestSoFar.getFitness()+" "+candidate.getFitness()+" "+(candidate.compareTo(bestSoFar) == -1)); //debugging
if(candidate.compareTo(bestSoFar) == -1)
bestSoFar = candidate;
}
Now the compareTo of a solution is simple:
Code:
//in Solution class
public int compareTo(Solution s) { //smaller fitness score indicates better solution
if(fitness < s.fitness) return -1;
if(fitness > s.fitness) return 1;
return 0;
}
I'm really lost why this is happenning, even when the comparison in the if clause returns false, the value of bestSoFar changes, sample output:
Code:
20.68888888888889 20.68888888888889 false //even though the comparison returns false
21.26086956521739 21.26086956521739 false //bestSoFar changes value