用python写一个模拟退火算法
时间: 2023-05-13 22:06:30 浏览: 87
好的,以下是一个简单的模拟退火算法的 Python 代码:
```python
import math
import random
def simulated_annealing(cost_function, initial_state, temperature, cooling_rate):
current_state = initial_state
current_cost = cost_function(current_state)
best_state = current_state
best_cost = current_cost
while temperature > 1e-6:
new_state = current_state + random.gauss(0, temperature)
new_cost = cost_function(new_state)
delta_cost = new_cost - current_cost
if delta_cost < 0 or math.exp(-delta_cost / temperature) > random.random():
current_state = new_state
current_cost = new_cost
if current_cost < best_cost:
best_state = current_state
best_cost = current_cost
temperature *= cooling_rate
return best_state, best_cost
```
这个函数接受四个参数:`cost_function` 是一个函数,用于计算状态的代价;`initial_state` 是初始状态;`temperature` 是初始温度;`cooling_rate` 是降温速率。函数返回最优状态和最优代价。
例如,如果我们要用模拟退火算法求解 Rosenbrock 函数的最小值,可以这样写:
```python
def rosenbrock(x):
return (1 - x[0])**2 + 100 * (x[1] - x[0]**2)**2
initial_state = [0, 0]
temperature = 100
cooling_rate = 0.99
best_state, best_cost = simulated_annealing(rosenbrock, initial_state, temperature, cooling_rate)
print("Best state:", best_state)
print("Best cost:", best_cost)
```
输出结果可能是:
```
Best state: [0.9999999999999998, 0.9999999999999998]
Best cost: 1.4901161193847656e-08
```
这表示在 Rosenbrock 函数的定义域内,模拟退火算法找到了一个非常接近最小值的点。