在人工智能、运筹学和计算机科学中,模拟退火算法是一种非常经典且实用的优化算法。它灵感来源于冶金学中的“退火”过程——通过缓慢降温使金属内部结构趋于稳定,从而获得低能量状态。本教程将手把手教你如何用Java语言实现模拟退火,即使是编程小白也能轻松上手!
模拟退火算法(Simulated Annealing, SA)是一种概率型全局优化算法,用于在大规模搜索空间中寻找近似最优解。与贪心算法不同,它允许在一定条件下接受“更差”的解,从而跳出局部最优,探索更优的全局解。
下面我们以经典的一维函数最小化问题为例:最小化函数 f(x) = x² - 10*cos(2πx) + 10(Rastrigin函数简化版),其中 x ∈ [-5.12, 5.12]。
public static double objectiveFunction(double x) { return x * x - 10 * Math.cos(2 * Math.PI * x) + 10;}
import java.util.Random;public class SimulatedAnnealing { private static final Random random = new Random(); public static void main(String[] args) { // 参数设置 double temperature = 1000; // 初始温度 double coolingRate = 0.95; // 降温速率 int maxIterations = 10000; // 最大迭代次数 // 随机初始化解 double currentX = -5.12 + random.nextDouble() * (5.12 - (-5.12)); double currentEnergy = objectiveFunction(currentX); double bestX = currentX; double bestEnergy = currentEnergy; for (int i = 0; i < maxIterations; i++) { // 生成邻域新解 double newX = currentX + (random.nextDouble() - 0.5) * 2; // 边界处理 newX = Math.max(-5.12, Math.min(5.12, newX)); double newEnergy = objectiveFunction(newX); double delta = newEnergy - currentEnergy; // Metropolis 准则 if (delta < 0 || Math.exp(-delta / temperature) > random.nextDouble()) { currentX = newX; currentEnergy = newEnergy; // 更新全局最优 if (currentEnergy < bestEnergy) { bestX = currentX; bestEnergy = currentEnergy; } } // 降温 temperature *= coolingRate; } System.out.println("最优解 x = " + bestX); System.out.println("最小值 f(x) = " + bestEnergy); } public static double objectiveFunction(double x) { return x * x - 10 * Math.cos(2 * Math.PI * x) + 10; }}
| 参数 | 说明 |
|---|---|
| 初始温度(temperature) | 越高越容易接受劣解,建议设为较大值(如1000) |
| 降温速率(coolingRate) | 通常在0.8~0.99之间,值越大降温越慢 |
| 最大迭代次数 | 控制算法运行时间,防止无限循环 |
相比梯度下降等局部搜索方法,模拟退火算法具有以下优势:
通过本教程,你已经掌握了如何用Java实现模拟退火来解决优化问题。无论是旅行商问题(TSP)、排课调度,还是机器学习超参数调优,模拟退火算法都是一种强大而灵活的工具。希望这篇优化算法教程能为你打开智能算法入门的大门!
提示:你可以尝试修改目标函数、调整参数,观察结果变化,加深理解。
本文由主机测评网于2025-12-11发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025126303.html