模拟退火算法Python实现

瞎BB

代码

导入库以及参数设置

import matplotlib.pyplot as plt
import math
import random
T_init = 100  # 初始最大温度
alpha = 0.95  # 降温系数
T_min = 1e-3  # 最小温度,即退出循环条件

目标函数

def obj(x):
    y = 10 * math.sin(5 * x) + 7 * math.cos(4 * x)
    return -y

主函数

def SA(T_init,alpha,T_min):
    T = T_init
    x_new = random.random() * 10#初解
    x_current = x_new
    y_current = float('inf')
    x_best = x_new
    y_best = float('inf')
    while T > T_min:
        for i in range(100):
            delta_x = random.random() - 0.5
            # 自变量变化后仍要求在[0,10]之间
            if 0 < (x_new + delta_x) < 10:
                x_new = x_new + delta_x
            else:
                x_new = x_new - delta_x
            y_new = obj(x_new)
            
            if (y_new<y_current):
                y_current=y_new
                x_current=x_new
                if (y_new<y_best):
                    y_best=y_new
                    x_best=x_new
            else:
                if random.random() < math.exp(-(y_new - y_current) / T):
                    y_current=y_new
                    x_current=x_new
                else:
                    x_new=x_current
        T *= alpha
    print('最优解',x_best,obj(x_best))
SA(T_init,alpha,T_min)
  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值