ai_lab_4
import math import rando
def objective_function(x):
return -x**2 + 10*x + 25
def acceptance_probability(old_cost, new_cost, temperature):
if new_cost > old_cost:
return 1.0
else:
return math.exp((new_cost - old_cost) / temperature)
def simulated_annealing(initial_solution, initial_temperature, cooling_rate, max_iterations):
current_solution = initial_solution current_cost =
objective_function(current_solution) best_solution
= current_solution best_cost = current_cost
temperature = initial_temperature
for _ in range(max_iterations):
neighbor_solution = current_solution + random.uniform(-1, 1)
neighbor_cost = objective_function(neighbor_solution
if acceptance_probability(current_cost, neighbor_cost, temperature) > random.random():
current_solution = neighbor_solution
current_cost = neighbor_cost
if current_cost > best_cost:
best_solution = current_solution
best_cost = current_cost
temperature *= cooling_rate # Cooling the temperature
return best_solution, best_cost
if name == "main":
initial_solution = random.uniform(-10, 10)
initial_temperature = 1000 cooling_rate
= 0.95 max_iterations = 1000
best_solution, best_cost = simulated_annealing(initial_solution, initial_temperature,
cooling_rate, max_iterations)
print("Best solution:", best_solution)
print("Best cost:", best_cost)