java实现模拟退火算法求解xsin(x)cos(2x)-2xsin(3x)+3xsin(4*x)最小值问题。
import static java.lang.Math.*;
//模拟退火算法
public class SimulatedAnnealingAlg {
public static double f(double x){
return x*sin(x)*cos(2*x)-2*x*sin(3*x)+3*x*sin(4*x);
}
public static void main(String[] args) {
double tempreture = 1000000;
double deltaT = 0.99;
double eps = 1e-14;//结束的条件
int upLimit = 50;
int downLimit = 0;
double lastx = random()*(upLimit-downLimit)+downLimit;
double currentx;
double bestX = 0;
while(tempreture>eps){
currentx = lastx+2*(random()-0.5)*tempreture;
if(currentx>upLimit){
currentx = upLimit;
}
if(currentx<downLimit){
currentx = downLimit;
}//越界判断
if(f(lastx)>f(currentx)){
lastx = currentx;
}else {
if(Math.exp(-abs(f(bestX)-f(currentx)/tempreture))>random()){
lastx = currentx;
}
}
if(f(lastx)<f(bestX)){
bestX = lastx;
}
System.out.println(lastx+" "+f(bestX));
tempreture = tempreture*deltaT;
}
}
}
第3030轮最优解(x,y):46.69687542916031 -215.56830769946862
第3031轮最优解(x,y):46.69687542916031 -215.56830769946862
第3032轮最优解(x,y):46.69687542916031 -215.56830769946862
第3033轮最优解(x,y):46.69687542916031 -215.56830769946862
第3034轮最优解(x,y):46.69687543437313 -215.56830769946865
第3035轮最优解(x,y):46.69687543437313 -215.56830769946865
第3036轮最优解(x,y):46.69687543467556 -215.56830769946885
第3037轮最优解(x,y):46.69687543467556 -215.56830769946885
第2988轮最优解(x,y):46.69687544276722 -215.56830769946873
第2989轮最优解(x,y):46.69687544276722 -215.56830769946873
第2990轮最优解(x,y):46.69687544276722 -215.56830769946873
第2991轮最优解(x,y):46.69687543368501 -215.56830769946885
第2992轮最优解(x,y):46.69687543368501 -215.56830769946885
第2993轮最优解(x,y):46.69687543368501 -215.56830769946885
第3200轮最优解(x,y):46.69687542954948 -215.56830769946882
第3201轮最优解(x,y):46.69687542954948 -215.56830769946882
第3202轮最优解(x,y):46.69687542954948 -215.56830769946882
第3203轮最优解(x,y):46.69687543377289 -215.56830769946885
第3204轮最优解(x,y):46.69687543377289 -215.56830769946885
第3205轮最优解(x,y):46.69687543377289 -215.56830769946885
第3206轮最优解(x,y):46.69687543377289 -215.56830769946885
三次实验的结果,大约能在3000次左右得到在0,50里面的最小的解,性能还是不错的!