NM4(0, 3, 0.0001)

 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
package labs;
public class Lab4 {
//variant 8
//x^3 + 3x^2 - 3
private static double e;
private static int n = 0;
private static double f(double x) {
return x*x*x + 3*x*x - 3;
}
private static double fx(double x) {
return 3*x*x + 6*x;
}
private static double newton(double c){
double cx = c - f(c)/fx(c);
n++;
if (Math.abs(f(c)) < e) {
return c;
} else {
return newton(cx);
}
}
private static double half(double l, double r){
double center = (l + r)/2;
n++;
if(f(center) == 0) {
return center;
}
if(f(l) * f(center) > 0) {
l = center;
} else {
r = center;
}
if (r - l < e) {
return l;
} else {
return half(l, r);
}
}
public static void start(double left, double right, double epsilon){
e = epsilon;
System.out.println("Half:\t"+ half(left, right) +"\nin " + Integer.toString(n) + " steps");
n = 0;
System.out.println("Gold:\t"+ newton((left + right) / 2) +"\nin " + Integer.toString(n) + " steps");
}
}