import math
import random
# 定义目标函数(示例为一个简单的二维函数)
def cost_function(x, y):
return (x - 2) ** 2 + (y + 3) ** 2
# 定义模拟退火算法
def simulated_annealing(cost_func, x_init, y_init, temp_init, temp_final, alpha, max_iter):
# 初始化当前解和当前解对应的成本
x_curr = x_init
y_curr = y_init
cost_curr = cost_func(x_curr, y_curr)
# 初始化最优解和最优解对应的成本
x_best = x_curr
y_best = y_curr
cost_best = cost_curr
# 初始化温度
temp_curr = temp_init
# 迭代搜索
for _ in range(max_iter):
# 生成新解
x_new = x_curr + random.uniform(-1, 1)
y_new = y_curr + random.uniform(-1, 1)
# 边界处理(根据实际问题进行修改)
x_new = max(min(x_new, 10), -10)
y_new = max(min(y_new, 10), -10)
# 计算新解的成本
cost_new = cost_func(x_new, y_new)
# 计算成本变化
cost_delta = cost_new - cost_curr
# 判断是否接受新解
if cost_delta < 0 or math.exp(-cost_delta / temp_curr) > random.random():
x_curr = x_new
y_curr = y_new
cost_curr = cost_new
# 更新最优解
if cost_curr < cost_best:
x_best = x_curr
y_best = y_curr
cost_best = cost_curr
# 降低温度
temp_curr *= alpha
return x_best, y_best, cost_best
# 示例运行
x_init = random.uniform(-10, 10)
y_init = random.uniform(-10, 10)
temp_init = 100
temp_final = 0.1
alpha = 0.95
max_iter = 1000
x_best, y_best, cost_best = simulated_annealing(cost_function, x_init, y_init, temp_init, temp_final, alpha, max_iter)
print("最优解:", x_best, y_best)
print("最优解对应的成本:", cost_best)
本文仅为学习记录,如有错误欢迎指出。