include iostream include math using namespace std class GoldenRatio pr

 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
#include <iostream>
#include <math.h>
using namespace std;
class GoldenRatio {
private:
static const double phi = 1.61803; // (1 + sqrt(5)) / 2
public:
double static f(double x) {
return (x + 1) * (x + 1) * (x + 1) + 5 * x * x;
}
double static min(double a, double b, double e){
double x1, x2;
while (true){
x1 = b - (b - a) / phi;
x2 = a + (b - a) / phi;
if (f(x1) >= f(x2))
a = x1;
else
b = x2;
if (abs(b - a) < e)
break;
}
return (a + b) / 2;
}
double static max(double a, double b, double e){
double x1, x2;
while (true){
x1 = b - (b - a) / phi;
x2 = a + (b - a) / phi;
if (f(x1) <= f(x2))
a = x1;
else
b = x2;
if (abs(b - a) < e)
break;
}
return (a + b) / 2;
}
};
int main() {
cout << GoldenRatio::min(-2, 2, 0.01);
}