0
2

参考文献

しっかり学ぶ数理最適化 モデルからアルゴリズムまで
梅谷俊治・著
発行 2020/10/23

準備

オンラインコンパイラを使用します。

ソースコード

sample.py
# -*- coding: utf-8 -*-
import numpy as np
import math
import random

def objective(x):
    return 2 * np.sin(x) + 3 * np.cos(2 * x) + 5 * np.sin(2 / 3 * x)

def acceptance_probability(old_cost, new_cost, temperature):
    if new_cost < old_cost:
        return 1.0
    else:
        return math.exp((old_cost - new_cost) / temperature)

def simulated_annealing(objective, initial_state, initial_temperature, cooling_rate, min_temperature, num_iterations):
    current_state = initial_state
    current_cost = objective(current_state)

    best_state = current_state
    best_cost = current_cost

    temperature = initial_temperature

    for i in range(num_iterations):
        new_state = current_state + np.random.uniform(-0.1, 0.1)
        new_cost = objective(new_state)

        if acceptance_probability(current_cost, new_cost, temperature) > random.random():
            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

    return best_state, best_cost

# パラメータの設定
initial_state = 0.0
initial_temperature = 100
cooling_rate = 0.9999
min_temperature = 0.01
num_iterations = 100000

# 最適化の実行
best_state, best_cost = simulated_annealing(objective, initial_state, initial_temperature, cooling_rate, min_temperature, num_iterations)

print("Best state:", best_state)
print("Best cost:", best_cost)


0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2