最優化第二講——一維搜索法(黃金分割法和java實現)

新區間的長度L(n),舊區間的長度L(n-1)。L(n)/L(n-1)  = 0.618

所以查找速度:0.618^n。

公式爲:

 

這個比較容易理解,看代碼就可以看清楚了,主要是區間的更新問題,每次更新長度都變化爲原來的0.618

代碼如下

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. private static void goldSearch(float start, float end, float eps) {  
  2.           
  3.         float a,b;  
  4.         b = Math.max(start, end);  
  5.         a = Math.min(start, end);  
  6.           
  7.         float t1, t2, f1, f2;  
  8.         float ranta = 0.618034f;  
  9.           
  10.         t1 = b - ranta * (b - a);  
  11.         t2 = a + ranta * (b - a);  
  12.         f1 = fun(t1);  
  13.         f2 = fun(t2);  
  14.           
  15.         while(t2 - t1 > eps) {  
  16.               
  17.             if(f1 <= f2) b = t2;  
  18.             else a = t1;   
  19.             t1 = b - ranta * (b - a);  
  20.             t2 = a + ranta * (b - a);  
  21.             f1 = (float) Math.sin(t1);  
  22.             f2 = (float) Math.sin(t2);  
  23.         }  
  24.           
  25.         float x, y;  
  26.         if(f1 > f2) {  
  27.             x = t2;  
  28.             y = f2;  
  29.         } else {  
  30.             x = t1;  
  31.             y = f1;  
  32.         }  
  33.         System.out.println(x + "\t" + y);  
  34.     }  
  35.       
  36.     private static float fun(float x) {  
  37.         return (float) Math.sin(x);  
  38.     }  


代碼中示例了對sin函數,在[0, 2*pi]區間內求極小值的方式。很容易理解
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章