Чмы лаба 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
#include <iostream>
#include <math.h>
#define phi 1.618034
float abs(float a){
return (a >= 0) ? a : -a;
}
float f(float x){
return -sin(x);
}
float goldSection(float a, float b, float eps){
float x1 = b - (b - a)/phi,
x2 = a + (b - a)/phi,
x;
float y1 = f(x1),
y2 = f(x2);
if(y1 >= y2)
a = x1;
else
b = x2;
if (abs(b - a) < eps)
return x = (a + b)/2;
else return x = goldSection(a, b, eps);
}
float bifurcatio(float a, float b, float eps){
float x0 = (b + a)/2.0,
delta = eps/2.0,
x;
if (b - a < 2 * eps)
return (a + b)/2;
if (f(x0 - delta) == f(x0 + delta))
return (a + b)/2;
else if(f(x0 - delta) < f(x0 + delta))
return bifurcatio(a, x0, eps);
else
return bifurcatio(x0, b, eps);
if (abs(b - a) < eps)
return x = (a + b)/2;
else return x = goldSection(a, b, eps);
}
int main(){
float a, b, eps;
std::cout << "input left bound:\t";
std::cin >> a;
std::cout << "input right bound:\t";
std::cin >> b;
std::cout << "input error value:\t";
std::cin >> eps;
std::cout << f(goldSection(a, b, eps)) << std::endl;
std::cout << f(bifurcatio(a, b, eps)) << std::endl;
return 0;
}