include iostream using std cout using std endl define fi 618 define ep

 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
#include <iostream>
using std::cout;
using std::endl;
#define fi 1.618
#define eps 0.01
typedef double (*test_function)(double x);
struct pair {
double x, y;
pair(double x, double y): x(x), y(y) { }
};
inline double func(double x) { return (x - 1) * (x - 1); }
struct pair* GoldenSection(double left, double right, test_function func)
{
while (right - left > eps) {
double x1 = right - (right - left) / fi;
double x2 = left + (right - left) / fi;
if (func(x1) > func(x2)) left = x1;
else right = x2;
}
double x = (left + right) / 2.0;
return new pair(x, func(x));
}
/*
double TernarySearch(double left, double right, test_function func)
{
}
*/
int main()
{
struct pair* result;
cout << "Golden Section method: " << endl;
result = GoldenSection(0, 2, func);
cout << "x = " << result->x << endl;
cout << "y = " << result->y << endl;
getchar();
delete result;
return 0;
}