Untitled

 avatar
unknown
plain_text
a year ago
1.5 kB
8
Indexable
import math
import random

def get_random_number(x_min, x_max):
    return random.uniform(x_min, x_max)

def is_acceptable(y, yt, temp):
    p = math.exp((yt - y) / temp)
    return p > random.uniform(0, 1)

def get_trial_interval(x, temp, x_min, x_max):
    xt_min = max(x - 2 * temp, x_min)
    xt_max = min(x + 2 * temp, x_max)
    return xt_min, xt_max

def function(x):
    pi = math.pi
    return 3 * math.sin((pi * x) / 5) + math.sin(pi * x)

def simulated_annealing(epochs, trials, temp, alpha, x_min, x_max):
    def print_epoch_info(epoch, x, y):
        print(f"\n\nEpoch {epoch}/{epochs}, x={x}, f(x)={y}, T={temp}")

    def print_trial_info(trial, xt, yt):
        print(f"\n      Interval per trial {trial} = [{xt_min}; {xt_max}]")
        print(f"      xt={xt}, f(xt)={yt}")

    x = get_random_number(x_min, x_max)

    for epoch in range(1, epochs + 1):
        y = function(x)
        print_epoch_info(epoch, x, y)

        for trial in range(1, trials + 1):
            xt_min, xt_max = get_trial_interval(x, temp, x_min, x_max)
            print_trial_info(trial, *get_trial_result(x, xt_min, xt_max))

        temp *= alpha

    return x

def get_trial_result(x, xt_min, xt_max):
    xt = get_random_number(xt_min, xt_max)
    yt = function(xt)
    return xt, yt

# Parameters
temp = 1.0
x_min, x_max = 0, 10
alpha = 0.9
epochs, trials = 5, 3

local_maximum = simulated_annealing(epochs, trials, temp, alpha, x_min, x_max)
print(f"\n\nLocal maximum of the function is {local_maximum}")
Editor is loading...