Secant method in Python

783 Views Asked by At

I have a function $f(x) = sin(2.5x)*e^x+0.5$. And I need to find the root in the interval [0,2]. But the problem is when I use the secant method I got the root, not in the interval [0,2].
I got $x= -0.29388400925330754$. I write code in python.

def func(x):
    f_x = math.sin(2.5 * x) * math.exp(x) + 0.5
    return f_x
def secant(f, x0, x1, eps):
    f_x0 = f(x0)
    f_x1 = f(x1)
    iteration_counter = 0
    while abs(f_x1) > eps and iteration_counter < 100:
        try:
            denominator = float(f_x1 - f_x0)/(x1 - x0)
            x = x1 - float(f_x1)/denominator
        except ZeroDivisionError:
            print ("Error! - denominator zero for x = ", x)
            sys.exit(1)     # Abort with error
        x0 = x1
        x1 = x
        f_x0 = f_x1
        f_x1 = f(x1)
        iteration_counter += 1
        

    # Here, either a solution is found, or too many iterations
    if abs(f_x1) > eps:
        iteration_counter = -1
    
    return x, iteration_counter

    
secant(func, 0, 2, 0.001)
1

There are 1 best solutions below

0
On BEST ANSWER

You are not using a bracketing method, so it is not unreasonable to find that the root you find is outside the initial interval as there is no guarantee that the iteration stays inside the interval.

Bracketing or interval-shrinking methods using the secant root are the false position - regula falsi method and Dekker's method. Note that pure regula falsi will often slow down remarkably in its convergence, one needs a weighted modification like the Illinois method for super-linear convergence.