二分查适用于单调区间, 三分查找则要求区间内为凸函数,即只有一个极值,三分查找用于查找极值。

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
public class Ternary {
final static double EPS = 1e-10;

public static void main(String[] args) {
System.out.println(ternarySearch(1,10, a -> Math.pow(a-3,2), EPS));
}

interface MathOperation {
double operation(double a);
}

public static double ternarySearch(double begin , double end,
MathOperation func, double eps){
double mid1, mid2;
while(begin + eps < end){
mid1 = (begin + end) / 2;
mid2 = (end + mid1) / 2;
double res1 = func.operation(mid1);
double res2 = func.operation(mid2);
if(res1 > res2){
begin = mid1;
} else {
end = mid2;
}
}
return begin;
}
}