2019年4月6日 星期六

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


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

The method[edit]




The first two iterations of the secant method. The red curve shows the function f, and the blue lines are the secants. For this particular case, the secant method will not converge to the visible root.

The secant method is defined by the recurrence relation
As can be seen from the recurrence relation, the secant method requires two initial values, x0 and x1, which should ideally be chosen to lie close to the root.

Derivation of the method[edit]

Starting with initial values x0 and x1, we construct a line through the points (x0f(x0)) and (x1f(x1)), as shown in the picture above. In slope–intercept form, the equation of this line is
The root of this linear function, that is the value of x such that y = 0 is
We then use this new value of x as x2 and repeat the process, using x1 and x2 instead of x0 and x1. We continue this process, solving for x3x4, etc., until we reach a sufficiently high level of precision (a sufficiently small difference between xn and xn−1):


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

例題2-7 例題2-7 已知方程式 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.00001;/* maximum iterations */
        int i=2;
        double x0,x1,x,q0,q1;
        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=i+1;
            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
5      1.829384    -0.000000
The Root=  1.829384 f(  1.829384)= -0.000000

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...