模拟退火算法实例python
时间: 2023-09-15 15:21:59 浏览: 75
当然可以!以下是一个简单的模拟退火算法的示例代码,使用 Python 实现:
```python
import math
import random
# 目标函数,这里以一个简单的函数为例
def objective_function(x, y):
return math.sin(x) + math.cos(y)
# 模拟退火算法
def simulated_annealing(init_temp, final_temp, cooling_rate, num_iterations):
# 初始化最优解和最优目标值
best_solution = None
best_value = float('-inf')
# 随机初始化当前解
current_solution = (random.uniform(-10, 10), random.uniform(-10, 10))
current_value = objective_function(current_solution[0], current_solution[1])
# 设置初始温度
current_temp = init_temp
# 迭代搜索
for i in range(num_iterations):
# 生成新解
new_solution = (current_solution[0] + random.uniform(-1, 1),
current_solution[1] + random.uniform(-1, 1))
# 计算新解的目标值
new_value = objective_function(new_solution[0], new_solution[1])
# 计算目标值差异
delta = new_value - current_value
# 判断是否接受新解
if delta > 0 or random.random() < math.exp(delta / current_temp):
current_solution = new_solution
current_value = new_value
# 更新最优解
if current_value > best_value:
best_solution = current_solution
best_value = current_value
# 降低温度
current_temp *= cooling_rate
return best_solution, best_value
# 参数设置
init_temp = 100
final_temp = 0.1
cooling_rate = 0.99
num_iterations = 1000
# 调用模拟退火算法
best_solution, best_value = simulated_annealing(init_temp, final_temp, cooling_rate, num_iterations)
# 输出结果
print("Best solution:", best_solution)
print("Best value:", best_value)
```
以上示例代码中的目标函数是一个简单的函数 `sin(x) + cos(y)`,你可以根据自己的需要替换成其他函数。模拟退火算法的参数可以根据具体问题进行调整,如初始温度、终止温度、冷却率等。
希望能帮到你!如果有任何问题,请随时提问。