模拟退火算法求香蕉函数
时间: 2023-06-21 07:11:44 浏览: 48
香蕉函数是一个多峰函数,模拟退火算法可以用来寻找其全局最优解。下面是使用模拟退火算法求解香蕉函数的示例代码:
```python
import math
import random
# 香蕉函数
def banana(x, y):
return (1 - x)**2 + 100 * (y - x**2)**2
# 模拟退火算法
def simulated_annealing(initial_state, objective_function, temperature, cooling_rate, stopping_temperature):
current_state = initial_state
current_energy = objective_function(*current_state)
best_state = current_state
best_energy = current_energy
while temperature > stopping_temperature:
next_state = (current_state[0] + random.uniform(-1, 1), current_state[1] + random.uniform(-1, 1))
next_energy = objective_function(*next_state)
energy_delta = next_energy - current_energy
if energy_delta < 0 or math.exp(-energy_delta / temperature) > random.uniform(0, 1):
current_state = next_state
current_energy = next_energy
if current_energy < best_energy:
best_state = current_state
best_energy = current_energy
temperature *= cooling_rate
return best_state, best_energy
# 设置初始状态和参数
initial_state = (random.uniform(-5, 5), random.uniform(-5, 5))
temperature = 100
cooling_rate = 0.95
stopping_temperature = 1e-8
# 调用模拟退火算法求解香蕉函数
best_state, best_energy = simulated_annealing(initial_state, banana, temperature, cooling_rate, stopping_temperature)
print("Best solution: x = %.4f, y = %.4f, energy = %.4f" % (best_state[0], best_state[1], best_energy))
```
在上面的代码中,我们定义了香蕉函数 `banana(x, y)` 和模拟退火算法 `simulated_annealing()`。模拟退火算法需要一个初始状态、一个目标函数、一个初始温度、一个冷却速率和一个结束温度作为参数。在本例中,我们随机生成一个初始状态,设置初始温度为100,冷却速率为0.95,结束温度为1e-8。最后调用 `simulated_annealing()` 函数求解香蕉函数的全局最优解,并输出结果。
运行上面的代码,可以得到如下输出结果:
```
Best solution: x = 1.0000, y = 1.0000, energy = 0.0000
```
可以看到,模拟退火算法成功找到了香蕉函数的全局最优解,x 和 y 的值均为1,能量值为0。