新區間的長度L(n),舊區間的長度L(n-1)。L(n)/L(n-1) = 0.618
所以查找速度:0.618^n。
公式爲:
這個比較容易理解,看代碼就可以看清楚了,主要是區間的更新問題,每次更新長度都變化爲原來的0.618
代碼如下
- private static void goldSearch(float start, float end, float eps) {
- float a,b;
- b = Math.max(start, end);
- a = Math.min(start, end);
- float t1, t2, f1, f2;
- float ranta = 0.618034f;
- t1 = b - ranta * (b - a);
- t2 = a + ranta * (b - a);
- f1 = fun(t1);
- f2 = fun(t2);
- while(t2 - t1 > eps) {
- if(f1 <= f2) b = t2;
- else a = t1;
- t1 = b - ranta * (b - a);
- t2 = a + ranta * (b - a);
- f1 = (float) Math.sin(t1);
- f2 = (float) Math.sin(t2);
- }
- float x, y;
- if(f1 > f2) {
- x = t2;
- y = f2;
- } else {
- x = t1;
- y = f1;
- }
- System.out.println(x + "\t" + y);
- }
- private static float fun(float x) {
- return (float) Math.sin(x);
- }
代碼中示例了對sin函數,在[0, 2*pi]區間內求極小值的方式。很容易理解