Simulated Annealing algorithm 是一种通用的随机搜索算法,是一种理论上的全局优化算法。它模拟了物理的
退火过程,由一个给定的初始高温开始,利用具有概率突跳特性的Metropolis策略在解空间中随机进行搜索,
伴随温度的不断下降重复抽样,直到得到全局最优解。When temperature T is high, the transition probability
from old state to new state is close to one, So SA algorithm can globally search in phase space. If the
temperature is low, the transition probability is close to zero, SA can only search in local phase space.
模拟退火算法是局部邻域搜索的推广,局部邻域搜索算法的结果完全依赖初始解和邻域的结构,而且只能
搜索到局部最优解。
//----------------------
#include<stdio.h>#include<math.h>
#include<stdlib.h>
#include<time.h>
//----------------------
#define Maxx 4
#define Minx -4
#define Maxy 4
#define Miny -4
#define TimeStepNum 10000
#define StepLength 0.2 //邻域搜索步长
#define InitTemp 10.0 //开始温度
#define FinalTemp 0.1 //结束温度
//---------------------
double function(int x,int y);
void metropolis( double temp);
//---------------------
double x,y,f;
int main()
{
srand((unsigned)time(NULL));
double temp; //温度
int i;
x=8.0*random()/RAND_MAX-4;
y=8.0*random()/RAND_MAX-4;
f=function(x,y);
for(temp=InitTemp;temp>FinalTemp; temp*=0.99)
{
for(i=0;i<StepLength;i++) metropolis(temp);
}
}
//目标函数
double function(int x,int y)
{
return sin(x*y)+x*x+y*y;
}
void metropolis( double temp)
{
double xold = x;
double yold = y;
x=x+2,0*StepLength*(1.0*rand()/RAND_MAX-0.5);
y=y+2,0*StepLength*(1.0*rand()/RAND_MAX-0.5);
if(x<Maxx&&x>Minx&&y<Maxy&&y>Miny)
{
double fnew = function(x,y);
if(exp(-(fnew-f)/temp)<rand()/RAND_MAX)
{
f=fnew;
}
else
{
x=xold;
y=yold;
}
}
}