include iostream include math using namespace std double double return

 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
#include <iostream>
#include <math.h>
using namespace std;
double f(double x) {
return pow(x, 2) + 5 * pow(x, 3); // x^2 + 5 * x^3
}
double find(double a, double b, double e, bool findMax) {
double phi = (1 + sqrt(5)) / 2;
double x1, x2, delta;
while (b - a > e) {
delta = (b - a) / phi();
x1 = b - delta;
x2 = a + delta;
if (findMax) {
if (f(x1) <= f(x2)) {
a = x1;
} else {
b = x2;
}
} else {
if (f(x1) >= f(x2)) {
a = x1;
} else {
b = x2;
}
}
}
return (a + b) / 2;
}
int main() {
double a, b, e;
int value;
cout << "Enter a:";
cin >> a;
cout << "Enter b:";
cin >> b;
cout << "Enter epsilon:";
cin >> e;
cout << "If u want find maximum enter 1 or enter any value for find minimum:";
cin >> value;
double x = find(a, b, e, value == 1);
cout << endl << "x = " << x << "; F(x) = " << f(x);
}