-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHillClimbing.java
43 lines (40 loc) · 1011 Bytes
/
HillClimbing.java
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
package Optimisation;
import java.util.function.BiFunction;
public class HillClimbing {
public static double findMinimum(BiFunction<Double, Double, Double> f) {
double curX = 0;
double curY = 0;
double curF = f.apply(curX, curY);
for (double step = 1e6; step > 1e-7; ) {
double bestF = curF;
double bestX = curX;
double bestY = curY;
boolean find = false;
for (int i = 0; i < 6; i++) {
double a = 2 * Math.PI * i / 6;
double nextX = curX + step * Math.cos(a);
double nextY = curY + step * Math.sin(a);
double nextF = f.apply(nextX, nextY);
if (bestF > nextF) {
bestF = nextF;
bestX = nextX;
bestY = nextY;
find = true;
}
}
if (!find) {
step /= 2;
} else {
curX = bestX;
curY = bestY;
curF = bestF;
}
}
System.out.println(curX + " " + curY);
return curF;
}
// Usage example
public static void main(String[] args) {
System.out.println(findMinimum((x, y) -> (x - 2) * (x - 2) + (y - 3) * (y - 3)));
}
}