2014-02-25 75 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; 
}