模拟退火算法,是一种基于蒙特卡洛思想的全局优化算法,模拟金属退火过程中的原子热运动行为。该算法通过接受“劣质解”来避免陷入局部最优,适用于组合优化和连续优化问题。

算法原理

MATLAB程序实现

以下代码以求解 Rastrigin函数 最小值为例,Rastrigin是典型的非线性多峰函数,具有大量局部极小值。 


    % 参数设置
    T_init = 1000;    % 初始温度
    T_end = 1e-3;     % 终止温度
    alpha = 0.95;     % 降温系数
    max_iter = 100;   % 每个温度下的迭代次数
    
    % 目标函数:Rastrigin函数(2维)
    objective = @(x) 20 + x(1)^2 + x(2)^2 - 10*(cos(2*pi*x(1)) + cos(2*pi*x(2)));
    
    % 初始解(随机生成)
    current_solution = 10 * rand(1, 2) - 5; % 范围[-5,5]
    current_energy = objective(current_solution);
    
    % 记录最优解
    best_solution = current_solution;
    best_energy = current_energy;
    
    T = T_init;
    while T > T_end
        for i = 1:max_iter
            % 生成邻域解(加高斯扰动)
            new_solution = current_solution + randn(1,2) * sqrt(T);
            new_energy = objective(new_solution);
            
            % 计算能量差
            delta_E = new_energy - current_energy;
            
            % Metropolis准则判断是否接受新解
            if delta_E < 0 || rand() < exp(-delta_E / T)
                current_solution = new_solution;
                current_energy = new_energy;
                
                % 更新全局最优
                if current_energy < best_energy
                    best_solution = current_solution;
                    best_energy = current_energy;
                end
            end
        end
        % 降温
        T = T * alpha;
    end
    
    % 输出结果
    fprintf('最优解: x = [%.4f, %.4f]\n', best_solution(1), best_solution(2));
    fprintf('最小值: f = %.4f\n', best_energy);

代码解释

  1. 目标函数Rastrigin 函数在 x = [0,0] 处取得全局最小值 0,但存在大量局部极小值。

  2. 邻域生成:通过添加高斯扰动(randn)生成新解,扰动幅度随温度降低而减小。

  3. 接受劣解:通过指数概率 exp(-delta_E / T) 允许暂时接受较差解,避免早熟收敛。

  4. 降温策略:温度按系数 alpha 指数下降,逐步缩小搜索范围。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐