methods - lab3

 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
public class Methods {
public static Double F(Double x) {
return Math.cos(x);
}
public static void methodBiSections(Double a, Double b, Double e) {
Double x1 = a;
Double x2 = b;
Double xmid = (x2 + x1) / 2;
for (int i = 2; ; i++) {
if ((x2 - x1) <= 2 * e) {
break;
}
if (F(xmid - (x2 - x1) / (Math.pow(2, i))) <= F(xmid + (x2 - x1) / (Math.pow(2, i)))) {
x2 = xmid;
xmid = (x2 + x1) / 2;
} else {
x1 = xmid;
xmid = (x2 + x1) / 2;
}
}
Double result = (x2 + x1) / 2;
System.out.println("Method Bi-Sections");
System.out.println(result);
System.out.println(F(result));
}
public static void methodGoldenSection(Double a, Double b, Double e) {
Double A = a;
Double D = b;
Double B = A + (3 - Math.sqrt(5)) * (D - A) / 2;
Double C = A + (Math.sqrt(5) - 1) * (D - A) / 2;
for (;;) {
if ((D - A) <= 2 * e) {
break;
}
if (F(B) <= F(C)) {
D = C;
} else {
A = B;
}
B = A + (3 - Math.sqrt(5)) * (D - A) / 2;
C = A + (Math.sqrt(5) - 1) * (D - A) / 2;
}
Double result = A + (D - A) / 2;
System.out.println("Method Golden Section");
System.out.println(result);
System.out.println(F(result));
}
public static void main(String[] args){
methodBiSections(2.0, 4.0, 0.01);
methodGoldenSection(2.0, 4.0, 0.01);
}
}