瞎BB
代码
导入库以及参数设置
import matplotlib.pyplot as plt
import math
import random
T_init = 100
alpha = 0.95
T_min = 1e-3
目标函数
def obj(x):y = 10 * math.sin(5 * x) + 7 * math.cos(4 * x)return -y
主函数
def SA(T_init,alpha,T_min):T = T_initx_new = random.random() * 10x_current = x_newy_current = float('inf')x_best = x_newy_best = float('inf')while T > T_min:for i in range(100):delta_x = random.random() - 0.5if 0 < (x_new + delta_x) < 10:x_new = x_new + delta_xelse:x_new = x_new - delta_xy_new = obj(x_new)if (y_new<y_current):y_current=y_newx_current=x_newif (y_new<y_best):y_best=y_newx_best=x_newelse:if random.random() < math.exp(-(y_new - y_current) / T):y_current=y_newx_current=x_newelse:x_new=x_currentT *= alphaprint('最优解',x_best,obj(x_best))
SA(T_init,alpha,T_min)