模拟退火算法(Simulated Annealing, SA)是一种用于全局优化的启发式搜索算法,它模仿了物理学中金属退火的过程。该算法在搜索空间中逐步降低“温度”,以寻找全局最优解。下面是一个用Java实现模拟退火算法的简单示例。
假设我们要解决的是一个简单的函数优化问题,例如最小化函数 f(x) = x^2
。
import java.util.Random;
public class SimulatedAnnealing {
// 定义目标函数(要最小化的函数)
public static double objectiveFunction(double x) {
return x * x; // 例如 f(x) = x^2
}
// 初始化当前解
public static double initializeSolution(double lowerBound, double upperBound) {
Random rand = new Random();
return lowerBound + rand.nextDouble() * (upperBound - lowerBound);
}
// 生成一个新的解(当前解的邻域解)
public static double generateNeighbor(double currentSolution, double stepSize) {
Random rand = new Random();
return currentSolution + (rand.nextDouble() - 0.5) * 2 * stepSize;
}
// 模拟退火算法
public static double simulatedAnnealing(double lowerBound, double upperBound, double initialTemp, double coolingRate, int maxIterations) {
double currentSolution = initializeSolution(lowerBound, upperBound);
double currentEnergy = objectiveFunction(currentSolution);
double temperature = initialTemp;
for (int i = 0; i < maxIterations; i++) {
// 生成一个新的解
double neighborSolution = generateNeighbor(currentSolution, temperature);
double neighborEnergy = objectiveFunction(neighborSolution);
// 接受新解的概率
if (neighborEnergy < currentEnergy || Math.exp((currentEnergy - neighborEnergy) / temperature) > Math.random()) {
currentSolution = neighborSolution;
currentEnergy = neighborEnergy;
}
// 降低温度
temperature *= coolingRate;
// 输出当前状态(可选)
System.out.println("Iteration " + i + ": Solution = " + currentSolution + ", Energy = " + currentEnergy + ", Temperature = " + temperature);
}
return currentSolution;
}
public static void main(String[] args) {
double lowerBound = -100.0;
double upperBound = 100.0;
double initialTemp = 100.0;
double coolingRate = 0.99;
int maxIterations = 1000;
double bestSolution = simulatedAnnealing(lowerBound, upperBound, initialTemp, coolingRate, maxIterations);
System.out.println("Best Solution Found: " + bestSolution);
System.out.println("Objective Function Value: " + objectiveFunction(bestSolution));
}
}
代码解释
- 目标函数:
objectiveFunction(double x)
:定义了我们要最小化的目标函数f(x) = x^2
。
- 初始化当前解:
initializeSolution(double lowerBound, double upperBound)
:在给定范围内随机生成一个初始解。
- 生成新的解:
generateNeighbor(double currentSolution, double stepSize)
:生成当前解的邻域解,即在当前解的基础上添加一个随机扰动。
- 模拟退火算法:
simulatedAnnealing(double lowerBound, double upperBound, double initialTemp, double coolingRate, int maxIterations)
:实现了模拟退火算法的主要逻辑。- 初始化当前解和当前能量。
- 在每次迭代中,生成一个新的解,并计算其能量。
- 根据接受新解的概率(基于当前能量和邻域解的能量以及当前温度)决定是否接受新解。
- 降低温度。
- 输出当前状态(可选)。
- 主函数:
- 在主函数中,设置了算法的参数(如边界、初始温度、冷却率和最大迭代次数),并调用
simulatedAnnealing
方法。 - 输出找到的最佳解及其目标函数值。
- 在主函数中,设置了算法的参数(如边界、初始温度、冷却率和最大迭代次数),并调用
这个示例展示了一个基本的模拟退火算法的实现。实际应用中,你可能需要根据具体问题调整目标函数、初始解生成方式、邻域解生成方式、温度初始值和冷却率等参数。