参考文献
しっかり学ぶ数理最適化 モデルからアルゴリズムまで
梅谷俊治・著
発行 2020/10/23
準備
オンラインコンパイラを使用します。
ソースコード
sample.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// 目的関数の定義
double objective(double x) {
return 2 * sin(x) + 3 * cos(2 * x) + 5 * sin(2.0 / 3.0 * x);
}
// 受け入れ確率を計算する関数
double acceptance_probability(double old_cost, double new_cost, double temperature) {
if (new_cost < old_cost) {
return 1.0;
} else {
return exp((old_cost - new_cost) / temperature);
}
}
// シミュレーテッド・アニーリングによる最適化
void simulated_annealing(double (*objective)(double), double initial_state, double initial_temperature, double cooling_rate, double min_temperature, int num_iterations, double *best_state, double *best_cost) {
double current_state = initial_state;
double current_cost = objective(current_state);
*best_state = current_state;
*best_cost = current_cost;
double temperature = initial_temperature;
for (int i = 0; i < num_iterations; i++) {
double new_state = current_state + ((double)rand() / RAND_MAX) * 0.2 - 0.1;
double new_cost = objective(new_state);
if (acceptance_probability(current_cost, new_cost, temperature) > (double)rand() / RAND_MAX) {
current_state = new_state;
current_cost = new_cost;
}
if (new_cost < *best_cost) {
*best_state = new_state;
*best_cost = new_cost;
}
temperature *= cooling_rate;
if (temperature < min_temperature) {
break;
}
}
}
int main() {
srand(time(0));
// パラメータの設定
double initial_state = 0.0;
double initial_temperature = 100.0;
double cooling_rate = 0.9999;
double min_temperature = 0.01;
int num_iterations = 100000;
// 最適化の実行
double best_state, best_cost;
simulated_annealing(objective, initial_state, initial_temperature, cooling_rate, min_temperature, num_iterations, &best_state, &best_cost);
printf("Best state: %f\n", best_state);
printf("Best cost: %f\n", best_cost);
return 0;
}