ЧМЫ 4

 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
#include <iostream>
#include <math.h>
using std::cout;
using std::endl;
#define y_eps 0.01
#define x_eps 0.01
#define newton_print(p, x) cout << "Start point " << p << ": (" << x << ", " << function(x) << ")" << endl
#define binary_print(l, r, x) cout << "Segment [" << l << ", " << r << "]: (" << x << ", " << function(x) << ")" << endl
double function(double x) { return x*x*x - 3*x*x + 3; }
double derivative(double x) { return 3*x*x - 6*x; }
int sign(double x) { return (x > 0) ? 1 : -1; }
double NewtonMethod(double x) {
while (abs(function(x)) > y_eps) {
x -= function(x) / derivative(x);
}
return x;
}
double BinarySearch(double left, double right) {
while (abs(right - left) > x_eps) {
double mid = (left + right) / 2;
(sign(function(left)) != sign(function(mid))) ? right = mid: left = mid;
}
return (left + right) / 2;
}
int main() {
double x;
cout << "F(x) = x^3 - 3x^2 + 3;" << endl;
cout << "Newton method:" << endl;
newton_print(-2, NewtonMethod(-2));
newton_print(1, NewtonMethod(1));
newton_print(3, NewtonMethod(3));
cout << "Binary search:" << endl;
binary_print(-2, 0, BinarySearch(-2, 0));
binary_print(0, 2, BinarySearch(0, 2));
binary_print(2, 5, BinarySearch(2, 5));
getchar();
return 0;
}