00001 #include <TooN/optimization/golden_section.h>
00002 #include <TooN/optimization/conjugate_gradient.h>
00003 #include <iostream>
00004 #include <cmath>
00005 #include <cassert>
00006 #include <cstdlib>
00007
00008 using namespace TooN;
00009 using namespace std;
00010
00011 double sq(double d)
00012 {
00013 return d*d;
00014 }
00015
00016 double Rosenbrock(const Vector<2>& v)
00017 {
00018 return sq(1 - v[0]) + 100 * sq(v[1] - sq(v[0]));
00019 }
00020
00021 Vector<2> RosenbrockDerivatives(const Vector<2>& v)
00022 {
00023 double x = v[0];
00024 double y = v[1];
00025
00026 Vector<2> ret;
00027 ret[0] = -2+2*x-400*(y-sq(x))*x;
00028 ret[1] = 200*y-200*sq(x);
00029
00030 return ret;
00031 }
00032
00033 int evals=0;
00034
00035 double Spiral(const Vector<2>& v)
00036 {
00037 double x = v[0];
00038 double y = v[1];
00039 evals++;
00040
00041 return sin(20.0*sqrt(x*x+y*y)+2.0*atan(y/x))+2.0*x*x+2.0*y*y;
00042 }
00043
00044
00045 Vector<2> SpiralDerivatives(const Vector<2>& v)
00046 {
00047 double x = v[0];
00048 double y = v[1];
00049
00050 double dx =2.0*(10.0*cos(20.0*sqrt(x*x+y*y)+2.0*atan(y/x))*x*x*x+10.0*cos(20.0*sqrt(x*x+y*y)+2.0*atan(y/x))*x*y*y-cos(20.0*sqrt(x*x+y*y)+2.0*atan(y/x))*y*sqrt(x*x+y*y)+2.0*x*x*x*sqrt(x*x+y*y)+2.0*x*sqrt(x*x+y*y)*y*y)/sqrt(pow(x*x+y*y,3.0));
00051 double dy = 2.0*(10.0*cos(20.0*sqrt(x*x+y*y)+2.0*atan(y/x))*y*x*x+10.0*cos(20.0*sqrt(x*x+y*y)+2.0*atan(y/x))*y*y*y+cos(20.0*sqrt(x*x+y*y)+2.0*atan(y/x))*x*sqrt(x*x+y*y)+2.0*y*sqrt(x*x+y*y)*x*x+2.0*y*y*y*sqrt(x*x+y*y))/sqrt(pow(x*x+y*y,3.0));
00052
00053 return makeVector(dx, dy);
00054 }
00055
00056 int main()
00057 {
00058 ConjugateGradient<2> cg(makeVector(1.5, 1.5), Spiral, SpiralDerivatives);
00059 cg.bracket_initial_lambda=1e-7;
00060
00061 cout << cg.x << " " << cg.y << endl;
00062 while(cg.iterate(Spiral, SpiralDerivatives))
00063 cout << cg.x << " " << cg.y << endl;
00064 cout << cg.x << " " << cg.y << endl;
00065
00066 cerr << "Total evaluations: " << evals << endl;
00067 }
00068