56 auto start = std::chrono::high_resolution_clock::now();
57 double x = x0, y = y0, dx, dy;
59 double g0 = dx * dx + dy * dy;
64 for (
int i = 0; i < maxIter; ++i)
72 double new_dx, new_dy;
74 double gk_new = new_dx * new_dx + new_dy * new_dy;
76 if (sqrt(gk_new) < tol)
82 double beta = gk_new / g0;
84 d_x = -new_dx + beta * d_x;
85 d_y = -new_dy + beta * d_y;
91 auto end = std::chrono::high_resolution_clock::now();
92 res.
duration = std::chrono::duration<double>(end - start).count();
103 auto start = std::chrono::high_resolution_clock::now();
108 for (
int i = 0; i < maxIter && T > Tmin; ++i)
111 double x_new = x + ((double)rand() / RAND_MAX - 0.5);
112 double y_new = y + ((double)rand() / RAND_MAX - 0.5);
114 double delta = f_new - f_current;
117 if (delta < 0 || exp(-delta / T) > ((
double)rand() / RAND_MAX))
129 auto end = std::chrono::high_resolution_clock::now();
130 res.
duration = std::chrono::duration<double>(end - start).count();
141 auto start = std::chrono::high_resolution_clock::now();
142 std::vector<Individual> population(populationSize);
143 double xMin = -10.0, xMax = 10.0;
144 double yMin = -10.0, yMax = 10.0;
147 for (
auto &ind : population)
149 ind.x = xMin + (xMax - xMin) * ((
double)rand() / RAND_MAX);
150 ind.y = yMin + (yMax - yMin) * ((
double)rand() / RAND_MAX);
154 res.
iterations = generations * populationSize;
156 for (
int gen = 0; gen < generations; ++gen)
159 std::vector<Individual> newPopulation;
160 for (
int i = 0; i < populationSize; ++i)
162 int a = rand() % populationSize;
163 int b = rand() % populationSize;
164 Individual parent = population[a].
fitness < population[b].fitness ? population[a] : population[b];
165 newPopulation.push_back(parent);
169 for (
int i = 0; i < populationSize - 1; i += 2)
171 if (((
double)rand() / RAND_MAX) < crossoverRate)
173 double alpha = (double)rand() / RAND_MAX;
174 double temp_x1 = alpha * newPopulation[i].x + (1 - alpha) * newPopulation[i + 1].x;
175 double temp_y1 = alpha * newPopulation[i].y + (1 - alpha) * newPopulation[i + 1].y;
176 double temp_x2 = alpha * newPopulation[i + 1].x + (1 - alpha) * newPopulation[i].x;
177 double temp_y2 = alpha * newPopulation[i + 1].y + (1 - alpha) * newPopulation[i].y;
178 newPopulation[i].x = temp_x1;
179 newPopulation[i].y = temp_y1;
180 newPopulation[i + 1].x = temp_x2;
181 newPopulation[i + 1].y = temp_y2;
186 for (
auto &ind : newPopulation)
188 if (((
double)rand() / RAND_MAX) < mutationRate)
190 ind.x += ((double)rand() / RAND_MAX - 0.5);
191 ind.y += ((double)rand() / RAND_MAX - 0.5);
205 population = newPopulation;
210 for (
const auto &ind : population)
212 if (ind.fitness < best.
fitness)
216 auto end = std::chrono::high_resolution_clock::now();
217 res.
duration = std::chrono::duration<double>(end - start).count();
double lineSearchBacktracking(double x, double y, double d_x, double d_y, double alpha_init, double rho, double c)