模拟退火 python
时间: 2023-09-12 19:06:21 浏览: 106
模拟退火(Simulated Annealing)是一种优化算法,常用于解决复杂的优化问题。下面是一个简单的模拟退火算法的 Python 代码示例:
```python
import math
import random
def objective_function(x):
# 定义目标函数,即需要优化的函数
return x**2
def simulated_annealing(objective_function, initial_solution, initial_temperature, cooling_rate, num_iterations):
current_solution = initial_solution
best_solution = initial_solution
current_temperature = initial_temperature
for i in range(num_iterations):
# 生成新解
new_solution = current_solution + random.uniform(-1, 1)
# 计算当前解和新解之间的目标函数值差异
current_cost = objective_function(current_solution)
new_cost = objective_function(new_solution)
cost_diff = new_cost - current_cost
# 判断是否接受新解
if cost_diff < 0 or math.exp(-cost_diff / current_temperature) > random.random():
current_solution = new_solution
# 更新最优解
if objective_function(current_solution) < objective_function(best_solution):
best_solution = current_solution
# 降低温度
current_temperature *= cooling_rate
return best_solution
# 使用模拟退火算法求解最小值
initial_solution = 10
initial_temperature = 100
cooling_rate = 0.9
num_iterations = 1000
best_solution = simulated_annealing(objective_function, initial_solution, initial_temperature, cooling_rate, num_iterations)
print("最优解为:", best_solution)
print("最小值为:", objective_function(best_solution))
```
在上面的示例代码中,我们首先定义了需要优化的目标函数 `objective_function`,然后使用 `simulated_annealing` 函数来执行模拟退火算法。需要传入的参数包括初始解、初始温度、降温速率以及迭代次数。
请注意,以上代码只是一个简单的示例,实际应用中可能需要根据具体的问题进行适当的修改和调整。
阅读全文