def generate(solution, nodeCount):
pos = np.random.randint(1, nodeCount, 2)
new_sol = copy.deepcopy(solution)
new_sol[pos[0]], new_sol[pos[1]] = new_sol[pos[1]], new_sol[pos[0]]
return new_sol
iter_max = 1000 # 循环次数
r = 0.97 # 降温的快慢
T = 5000 # 初始温度, 加温过程
T_min = 1 # 温度下限
cnt = 0
while T > T_min:
# 循环直到系统冷却
for iter_cnt in range(iter_max):
# 等温过程
new_sol = generate(solution, nodeCount)
new_obj = calPath(new_sol, dis)
delta_f = new_obj - obj
if delta_f < 0 : # 新解更优
obj = new_obj
solution = new_sol
else:
# 按 metropolis 准则接受新解
if math.exp(-delta_f/T) > np.random.uniform(0, 1):
obj = new_obj
solution = new_sol
cnt += 1
T *= r
TSP问题(Python 模拟退火)
最新推荐文章于 2024-05-09 10:04:00 发布