How to do the Bisection method in Python

前端 未结 7 2437
小蘑菇
小蘑菇 2021-02-15 15:05

I want to make a Python program that will run a bisection method to determine the root of:

f(x) = -26 + 85x - 91x2 +44x3 -8x4 + x5

The Bisecti

7条回答
  •  旧巷少年郎
    2021-02-15 15:35

    I'm trying to make some modifications :

    1. While loop : the tolerance and the number of iterations performed by the algorithm
    2. save in addition to the root approach, the vector of points generated by the algorithm xn (all c points), the vector of all images f(c)
    3. Assuming Xs is a given approximation of the root, save the absolute error np.linalg.norm(Xs-xn)
    4. Save the approximate error : np.linalg.norm(xn+1 - xn).

    This is my code:

    import numpy as np
    def bisection3(f,x0,x1,tol,max_iter):
        c = (x0+x1)/2.0
        x0 = c
        Xs = 0.3604217029603
        err_Abs = np.linalg.norm(x0-Xs)
        itr = 0
        f_x0 = f(x0)
        f_x1 = f(x1)
        xp = [] # sucesion que converge a la raiz
        errores_Abs = []
        errores_Aprox = []
        fs = [] # esta sucecion debe converger a cero 
        while(((x1-x0)/2.0 > tol) and (itr< max_iter)):
            if f(c) == 0:
                return c
            elif f(x0)*f(c) < 0:
                x1 = c
            else :
                x0 = c
            c = (x0+x1)/2.0    
            itr +=1
            err_Abs = np.linalg.norm(x0-Xs)
            err_Aprox = np.linalg.norm(x1 - x0)
            fs.append(f(c))
            xp.append(c)
            errores_Abs.append(err_Abs)
            errores_Aprox.append(err_Aprox)
        return x0,errores_Abs, errores_Aprox,fs,xp
    

    And i have an example of execution :

    f  = lambda x : 3*x + np.sin(x) - np.exp(x)
    X0_r1 ,  err_Abs_r1,err_Aprox_r1, fs_r1 , xp_r1 =   bisection3(f,0,0.5,1e-5,100)
    

提交回复
热议问题