Python program to find roots of an equation using secant method

Hello everyone, in this tutorial, we are going to learn how to implement the secant method in Python to find the roots of a given equation of the form f(x) = 0.

Here’s the algorithm to implement the secant method.

First, we initialize two variables x1 and x2 that are the estimated values for the root. We also initialize a variable e to define the desired accuracy and a variable for iteration(Let’s say i) in a loop. Then, for every iteration, we calculate f(x1) and f(x2) and intermediate values as shown in the code. If the difference between two intermediate values is less than the desired accuracy, we break the loop and print the result as shown.

The above has been implemented in Python below. Have a look at the given program.

def f(x):
    return pow(x, 4) + 2*x - 1

def roots_secant(x1, x2, e):
    i=0
    xm1 = 0
    xm2 = 0
    check = 0
    if(f(x1) * f(x2) < 0):
        while(1):
            xm1 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1))
            check = f(x1) * f(xm1)
            if(check == 0):
                break
            
            x1 = x2
            x2 = xm1
            
            i = i + 1
            
            xm2 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1))
            if(abs(xm2 - xm1) < e):
                break
            
        return xm1
    else:
        return -1
    
    
print(roots_secant(0, 1, 0.00001))

Output:

0.4745430868109658

Explanation: In the above example, we have defined f(x) as x^4 + 2x – 1. The secant method takes three parameters x1, x2, and e. x1 and x2 are initial approximation values. These values are updated in every iteration of the loop until the difference between calculated intermediate values is less than e. The function returns the root between the given interval (initial values of x1 and x2) if a root is found with the desired accuracy. If not, then the function returns -1.

Thank you.

Also read: Find the root of an equation using Newton Raphson method in C++

Leave a Reply

Your email address will not be published.