methods - lab4

 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
69
70
71
public class Main {
public static Double f1(Double x) {
return 3 * Math.pow(x, 2) + 6 * x;
}
public static Double f(Double x) {
return Math.pow(x, 3) + 3 * Math.pow(x, 2) - 2;
}
public static void methodBi(Double a, Double b, Double e) {
Double A = a;
Double B = b;
Double C;
int count = 0;
for (;;) {
if (B - A > 2 * e) {
C = (A + B) / 2;
if (f(A) * f(C) > 0) {
A = C;
} else {
B = C;
}
count++;
} else {
//return (A + B) / 2;
System.out.print((A + B) / 2);
System.out.print("\t\t");
System.out.println(count);
return;
}
}
}
public static void methodNewton(Double a, Double b, Double e) {
Double x0 = (a + b) / 2;
Double x1 = x0 - f(x0) / f1(x0);
int count = 1;
for(;;) {
if (Math.abs(f(x1)) < e) {
System.out.print(x1);
System.out.print("\t");
System.out.println(count);
return;
//return x1;
}
x0 = x1;
x1 = x0 - f(x0) / f1(x0);
count ++;
}
}
public static void main(String[] args){
System.out.println("x\t\t\tsteps");
System.out.println("Method Bi-sections");
//System.out.println(methodBi(-1.5, 0.0, 0.001));
//System.out.println(methodBi(-3.5, -2.0, 0.001));
//System.out.println(methodBi(0.0, 1.5, 0.001));
methodBi(-1.5, 0.0, 0.001);
methodBi(-3.5, -2.0, 0.001);
methodBi(0.0, 1.5, 0.001);
System.out.println("Newton's method");
//System.out.println(methodNewton(-1.5, 0.0, 0.001));
//System.out.println(methodNewton(-3.5, -2.0, 0.001));
//System.out.println(methodNewton(0.0, 1.5, 0.001));
methodNewton(-1.5, 0.0, 0.001);
methodNewton(-3.5, -2.0, 0.001);
methodNewton(0.0, 1.5, 0.001);
}
}