python实现模拟退火算法

模拟退火算法(Simulated Annealing, SA)是一种启发式随机搜索算法,它模仿了物理学中固体物质的退火过程。在求解组合优化问题时,模拟退火算法从某一较高初温开始,伴随温度参数的不断下降,结合概率突跳特性在解空间中随机寻找目标函数的全局最优解。

以下是一个简单的 Python 实现模拟退火算法的示例,用于解决函数的最优化问题(例如寻找函数 f(x) = x^2 的最小值):

import math  
import random  
  
# 目标函数,例如 f(x) = x^2  
def objective_function(x):  
    return x ** 2  
  
# 模拟退火算法  
def simulated_annealing(initial_temp, min_temp, cooling_rate, max_iter, x_start):  
    current_x = x_start  
    current_energy = objective_function(current_x)  
    best_x = current_x  
    best_energy = current_energy  
    temp = initial_temp  
  
    for i in range(max_iter):  
        # 产生新解  
        new_x = current_x + random.uniform(-1, 1)  
        new_energy = objective_function(new_x)  
  
        # 判断是否接受新解  
        if new_energy < current_energy:  
            current_x = new_x  
            current_energy = new_energy  
            if new_energy < best_energy:  
                best_x = new_x  
                best_energy = new_energy  
        else:  
            # 以一定概率接受较差的解  
            if random.random() < math.exp(-(new_energy - current_energy) / temp):  
                current_x = new_x  
                current_energy = new_energy  
  
        # 降温  
        temp *= cooling_rate  
  
        # 判断是否终止  
        if temp < min_temp:  
            break  
  
    return best_x, best_energy  
  
# 参数设置  
initial_temp = 100  # 初始温度  
min_temp = 0.01     # 最小温度  
cooling_rate = 0.95 # 降温率  
max_iter = 1000     # 最大迭代次数  
x_start = 5         # 初始解  
  
# 运行模拟退火算法  
best_x, best_energy = simulated_annealing(initial_temp, min_temp, cooling_rate, max_iter, x_start)  
print(f"Best x: {best_x}, Best energy: {best_energy}")

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孺子牛 for world

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值