模拟退火模板_c++

模拟退火算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double solve(){
double T=100; //初始温度
double delta = 0.98; //降温系数
double x=50.0; //x的初始温度
double now=func(x); //计算初始函数值
double ans=now; //返回值
while(T>eps){ //eps是终止温度
int f[2]={1,-1};
double newx = x+f[rand()%2]*T; //按概率改变x,随T的降温而减少
if(newx >= 0 && newx<=100){
double next = func(newx);
ans=min(ans,next);
if(now-next>eps){x=newx;now=next;}
}
T*=delta;
}
return ans;
}