2014-02-25 77 views
-1

我的函數以f它是以下形式的另一種功能:優化Switch語句/ While循環

// function f 
mgf:function(p,n){ 
    return function(t){ 
     return Math.pow(1-p+p*Math.exp(t),n); 
    }; 
} 

與數字pn。然後,它生成由該f功能不同的功能和變量值h和基於o(順序,123,或4x並運行一個while循環直到v1v2基本上相等,則最終返回該值:

derivative:function(f,o,x){ 
    var h=0.01,v1,v2; 
    switch(o){ 
     case 1: 
      while((typeof v1==='undefined' && typeof v2==='undefined') || Math.abs(v1-v2)>1E-5) { 
       v1=(-f(x+2*h)+8*f(x+h)-8*f(x-h)+f(x-2*h))/(12*h); 
       h-=h/2; 
       v2=(-f(x+2*h)+8*f(x+h)-8*f(x-h)+f(x-2*h))/(12*h); 
      } 
      return v2; 
     case 2: 
      while((typeof v1==='undefined' && typeof v2==='undefined') || Math.abs(v1-v2)>1E-5) { 
       v1=(-f(x+2*h)+16*f(x+h)-30*f(x)+16*f(x-h)-f(x-2*h))/(12*Math.pow(h,2)); 
       h-=h/2; 
       v2=(-f(x+2*h)+16*f(x+h)-30*f(x)+16*f(x-h)-f(x-2*h))/(12*Math.pow(h,2)); 
      } 
      return v2; 
     case 3: 
      while((typeof v1==='undefined' && typeof v2==='undefined') || Math.abs(v1-v2)>1E-5) { 
       v1=(f(x+2*h)-2*f(x+h)+2*f(x-h)-f(x-2*h))/(2*Math.pow(h,3)); 
       h-=h/2; 
       v2=(f(x+2*h)-2*f(x+h)+2*f(x-h)-f(x-2*h))/(2*Math.pow(h,3)); 
      } 
      return v2; 
     case 4: 
      while((typeof v1==='undefined' && typeof v2==='undefined') || Math.abs(v1-v2)>1E-5) { 
       v1=(f(x+2*h)-4*f(x+h)+6*f(x)-4*f(x-h)+f(x-2*h))/Math.pow(h,4); 
       h-=h/2; 
       v2=(f(x+2*h)-4*f(x+h)+6*f(x)-4*f(x-h)+f(x-2*h))/Math.pow(h,4); 
      } 
      return v2; 
    } 
} 

正如你可以看到這個代碼很笨重,重複性。每種情況下執行完全相同的功能,但具有原始f功能的不同功能。我怎樣才能優化這段代碼,並將其重寫爲更具可讀性?我可以提取一般算法:

while(x) { 
    v1=y; 
    h-=h/2; 
    v2=y; 
} 
return v2; 

並以某種方式有一個參數,它的功能是f? IE瀏覽器。 (-f(x+2*h)+8*f(x+h)-8*f(x-h)+f(x-2*h))/(12*h)

+4

您可能要發佈此上http://codereview.stackexchange.com/。他們可能會給你更好的建議。 –

+0

難道你不能只是採取什麼不同,並將這些值設置爲變量,並在開關後使用它們的公共方程? – epascarello

+0

@epascarello,作爲答案,我會接受。有時候有一個全新的眼睛是很好的。 – tenub

回答

0

按epascarello的評論,解決方法很簡單:

derivative:function(f,o,x){ 
    var h=0.01,v1,v2,f1; 
    switch(o){ 
     case 1: 
      f1=function(x,h){ return (-f(x+2*h)+8*f(x+h)-8*f(x-h)+f(x-2*h))/(12*h); }; 
      break; 
     case 2: 
      f1=function(x,h){ return (-f(x+2*h)+16*f(x+h)-30*f(x)+16*f(x-h)-f(x-2*h))/(12*Math.pow(h,2)); }; 
      break; 
     case 3: 
      f1=function(x,h){ return (f(x+2*h)-2*f(x+h)+2*f(x-h)-f(x-2*h))/(2*Math.pow(h,3)); }; 
      break; 
     case 4: 
      f1=function(x,h){ return (f(x+2*h)-4*f(x+h)+6*f(x)-4*f(x-h)+f(x-2*h))/Math.pow(h,4); }; 
      break; 
    } 
    while((typeof v1==='undefined' && typeof v2==='undefined') || Math.abs(v1-v2)>1E-5) { 
     v1=f1(x,h); 
     h-=h/2; 
     v2=f1(x,h); 
    } 
    return v2; 
}