2019年4月5日 星期五

[JAVA程式語言]例題 2-1 解 f(x)=x^3 -4x +2 =0 非線性方程式的解

[JAVA程式語言]例題 2-1 解 f(x)=x^3 -4x +2 =0 非線性方程式的解

/* ex2-1.java Bisection Method is used for solving the
 * nonlinear equation f(x)=0, its root is between a and b
 */

public class Main {

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

public static void main(String args[]){
    Main fun = new Main();
    final int MAX = 50;  /* maximum iterations */
    final double TOL = 0.001;/* maximum iterations */
        double x,a,b,p,h;
        int i=1;
        a=1.6;
        b=1.7;
        System.out.printf(" i    a(i)        b(i)       p(i)       f(p(i))      h(i)\n");
        while(i<=MAX)  {
            p=(a+b)/2.0;
            h=Math.abs((b-a)/2.0);
            System.out.printf("%2d   %9.6f   %9.6f  %9.6f   %9.6f   %9.6f\n", i,a,b,p,fun.fx(p),h);
            if(Math.abs(fun.fx(p))==0 || h<TOL) {
                System.out.printf("%2d iterations!!!\n",i);
            System.out.printf(" The Root=%9.6lf  f(%9.6f)=%9.6f\n",p,p,fun.fx(p));
            break;
            }
            else
            {
            if(fun.fx(a)*fun.fx(p) >0){
                a=p;
            }
            else if(fun.fx(b)*fun.fx(p) >0) {
                b=p;
            }
        i++;
            }
        }
        System.out.printf("Bisection Method failed after %d iterations!!!\n",i);
}
}

  a=0.5 b=0.6 輸出畫面
  i      a(i)                  b(i)         p(i)              f(p(i))        h(i)
 1    0.500000    0.600000   0.550000   -0.033625    0.050000
 2    0.500000    0.550000   0.525000    0.044703    0.025000
 3    0.525000    0.550000   0.537500    0.005287    0.012500
 4    0.537500    0.550000   0.543750   -0.014233    0.006250
 5    0.537500    0.543750   0.540625   -0.004489    0.003125
 6    0.537500    0.540625   0.539063    0.000395    0.001563
 7    0.539063    0.540625   0.539844   -0.002048    0.000781
 7 iterations!!!

 a=1.6 b=1.7 輸出畫面
  i      a(i)                b(i)             p (i)          f(p(i))          h(i)
 1    1.600000    1.700000   1.650000   -0.107875    0.050000
 2    1.650000    1.700000   1.675000   -0.000578    0.025000
 3    1.675000    1.700000   1.687500    0.055420    0.012500
 4    1.675000    1.687500   1.681250    0.027224    0.006250
 5    1.675000    1.681250   1.678125    0.013274    0.003125
 6    1.675000    1.678125   1.676562    0.006336    0.001563
 7    1.675000    1.676562   1.675781    0.002876    0.000781
 7 iterations!!!

沒有留言:

張貼留言

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

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