2014-02-24 153 views
-1

類難倒了,爲什麼我的計算衍生數值方法並不是不顧Math.abs(v1-v2)循環肯定比1E-7更大:while循環只運行一次?

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

     ... 

     default: 
      return 0; 
    } 
} 

這可能只是我有一個大腦放屁雖然。任何想法如何解決它

+0

你傳遞什麼值? – Bergi

回答

0

的解決方案是移動的v1定義內循環:

var h=1,v1,v2; 

... 

while((typeof v1==='undefined' && typeof v2==='undefined') || Math.abs(v1-v2)>1E-7) { 
    //v2=(f(x+h)-f(x))/h; 
    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); 
} 
4

循環第一次運行時,它將設置v2,因此typeof v2==='undefined'不再爲真。它也設置v1=v2,所以Math.abs(v1-v2)===0,所以第二個條件也是錯誤的。因此,兩個條件都不成立,所以循環退出。

0

在while循環的最後一件事在V1 = V2等while循環的下一次迭代,Math.abs(V1-V2)=== 0

0

的問題是你的while循環中的最後一條語句。我想你想這樣做:

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

     ... 

     default: 
      return 0; 
    } 
}