我试图在java中实现roullete轮。
我创建了两种方法。一种是制造柔性轮,另一种是旋转柔性轮。
我应该如何实施probalibities。我的方法不是这样做的。 我创建柔性轮的方法是完全错误的。
例如,如果我得到:
50%的染色体与健康86
35%的染色体与健康88
15%的染色体与健康90
如何确保15%的人有更多机会被选中?
public void createRolette(Population population) throws Exception {
int swap;
for (int i=0; i<populationSize; i++){
population.getIndividual(i);
Simulator.allocateTask(i);
rouletteId.add(i);
rouletteFit.add(calcFitness(i));
}
for (int i = 0; i < rouletteFit.size() - 1; i++) {
for (int j = 0; j < rouletteFit.size() - i - 1; j++) {
if (rouletteFit.get(j) > rouletteFit.get(j+1))
{
swap = rouletteFit.get(j);
rouletteFit.set(j, rouletteFit.get(j+1));
rouletteFit.set(j+1, swap);
swap = rouletteId.get(j);
rouletteId.set(j, rouletteId.get(j+1));
rouletteId.set(j+1, swap);
}
}
}
System.out.println(rouletteId.toString());
System.out.println(rouletteFit.toString());
}
public int rotateRolette(Population population) {
Integer SelectedIndv = (int)(Math.random()* (rouletteId.size())); // faz a escolha entre 0 e o numero maximo de elementos;
return rouletteId.get(SelectedIndv);
}
答案 0 :(得分:0)
我不确定你的代码是做什么的。但对于轮盘赌轮,你应该做这样的事情:
答案 1 :(得分:0)
前一个答案中描述的步骤的可能实现(使用Java 8):
class RouletteWheelSelector {
public Population<DoubleGene, Double>
select(Population<DoubleGene, Double> population, int count) {
// The incremental fitness probability array.
final double[] incremental = incremental(probabilities(population));
final Random random = new Random();
return IntStream.range(0, count)
// Select the individual index.
.map(i -> indexOf(incremental, random.nextDouble()))
// Select the individual.
.mapToObj(i -> population.get(i))
// Create the new population object.
.collect(Population.toPopulation());
}
// Calculate the fitness probabilities of the given population.
static double[] probabilities(Population<?, Double> population) {
final double[] fitness = population.stream()
.mapToDouble(pt -> pt.getFitness())
.toArray();
final double sum = Arrays.stream(fitness).sum();
return Arrays.stream(fitness)
.map(v -> v/sum)
.toArray();
}
// Create the incremental probability array.
static double[] incremental(final double[] values) {
for (int i = 1; i < values.length; ++i) {
values[i] += values[i - 1];
}
return values;
}
// Binary search for the individual index for a given probability.
static int indexOf(final double[] incr, final double v) {
int imin = 0;
int imax = incr.length;
int index = -1;
while (imax > imin && index == -1) {
final int imid = (imin + imax) >>> 1;
if (imid == 0 || (incr[imid] >= v && incr[imid - 1] < v)) {
index = imid;
} else if (incr[imid] <= v) {
imin = imid + 1;
} else if (incr[imid] > v) {
imax = imid;
}
}
return index;
}
}
代码已从&#39; RouletteWheelSelector&#39;中提取。 Jenetics项目。