чмы лаба 3 Паша

 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
#include <iostream>
#include <math.h>
using std::cout;
using std::endl;
#define fi 1.6180
#define pi 3.1416
#define eps 0.001
#define RETRES double x = (left + right) / 2.0; \
return new pair(x, func(x), steps);
typedef double (*test_function)(double x);
struct pair {
double x, y;
int steps;
pair(double x, double y, int steps): x(x), y(y), steps(steps) { }
};
inline double func(double x) { return sin(x) - x / 2.0; }
struct pair* GoldenSection(double left, double right, test_function func)
{
int steps = 0;
while (right - left > eps) {
steps++;
double x1 = right - (right - left) / fi;
double x2 = left + (right - left) / fi;
if (func(x1) > func(x2)) left = x2;
else right = x1;
}
RETRES
}
struct pair* Bifurcation(double left, double right, test_function func)
{
int steps = 0;
double delta = eps / 2.0;
while (right - left > 2 * eps) {
steps++;
double x = (left + right) / 2.0;
if (func(x - delta) == func(x + delta)) break;
if (func(x - delta) < func(x + delta)) right = x;
else left = x;
}
RETRES
}
int main()
{
struct pair* result;
//=================================================
cout << "Golden Section method: " << endl;
result = GoldenSection(-pi, 2 * pi, func);
cout << "x = " << result->x << endl;
cout << "y = " << result->y << endl;
cout << "steps = " << result->steps << endl;
delete result;
//=================================================
cout << "Bifurcation method: " << endl;
result = Bifurcation(-pi, 2 * pi, func);
cout << "x = " << result->x << endl;
cout << "y = " << result->y << endl;
cout << "steps = " << result->steps << endl;
delete result;
//=================================================
getchar();
return 0;
}