aboutsummaryrefslogtreecommitdiffstats
path: root/test/test_cg.cpp
blob: b32c783387b8047158af331109a89d6929c45d3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <methods/conjugate_gradient/conjugate_gradient.hpp>
#include <methods/powell/powell_method.hpp>
#include <vector>
using namespace std;

using namespace opt_utilities;

class foo
  :public diff_func_obj<double,vector<double> >
{
  foo* do_clone()const
  {
    return new foo(*this);
  }

  double do_eval(const vector<double>& p)
  {
    static int call_cnt=0;
    ++call_cnt;
    //cerr<<call_cnt<<endl;
    double result=0;
    for(int i=0;i<p.size();++i)
      {
	result+=p[i]*p[i];
      }
    return result;
  }

  vector<double> do_gradient(const vector<double>& p)
  {
    static int call_cnt=0;
    ++call_cnt;
    cerr<<call_cnt<<endl;
    vector<double> result(p.size());
    for(int i=0;i<p.size();++i)
      {
	result[i]=2*p[i];
      }
    return p;
  }
};


int main()
{
  optimizer<double,vector<double> > opt;
  opt.set_opt_method(conjugate_gradient<double,vector<double> >());
  //opt.set_opt_method(powell_method<double,vector<double> >());
  opt.set_func_obj(foo());
  std::vector<double> p(300);
  for(int i=0;i<p.size();++i)
    {
      p[i]=100;
    }
  opt.set_start_point(p);
  p=opt.optimize();
  cout<<p[0]<<"\t"<<p[1]<<endl;
}