Skip to content

Instantly share code, notes, and snippets.

@ehzawad
Created June 18, 2023 03:46
Show Gist options
  • Select an option

  • Save ehzawad/08c92fbd11b90afd50999268f3f8fff9 to your computer and use it in GitHub Desktop.

Select an option

Save ehzawad/08c92fbd11b90afd50999268f3f8fff9 to your computer and use it in GitHub Desktop.
import math
import random
# Initial state: a random number between 0 and 2π
def initial_state():
return random.uniform(0, 2*math.pi)
# Neighbor: a new state very close to the current one
def neighbor(state):
new_state = state + random.gauss(0, 0.1)
return new_state % (2*math.pi) # Ensure state is within [0, 2π]
# Evaluation: the value of the sine function (our objective)
def evaluation(state):
return math.sin(state)
# Temperature: Starts high and decreases over time. We're using a linear schedule here.
def temperature(t, max_iter):
return max_iter / t
def simulated_annealing(max_iter):
current = initial_state()
for t in range(1, max_iter + 1):
T = temperature(t, max_iter)
next_neighbor = neighbor(current)
deltaE = evaluation(next_neighbor) - evaluation(current)
if deltaE > 0:
current = next_neighbor
elif random.uniform(0, 1) < math.exp(deltaE / T):
current = next_neighbor
return current, math.sin(current)
result_state, result_value = simulated_annealing(1000000)
print(f"The maximum value is {result_value} and it occurs at {result_state}.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment