簡體   English   中英

而循環只運行一次?

[英]While Loop Only Running Once?

盡管Math.abs(v1-v2)絕對大於1E-7但為什么我的計算導數的數值方法卻沒有循環的Math.abs(v1-v2)

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;
    }
}

不過可能只是我有腦子放屁。 關於如何解決它的任何想法?

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

在v1 = v2中的while循環中的最后一件事,因此在while循環的下一次迭代中,Math.abs(v1-v2)=== 0

因為v1 = v2,所以v1-v2 == 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);
}

問題是您在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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM