ЧСМ 5 лаба

 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
#include "stdafx.h"
#include <iostream>
#include <math.h>
#define e 0.0001
double f(double x) { return x*x*x - 8*x*x + 4; }
double f1(double x) { return 3*x*x - 16*x; }
double BinarySearch(double a, double b) {
int count = 1;
double c;
while(true) {
if (b-a >2*e) {
c = (a+b)/2;
if (f(a)*f(c) >0) {
a = c;
} else {
b = c;
}
count++;
} else {
printf("i = %d\t", count);
return (a+b)/2;
}
}
}
double NewtonMethod(double a, double b) {
double x = (a+b)/2;
x -= f(x) / f1(x);
int count = 1;
while (true) {
if(abs(f(x)) > e) {
x -= f(x) / f1(x);
count++;
} else {
printf("i = %d\t", count);
return x;
}
}
}
int main() {
double x;
printf("f(x) = x^3 - 8*x^2 + 2\n");
printf("Binary search\n");
printf("[-1, -0.5]: x = %f, f(x) = %.10f \n", x = BinarySearch(-1, -0.5), f(x));
printf("[0.5, 1]: x = %f, f(x) = %.10f \n", x = BinarySearch(0.5, 1), f(x));
printf("[7, 9]: x = %f, f(x) = %.10f \n", x = BinarySearch(7, 9), f(x));
printf("Newton method\n") ;
printf("[-1, -0.5]: x = %f, f(x) = %.10f \n", x = NewtonMethod(-1, -0.5), f(x));
printf("[0.5, 1]: x = %f, f(x) = %.10f \n", x = NewtonMethod(0.5, 1), f(x));
printf("[7, 9]: x = %f, f(x) = %.10f \n", x = NewtonMethod(7, 9), f(x));
return 0;
}