methods - lab5

 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
public class Marina_Lab5 {
public static double f(double x, double y) {
return Math.pow(x-1, 2) + Math.pow(y-2, 4) + Math.exp(1/(x*x + y*y));
}
public static double dfdx(double x, double y) {
return 2*(x-1) + (-2*x / Math.pow(x*x + y*y, 2)) * Math.exp(1/(x*x + y*y));
}
public static double dfdy(double x, double y) {
return 4*Math.pow(y-2, 3) + (-2*y / Math.pow(x*x + y*y, 2)) * Math.exp(1/(x*x + y*y));
}
public static double grad(double x, double y, double lambda) {
return f(x - lambda*dfdx(x, y), y - lambda*dfdy(x, y));
}
public static double methodBi(double a, double b, double e, double x, double y) {
double A = a;
double B = b;
double C = (A + B) / 2;
for (;;) {
if (B - A <= e) {
return C;
}
if (grad(x, y, C - e/2) < grad(x, y, C + e/2)) {
B = C;
} else {
A = C;
}
C = (A + B) / 2;
}
}
public static void descent(double x, double y, double e) {
double xi = x;
double yi = y;
double xi1, yi1, i;
double lambda;
System.out.println("i = 0\t" + "xi = " + xi + "\t\tyi = " + yi + "\t\tf(xi, yi) = " + f(xi, yi));
for (i = 0; ; i++) {
lambda = methodBi(-10, 10, e, xi, yi);
xi1 = xi - lambda * dfdx(xi, yi);
yi1 = yi - lambda * dfdy(xi, yi);
if (Math.sqrt(Math.pow(xi1 - xi, 2) + Math.pow(yi1 - yi, 2)) <= e) {
System.out.println("Result:");
System.out.println("i = " + i + "\txi = " + xi1 + "\tyi = " + yi1 + "\tf(xi, yi) = " + f(xi1, yi1));
return;
}
System.out.println("i = " + i + "\txi = " + xi1 + "\tyi = " + yi1 + "\tf(xi, yi) = " + f(xi1, yi1));
xi = xi1;
yi = yi1;
}
}
public static void main(String args[]) {
descent(1, 2, 0.001);
}
}