模拟退火算法的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; }
相关文章推荐
- YMS Round #1 Div. 2 A Promotion Counting
- 层次分析法的C++实现
- leetcode_258_Add Digit(easy)(C++)
- 遗传算法的C++实现
- C++中++符号的前置和后置的重载格式
- C++中的类成员函数
- c++中int,float,double转string的一个简单方法
- C++类的封装与类库的组成
- 《C++0x漫谈》系列之:Concept, Concept!
- #碰到的小问题#c++中vector<int> 和vector<int>::iterator有什么不同
- 谈谈C++类与主函数的结构安排
- 以OLE方式读写EXCEL的C++类【转载】
- C++进阶—— helper function 的设计与实现
- C++实验2—标准体重
- C语言实现单链表面试题汇总
- C语言32个关键字
- C++有子对象的派生类的构造函数
- C语言32个关键字
- File: f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\winocc.cpp错误
- C++实验2-模拟ATM