double f1 double double double return exp -z double f2 double double d

 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
double f1(double x, double y, double z)
{
return 2 * x - y - exp(-z);
}
double f2(double x, double y, double z)
{
return -x + 2 * y*y - exp(-z);
}
double f3(double x, double y, double z)
{
return exp(x) + y + z;
}
double f11(double x, double y, double z)
{
return 2;
}
double f12(double x, double y, double z)
{
return -1;
}
double f13(double x, double y, double z)
{
return exp(-z);
}
double f21(double x, double y, double z)
{
return -1;
}
double f22(double x, double y, double z)
{
return 4 * y;
}
double f23(double x, double y, double z)
{
return exp(-z);
}
double f31(double x, double y, double z)
{
return exp(x);
}
double f32(double x, double y, double z)
{
return 1;
}
double f33(double x, double y, double z)
{
return 1;
}
void gradDescent(std::vector<double> &x, std::vector<std::vector<double>> &iters)
{
double lambda = 1e-2;
std::vector<double> xNext;
std::vector<std::vector<double> > J(3, std::vector<double>(3, 0));
double(*P[3][3])(double, double, double) = { { f11, f12, f13 }, { f21, f22, f23 }, { f31, f32, f33 } };
double norm = 0;
do
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
J[i][j] = P[i][j](x[0], x[1], x[2]);
}
}
transposition(J);
std::vector < std::vector<double>> F(3, std::vector<double>(1, 0));
F[0][0] = f1(x[0], x[1], x[2]);
F[1][0] = f2(x[0], x[1], x[2]);
F[2][0] = f3(x[0], x[1], x[2]);
std::vector < std::vector<double>> temp(3, std::vector<double>(1, 0));
multiply(J, F, temp);
xNext = { temp[0][0], temp[1][0], temp[2][0] };
for (int i = 0; i < 3; ++i)
{
xNext[i] = x[i] - lambda*xNext[i];
}
norm = 0;
for (int i = 0; i < 3; ++i)
{
norm = std::max(fabs(xNext[i] - x[i]), norm);
}
x = xNext;
iters.push_back(x);
} while (norm > eps);
}