-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.cpp
More file actions
98 lines (91 loc) · 2.65 KB
/
Copy pathtest.cpp
File metadata and controls
98 lines (91 loc) · 2.65 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// NB
// turn the std=c++11 feature with g++
// no actions needed with Visual C++ which support C++11 standart
#include <cstdio>
#include <cmath>
#include "ralg.h"
inline double sign(double x)
{
if (x < 0) return -1.;
if (x > 0) return 1.;
return 0.;
}
int main()
{
double x0[2]; x0[0] = 1000; x0[1] = 1000;
double res[2];
ralg_options opt = defaultOptions;
opt.output_iter = 1;
ralg(&opt,
[](const double* x, double& f, double* grad) -> bool
{
f = 1000*(x[0]-3)*(x[0]-3) + x[1]*x[1];
grad[0] = 1000*2*(x[0]-3);
grad[1] = 2*x[1];
return true;
},
2,
x0,
res);
printf("for 1000(x-3)^2 + y^2 -> min the answer is %.2lf %.2lf\n", res[0], res[1]);
ralg(&opt,
[](const double* x, double& f, double* grad) -> bool
{
f = 1000*(x[0]-3)*(x[0]-3) + x[1]*x[1];
grad[0] = 1000*2*(x[0]-3);
grad[1] = 2*x[1];
f = -f; grad[0] = -grad[0]; grad[1] = -grad[1];
return true;
},
2,
x0,
res, RALG_MAX);
printf("for inv 1000(x-3)^2 + y^2 -> max the answer is %.2lf %.2lf\n", res[0], res[1]);
opt.is_monotone = false;
ralg(&opt,
[](const double* x, double& f, double* grad) -> bool
{
f = -(x[0]-3)*(x[0]-3) - 0.001*x[1]*x[1];
grad[0] = -2*(x[0]-3);
grad[1] = -0.001*2*x[1];
return true;
},
2,
x0,
res,
RALG_MIN);
printf("for -(x-3)^2 - 0.001y^2 -> max the answer is %.2lf %.2lf\n", res[0], res[1]);
ralg(&opt,
[](const double* x, double& f, double* grad) -> bool
{
f = fabs(x[0]-3) + 100.*fabs(x[0]+2) + 0.001*fabs(x[1]);
grad[0] = sign(x[0]-3) + 100.*sign(x[0]+2);
grad[1] = 0.001*sign(x[1]);
return true;
},
2,
x0,
res,
RALG_MIN);
printf("for |x-3| + 100|x+2| + 0.001|y| -> min the answer is %.2lf %.2lf\n", res[0], res[1]);
// stress test
int dim = 100;
double* x0_stress = new double[dim];
double* res_stress = new double[dim];
for(int i = 0; i < dim; ++i) x0_stress[i] = 1000.;
ralg(&opt,
[dim](const double* x, double& f, double* grad) -> bool
{
f = 0.;
for(int i = 0; i < dim; ++i) { f += (i+1.) * fabs(x[i] - i - 1); }
for(int i = 0; i < dim; ++i) { grad[i] = (i+1)*sign(x[i]-i-1);}
return true;
},
dim,
x0_stress,
res_stress,
RALG_MIN);
delete [] res_stress;
delete [] x0_stress;
return 0;
}