2019年4月7日 星期日

[JAVA程式語言]例題3-2 依據下表求f'(x)一階微分值=?

 [JAVA程式語言]例題3-2  依據下表求f'(x)一階微分值

 x           f(x)             f'(x)
======================
-0.3     -0.20431      ????
-0.1     -0.08993      ????
 0.1       0.11007      ????
 0.3       0.39569      ????
======================


/* ex3-2.java is used for solving nonlinear equation
 * based on Fixed-Point Algorithm g(x)=x with initial
 * approximation P0.
 例題3-2 一下表求f'(x)一階微分值

x           f(x)       f'(x)
================================
-0.3     -0.20431      ????
-0.1     -0.08993      ????
0.1       0.11007      ????
0.3       0.39569      ????

x=[-0.3 , -0.1 , 0.1 , 0.3]
f=[-0.20431 ,  -0.08993 , 0.11007 , 0.39569]

(A) 向前差近似 (三點)
fi' =  [ -f(i+2) + 4f(i+1) -3 f(i) ] / 2h ,
O(h) = 1/3 * h*h *  < fi 三次微分 >

(B) 向後差近似(三點)
fi' =  [ 3f(i) - 4f(i-1) + f(i-2) ] / 2h ,
O(h) = 1/3 * h*h * < fi 三次微分 >

(C) 中央近似 (雙點)
fi' = [f(i+1) - f(i-1)] / 2h  ,
O(h) = -1/6 * h *h *  < fi 三次微分 >
中央近似沒有三點

*/

public class Main {

    double FordDiff(int i ){ // 前差微分
        // 前差微分 fi' =  [ -f(i+2) + 4f(i+1) -3 f(i) ] / 2h ,
        double h1,h2,h3,s;
        double x[]={-0.3 , -0.1 , 0.1 , 0.3};
        double f[]={-0.20431 ,  -0.08993 , 0.11007 , 0.39569};
        h1=x[i+1];
        h2=x[i];
        h3=Math.abs(h1-h2);
        s= -f[i+2] + 4*f[i+1] -3*f[i];
        return ( s / (2* h3));
    }

    double BackDiff(int i ){ // 前差微分
        // // 後差微分 fi' =  [ 3f(i) - 4f(i-1) + f(i-2) ] / 2h ,
        double h1,h2,h3,s;
        double x[]={-0.3 , -0.1 , 0.1 , 0.3};
        double f[]={-0.20431 ,  -0.08993 , 0.11007 , 0.39569};
        h1=x[i];
        h2=x[i-1];
        h3=Math.abs(h1-h2);
        s= 3*f[i]-4*f[i-1] +f[i-2];
        return ( s / (2* h3));
    }

    public static void main(String args[]){
        Main fun = new Main();
        double x[]={-0.3 , -0.1 , 0.1 , 0.3};
        double f[]={-0.20431 ,  -0.08993 , 0.11007 , 0.39569};
        int i;
        //===========================
        //前差微分 fi' =  [ -f(i+2) + 4f(i+1) -3 f(i) ] / 2h ,
        for (i=0;i<=1;i++){
            System.out.printf("x= %2.2f , f(x)= %2.6f , FordDiff : %10.6f\n",x[i],f[i],fun.FordDiff(i));
        }
        System.out.printf("\n\n");
        for (i=3;i>1;i--){
            System.out.printf("x= %2.2f , f(x)= %2.6f , BackDiff : %10.6f\n",x[i] ,f[i],fun.BackDiff(i));
        }
    }
}


輸出畫面

x= -0.30 , f(x)= -0.204310 , FordDiff :   0.357850
x= -0.10 , f(x)= -0.089930 , FordDiff :   0.785950


x= 0.30 , f(x)= 0.395690 , BackDiff :   1.642150
x= 0.10 , f(x)= 0.110070 , BackDiff :   1.214050

沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...