📄 模拟退火算法.cpp
字号:
/*************************************************************
**** 本程序是实现了模拟退火算法 ******
**** 利用模拟退火算法,求出某函数的最小小值 ******
**** 编写者: 张庆贤 ******
***************************************************************/
#include "iostream.h"
#include "stdlib.h"
#include "stdio.h"
#include "math.h"
/********************************
定义常量
********************************/
#define MAX_TP 20000000 //最高温度
#define MIN_TP 1 //控制的最低温度
#define LENGTH 0.01 //步长,各个函数不一样,
#define BK 0.1 //B常数
#define AF 0.95 //温度变化速率
#define debuge 1 //调试信息的控制
/***********************************
目标函数
************************************/
double fun(double x)
{
int a,b,c;
a=-4;
b=-8;
c=-12;
return (a*x*x+b*x+c);
}
/***********************************************
模拟退火算法
************************************************/
double sa()
{
double old_x,new_x;//变量
double tempt=MAX_TP;
double old_eg,new_eg;//能量函数
double dx; //符号
//随机的产生一个初试值
old_x=(double)(rand()%2);
old_eg=fun(old_x);
/*************************
逐渐降温的过程
**************************/
while(tempt>MIN_TP)
{
dx=(double)(rand()%3);
if(dx>1.5)
dx=1;
else
dx=-1;
//length=(float(rand()%30))/60;
//做调试的时候用的输出
//cout<<" length="<<dx*length;
//***************************
new_x=(double)(old_x+dx*LENGTH);
new_eg=fun(new_x);
if((old_eg-new_eg)<0)
{
old_x=new_x;
old_eg=new_eg;
}
else
{
double rd=(double)(rand()%100);
double p;
/**************************************
在本程序中有加0.8有一定的理论依据
**************************************/
rd=rd/100+0.8;
p=exp(-(old_eg-new_eg)/(BK*tempt));
//**************************************
#if debuge
cout<<" rd="<<rd<<" p="<<p<<'\n';
#endif
//*****************************************
if(p>rd)
{
//接受不正常情况下的扰动
old_x=new_x;
old_eg=new_eg;
}
else
{
}
}
/************************************
降温
************************************/
if(old_x!=new_x)
{
tempt=tempt*AF;
}
//**************************************
#if debuge
cout<<" old_x="<<old_x<<'\n';
cout<<"fun="<<fun(old_x)<<'\n';
#endif
//***************************************
}
return(old_x);
}
void main()
{
double a;
a=sa();
cout<<"the min "<<fun(a)<<'\n';
cout<<"min x="<<a;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -