您的位置:首页 > 编程语言 > C语言/C++

模拟退火算法的C++实现

2016-03-20 10:48 405 查看
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;

const int inf = 0xffffff;

const double pi = acos(-1.0);

inline double f(double& x)
{
return sin(x) + cos(x);
}

inline void randval(double * s)
{
* s = fmod((* s + pi) * (* s + pi) * (* s + pi) * (* s + pi) * (* s + pi), 1.0);
}

inline int accept(double& Ecurrent, double& Enew, double T, double& s)
{
double dE = Enew - Ecurrent;

if(dE < 0.0)
return 1;
if(s < exp(-dE / T))
return 1;
else
return 0;
}

int main()
{
cout << "Finding the minimum via simulating annealing:" << endl;

double xlow = 0.0;
double xhigh = 4.0;
double Tmax = 500.0;
double Tmin = 1.0;
double Tstep = 0.01;

double s = 0.118; // seed
randval(&s);

double xcurrent = s * (xhigh - xlow);
double Ecurrent = f(xcurrent);

double minimun = inf;
double xValue;

for(int T = Tmax; T > Tmin; T -= Tstep)
{
randval(&s);

double xnew = s * (xhigh - xlow);
double Enew = f(xnew);

if(accept(Ecurrent, Enew, T, s) != 0)
{
xcurrent = xnew;
Ecurrent = Enew;
} // end for loop

if(f(xcurrent) < minimun)
{
minimun = f(xcurrent);
xValue = xcurrent;
}

cout << "The minimun found is " << Ecurrent << " at x = " << xcurrent << endl;
}

cout << "============================================" << endl;
cout << "The final minimun is " << minimun << " at x = " << xValue << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: