模拟退火算法怎么python代码
时间: 2023-09-06 16:09:18 浏览: 99
模拟退火算法 Python代码
模拟退火算法的Python代码如下:
```
import math
import random
def simulated_annealing(cost_func, initial_solution, max_temp=100, min_temp=1, iterations=1000, cooling_rate=0.03):
current_solution = initial_solution
best_solution = current_solution
current_temp = max_temp
for i in range(iterations):
# Generate a new solution
new_solution = current_solution + random.uniform(-1, 1)
# Calculate the cost of the new and current solution
current_cost = cost_func(current_solution)
new_cost = cost_func(new_solution)
# If the new solution is better, accept it
if new_cost < current_cost:
current_solution = new_solution
# If the new solution is the best so far, update the best solution
if new_cost < cost_func(best_solution):
best_solution = new_solution
# If the new solution is not better, calculate acceptance probability based on temperature and accept/reject the solution
else:
acceptance_prob = math.exp(-(new_cost - current_cost) / current_temp)
if random.uniform(0, 1) < acceptance_prob:
current_solution = new_solution
# Decrease the temperature
current_temp *= 1-cooling_rate
if current_temp < min_temp:
break
return best_solution
```
其中,`cost_func` 是代价函数,`initial_solution` 是初始解,`max_temp` 是最高温度,`min_temp` 是最低温度,`iterations` 是迭代次数,`cooling_rate` 是降温速率。
阅读全文