-1
我的函數以f
它是以下形式的另一種功能:優化Switch語句/ While循環
// function f
mgf:function(p,n){
return function(t){
return Math.pow(1-p+p*Math.exp(t),n);
};
}
與數字p
和n
。然後,它生成由該f
功能不同的功能和變量值h
和基於o
(順序,1
,2
,3
,或4
)x
並運行一個while循環直到v1
和v2
基本上相等,則最終返回該值:
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)
您可能要發佈此上http://codereview.stackexchange.com/。他們可能會給你更好的建議。 –
難道你不能只是採取什麼不同,並將這些值設置爲變量,並在開關後使用它們的公共方程? – epascarello
@epascarello,作爲答案,我會接受。有時候有一個全新的眼睛是很好的。 – tenub