python模拟退火算法代码
时间: 2023-10-30 09:00:27 浏览: 100
智能算法之模拟退火算法代码.rar
当然,我可以为您提供一个简单的Python模拟退火算法的代码示例。以下是一个基本的实现:
```python
import math
import random
def simulated_annealing(cost_func, initial_solution, initial_temperature, cooling_rate):
current_solution = initial_solution
best_solution = initial_solution
current_temperature = initial_temperature
while current_temperature > 0.01:
neighbor = generate_neighbor(current_solution)
current_cost = cost_func(current_solution)
neighbor_cost = cost_func(neighbor)
delta_cost = neighbor_cost - current_cost
if delta_cost < 0:
current_solution = neighbor
if neighbor_cost < cost_func(best_solution):
best_solution = neighbor
elif random.random() < math.exp(-delta_cost / current_temperature):
current_solution = neighbor
current_temperature *= cooling_rate
return best_solution
# 定义一个简单的代价函数(示例)
def cost_func(solution):
# 假设我们要最小化的目标是一个简单的二维函数 f(x, y) = (x-3)^2 + (y-4)^2
x, y = solution
return (x - 3) ** 2 + (y - 4) ** 2
# 生成一个邻居解(示例)
def generate_neighbor(solution):
x, y = solution
return (x + random.uniform(-0.1, 0.1), y + random.uniform(-0.1, 0.1))
# 设置初始解、初始温度和冷却率
initial_solution = (0, 0)
initial_temperature = 100
cooling_rate = 0.99
# 运行模拟退火算法
best_solution = simulated_annealing(cost_func, initial_solution, initial_temperature, cooling_rate)
print("最优解:", best_solution)
```
请注意,以上代码只是模拟退火算法的一个基本实现,您可以根据自己的具体问题进行修改和扩展。
阅读全文