Roulette selection function for the genetic algorithm

So, I wrote a roulette selection function for my genetic algorithm:

public String tournament(float fitness, Chromosome pop[], int selection) { // roulette if (selection == 1) { Random random = new Random(); float slice = random.nextFloat() * fitness; float curFitness = 0.0f; for (int i = 0; i < initialPopulation; i++) { curFitness += pop[i].fitness; if (curFitness >= slice) return pop[i].bits; } } return ""; } 

The problem is that it sometimes returns an empty string that only placed them to satisfy the return condition. This is usually not a problem, but during some runs it causes the GA to end, as the next step involves the crossover step. Any ideas?

+4
source share
2 answers

Thus, it turns out that the mutation function sometimes nullified some of my bitstrings, which caused the population to contain empty strings.

Before that, he looked like this:

 public String mutate(String bits) { Random random = new Random(); StringBuffer buf = new StringBuffer(bits); for (int i = 0; i < bits.length(); i++) { if (random.nextFloat() < mutationRate) { if (bits.charAt(i) == '1') { buf.setCharAt(i, '0'); return buf.toString(); } else { buf.setCharAt(i, '1'); return buf.toString(); } } } return ""; } 

And I changed it to this:

 public String mutate(String bits) { Random random = new Random(); StringBuffer buf = new StringBuffer(bits); for (int i = 0; i < bits.length(); i++) { if (random.nextFloat() < mutationRate) { if (bits.charAt(i) == '1') { buf.setCharAt(i, '0'); } else { buf.setCharAt(i, '1'); } } } return buf.toString(); } 

A careless mistake.

+2
source

I guess the problem is that your fitness sometimes less than the sum of your pop[i].fitness es. Try putting the string return "ERROR: " + fitness + " / " + curFitness; after the for loop, but inside the if , or something like that, and see what comes back.

0
source

All Articles