2019年4月6日 星期六

[JAVA程式語言]例題2-6 已知方程式 e^x + x^-2 + 2 cosx -6 利用正割法 找出f(x)=0的根=? err=0.001

[JAVA程式語言]例題2-6 已知方程式 e^x + x^-2 + 2 cosx -6 利用正割法 找出f(x)=0的根=? err=0.001

/* ex2-6.java Secant Method is similar to Newton-Raphson
 *  Method used for find solutions to f(x)=0 given
 *  initial approximations x0 and x1.

例題2-6 已知方程式 e^x + x^-2 + 2 cosx -6 利用正割法 找出f(x)=0的根=?

*/

public class Main {

    double fx(double x1) {
    return (Math.exp(x1)+1/Math.pow(2,x1)+2*Math.cos(x1)-6);
}

public static void main(String args[]){
    Main fun = new Main();
    final int MAX = 50;  /* maximum iterations */
    final double TOL = 0.001;/* maximum iterations */
        int i=2;
        double x0,x1,x,q0,q1;
        // f(1.8) * f(2.0) < 0 有根位於1.8 ~ 2.0 之間
        x0=1.8;
        x1=2.0;
        q0=fun.fx(x0);
        q1=fun.fx(x1);
        System.out.printf("i       xi           f(x)\n");
        System.out.printf("%-2d   %10.6f   %10.6f\n",0,x0,q0);
        System.out.printf("%-2d   %10.6f   %10.6f\n",1,x1,q1);
        while(i<=MAX) {
            x=x1-q1*(x1-x0)/(q1-q0);
            System.out.printf("%-2d   %10.6f   %10.6f\n",i,x,fun.fx(x));
            if(Math.abs(x-x1) < TOL) {
                System.out.printf("The Root=%10.6f f(%10.6f)=%10.6f\n",x,x,fun.fx(x));
                break;
        }
            else
            {
            i++;
            x0=x1;
            q0=q1;
            x1=x;
            q1=fun.fx(x);
            }
        }
        if(i>MAX){
            System.out.printf("Secant Method faileds!!!\n");
        } 
}
}


輸出畫面
i       xi           f(x)
0      1.800000    -0.117582
1      2.000000     0.806762
2      1.825441    -0.016116
3      1.828860    -0.002147
4      1.829385     0.000007
The Root=  1.829385 f(  1.829385)=  0.000007

沒有留言:

張貼留言

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

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