NM3(0, 3PI/2, 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
package labs;
public class Lab3 {
private static double e;
private static int n = 0;
private static double function(double x) {
return -Math.sin(x);
}
private static double gold(double l, double r){
double lc = r - (r-l)/1.618034,
rc = l + (r-l)/1.618034;
n++;
double b1 = function(lc);
double b2 = function(rc);
double buf = function(lc) - function(rc);
if (buf == 0){
l = lc;
r = rc;
} else if (buf > 0) {
l = lc;
} else {
r = rc;
}
if (r - l < e) {
return (r + l) /2;
} else {
return gold(l, r);
}
}
private static double half(double l, double r){
double center = (l + r)/2.0;
n++;
double buf = function(center-(e/2.0)) - function(center+(e/2.0));
if (buf == 0 || r - l < 2*e){
return center;
} else if (buf > 0) {
return half(center, r);
} else {
return half(l, center);
}
}
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"+ gold(left, right) +"\nin " + Integer.toString(n) + " steps");
}
}