模拟退火算法实现实例

import math
import random

# 定义目标函数(示例为一个简单的二维函数)
def cost_function(x, y):
    return (x - 2) ** 2 + (y + 3) ** 2

# 定义模拟退火算法
def simulated_annealing(cost_func, x_init, y_init, temp_init, temp_final, alpha, max_iter):
    
    # 初始化当前解和当前解对应的成本
    x_curr = x_init
    y_curr = y_init
    cost_curr = cost_func(x_curr, y_curr)
    
    # 初始化最优解和最优解对应的成本
    x_best = x_curr
    y_best = y_curr
    cost_best = cost_curr
    
    # 初始化温度
    temp_curr = temp_init
    
    # 迭代搜索
    for _ in range(max_iter):
        
        # 生成新解
        x_new = x_curr + random.uniform(-1, 1)
        y_new = y_curr + random.uniform(-1, 1)
        
        # 边界处理(根据实际问题进行修改)
        x_new = max(min(x_new, 10), -10)
        y_new = max(min(y_new, 10), -10)
        
        # 计算新解的成本
        cost_new = cost_func(x_new, y_new)
        
        # 计算成本变化
        cost_delta = cost_new - cost_curr
        
        # 判断是否接受新解
        if cost_delta < 0 or math.exp(-cost_delta / temp_curr) > random.random():
            x_curr = x_new
            y_curr = y_new
            cost_curr = cost_new
            
            # 更新最优解
            if cost_curr < cost_best:
                x_best = x_curr
                y_best = y_curr
                cost_best = cost_curr
        
        # 降低温度
        temp_curr *= alpha
    
    return x_best, y_best, cost_best

# 示例运行
x_init = random.uniform(-10, 10)
y_init = random.uniform(-10, 10)
temp_init = 100
temp_final = 0.1
alpha = 0.95
max_iter = 1000

x_best, y_best, cost_best = simulated_annealing(cost_function, x_init, y_init, temp_init, temp_final, alpha, max_iter)

print("最优解:", x_best, y_best)
print("最优解对应的成本:", cost_best)

本文仅为学习记录,如有错误欢迎指出。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值