2019年4月5日 星期五

[JAVA程式語言]例題2-3 已知非線性方程式 x^3 + 4x^2 -10 =0 請使用Newton-Raphson方法找出其位於(1.0,2.0)之間的根=?

[JAVA程式語言]例題2-3 已知非線性方程式 x^3 + 4x^2 -10 =0 請使用Newton-Raphson方法找出其位於(1.0,2.0)之間的根=?

假設啟動值x0=1.5 

/* ex2-4.java is used for solving nonlinear equation f(x)=0
 * based on Newton-Raphson Method with initial approximation
 * p0.
例題2-3 已知非線性方程式 x^3 + 4x^2 -10 =0 請使用Newton-Raphson方法找出其位於(1.0,2.0)之間的根=?
*/

public class Main {

    double fx(double x1) {
    return (Math.pow(x1,3)+4*Math.pow(x1,2)-10);
}

double ffx(double x1) {
    return (3*Math.pow(x1,2)+ 8*x1);
}


public static void main(String args[]){
    Main func = new Main();
    final int MAX = 100;  /* maximum iterations */
    final double TOL = 0.001;/* maximum iterations */
        int i=1;
        double x0,x;
        x0=1.5;
        while(i<=MAX){
            x= x0- func.fx(x0)/func.ffx(x0) ;
            System.out.printf("%2d   %10.7f\n",i-1,x0);
            if(Math.abs(x-x0) <TOL){
                System.out.printf("Root=%10.7f x-x0=%10.7f\n",x,Math.abs(x-x0));
                break;
            }   
            i++;
            x0=x;
        }
        System.out.printf("Newton-Raphson Method failed after %2d iterations!!!\n",i);
}
}


 輸出畫面
 0    1.5000000
 1    1.3733333
 2    1.3652620
Root= 1.3652300 x-x0= 0.0000320
Newton-Raphson Method failed after  3 iterations!!!

沒有留言:

張貼留言

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

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