理论部分参考《Practical Optimization》中4.4节,代码如下:
OneDimensionalOptimization。h
#ifndef _OneDimensionalOptimization_ #define _OneDimensionalOptimization_ #include <algorithm> using namespace std; class OneDimensionalOptimization { public: //参考《Practical Optimization》中4.4节 double goldenSectionSearch(double(*p)(double x),double& l, double& u, double& x, double tol = 1e-6); }; #endif
OneDimensionalOptimization.cpp
#include "OneDimensionalOptimization.h" double OneDimensionalOptimization::goldenSectionSearch(double(*p)(double x),double& l, double& u,double& x, double tol) { //1) double xlk = l; double xuk = u; //2) double I1 = xuk - xlk; double K = 1.618034; double Ikp1 = I1 / K; double xak = xuk - Ikp1; double xbk = xlk + Ikp1; double fak = p(xak); double fbk = p(xbk); //3) while(true) { double Ikp2 = Ikp1 / K; if(fak >= fbk) { xlk = xak; xuk = xuk; xak = xbk; xbk = xlk + Ikp2; fak = fbk; fbk = p(xbk); } else { xlk = xlk; xuk = xbk; xak = xuk - Ikp2; xbk = xak; fbk = fak; fak = p(xak); } Ikp1 = Ikp2; //4) if(Ikp2 < tol || xak > xbk) { if(fak > fbk) x = 0.5 * (xbk + xuk); if(fak == fbk) x = 0.5 * (xak + xbk); if(fak < fbk) x = 0.5 * (xlk + xak); l = xlk; u = xuk; return p(x); } } }
测试代码主程序:
main.cpp
#include "src\Optimizer\OneDimensionalOptimization.h" #include <fstream> using namespace std; double p(double x) { return -sin(x); } int main(int argv, char** argc) { OneDimensionalOptimization* one = new OneDimensionalOptimization(); double l = 0; double u = 2*3.1415926; double x; double res = one->goldenSectionSearch(p,l,u,x,1e-5); return 1; }
该方法的收敛结果误差较大。