Skip to content

Commit 088e746

Browse files
committed
[SimulatedAnnealer]: Fixed bug that made SA no better than random search
1 parent e6bccfa commit 088e746

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

src/secondary-pop-nodes/annealer/SimulatedAnnealer.cpp

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include "secondary-pop-nodes/annealer/SimulatedAnnealer.hpp"
22
#include <string>
33
#include <sstream>
4+
#include <iostream>
45
#include <random>
56
#include <cmath>
67

@@ -98,15 +99,15 @@ void SimulatedAnnealer::init(bool maximize, TemperatureSchedule * schedule) {
9899
}
99100

100101
Individual ** SimulatedAnnealer::newPopulation() {
101-
Individual ** population = (Individual**)malloc(
102+
Individual ** nextPopulation = (Individual**)malloc(
102103
sizeof(Individual*)*populationSize
103104
);
104105

105106
for (int i = 0; i < populationSize; i++) {
106-
population[i] = getNeighbour(myPopulation[i]);;
107+
nextPopulation[i] = getNeighbour(myPopulation[i]);
107108
}
108109

109-
return population;
110+
return nextPopulation;
110111
}
111112

112113
int SimulatedAnnealer::compareNeighbourliness(
@@ -202,7 +203,8 @@ Individual * SimulatedAnnealer::getNeighbour(Individual * target) {
202203
choice = neighbourDistribution(generator);
203204
}
204205

205-
if (neighbours[choice] == NULL) return target;
206+
if (neighbours[choice] == NULL) return target->deepCopy();
207+
206208
int targetFitness = target->checkFitness();
207209
int neighbourFitness = neighbours[choice]->checkFitness();
208210

@@ -222,22 +224,21 @@ Individual * SimulatedAnnealer::getNeighbour(Individual * target) {
222224
float temp = schedule->currentTemp(currentGeneration);
223225
if (temp == 0) {
224226
delete(neighbour);
225-
return target;
227+
return target->deepCopy();
226228
}
227229

228230
int delta = maximize ? neighbourFitness - targetFitness :
229231
targetFitness - neighbourFitness;
230232

231-
float probability = exp(((float)-delta)/temp);
233+
float probability = exp(((float)delta)/temp);
232234

233235
uniform_real_distribution<float>
234236
goingWrongWayDistribution(0, 1);
235237

236238
if (goingWrongWayDistribution(generator) < probability) {
237239
return neighbour;
238240
} else {
239-
delete(neighbour);
240-
return target;
241+
return target->deepCopy();
241242
}
242243
}
243244
}

0 commit comments

Comments
 (0)