python模拟退火算法解决旅行商三十个城市之间的问题并可视化展示的源码
时间: 2024-03-20 16:41:53 浏览: 67
模拟退火算法解决旅行商问题
4星 · 用户满意度95%
好的,下面是Python模拟退火算法解决旅行商三十个城市之间的并可视化展示源码:
```pythonimport random
import math
import matplotlib.pyplot as plt
# 随机生成30个城市的坐标
cities = []
for i in range(30):
city = (random.randint(0, 100), random.randint(0, 100))
cities.append(city)
# 计算两个城市之间的距离
def distance(city1, city2):
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
# 模拟退火算法求解TSP问题
def TSP(cities, T_init, T_end, alpha, iter_max):
n = len(cities)
cur_solution = list(range(n))
random.shuffle(cur_solution)
cur_cost = sum(distance(cities[cur_solution[i]], cities[cur_solution[i-1]]) for i in range(n))
T = T_init
T_list = []
cost_list = []
while T > T_end:
for i in range(iter_max):
new_solution = cur_solution.copy()
a = random.randint(0, n-1)
b = random.randint(0, n-1)
new_solution[a], new_solution[b] = new_solution[b], new_solution[a]
new_cost = sum(distance(cities[new_solution[i]], cities[new_solution[i-1]]) for i in range(n))
delta_cost = new_cost - cur_cost
if delta_cost < 0 or math.exp(-delta_cost/T) > random.random():
cur_solution = new_solution.copy()
cur_cost = new_cost
T *= alpha
T_list.append(T)
cost_list.append(cur_cost)
return cur_cost, cur_solution, T_list, cost_list
# 可视化展示
def plot_result(cities, solution, T_list, cost_list):
n = len(cities)
x = [cities[solution[i]][0] for i in range(n)]
y = [cities[solution[i]][1] for i in range(n)]
plt.subplot(121)
plt.plot(x, y, 'o-')
plt.title('Shortest Path')
plt.subplot(122)
plt.semilogx(T_list, cost_list)
plt.title('Convergence')
plt.xlabel('Temperature')
plt.ylabel('Distance')
plt.show()
if __name__ == '__main__':
T_init = 100
T_end = 0.1
alpha = 0.99
iter_max = 1000
cost, solution, T_list, cost_list = TSP(cities, T_init, T_end, alpha, iter_max)
plot_result(cities, solution, T_list, cost_list)
```
该代码首先随机生成了30个城市的坐标。然后定义了`distance`函数用于计算两个城市之间的距离,`TSP`函数用于求解TSP问题,并返回最短路径长度、最短路径的顺序、温度和路径长度的变化列表。最后,定义了`plot_result`函数用于可视化展示结果,包括最短路径和温度路径长度的变化情况。
在代码运行过程中,首先调用`TSP`函数求解最短路径和路径顺序,然后调用`plot_result`函数将结果可视化展示出来。
希望这份代码对您有帮助!
阅读全文