Secant Method Python Program with Output

Table of Contents

This program implements Secant Method for finding real root of nonlinear equation in python programming language.

In this python program, x0 & x1 are two initial guess values, e is tolerable error and f(x) is actual non-linear function whose root is being obtained using secant method. Variable x2 holds approximated root in each step.

Python Source Code: Secant Method


# Defining Function
def f(x):
    return x**3 - 5*x - 9

# Implementing Secant Method

def secant(x0,x1,e,N):
    print('\n\n*** SECANT METHOD IMPLEMENTATION ***')
    step = 1
    condition = True
    while condition:
        if f(x0) == f(x1):
            print('Divide by zero error!')
            break
        
        x2 = x0 - (x1-x0)*f(x0)/( f(x1) - f(x0) ) 
        print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, f(x2)))
        x0 = x1
        x1 = x2
        step = step + 1
        
        if step > N:
            print('Not Convergent!')
            break
        
        condition = abs(f(x2)) > e
    print('\n Required root is: %0.8f' % x2)


# Input Section
x0 = input('Enter First Guess: ')
x1 = input('Enter Second Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')

# Converting x0 and e to float
x0 = float(x0)
x1 = float(x1)
e = float(e)

# Converting N to integer
N = int(N)


#Note: You can combine above three section like this
# x0 = float(input('Enter First Guess: '))
# x1 = float(input('Enter Second Guess: '))
# e = float(input('Tolerable Error: '))
# N = int(input('Maximum Step: '))

# Starting Secant Method
secant(x0,x1,e,N)

Python Program Output: Secant Method

Enter First Guess: 2
Enter Second Guess: 3
Tolerable Error: 0.000001
Maximum Step: 10


*** SECANT METHOD IMPLEMENTATION ***
Iteration-1, x2 = 2.785714 and f(x2) = -1.310860
Iteration-2, x2 = 2.850875 and f(x2) = -0.083923
Iteration-3, x2 = 2.855332 and f(x2) = 0.002635
Iteration-4, x2 = 2.855196 and f(x2) = -0.000005
Iteration-5, x2 = 2.855197 and f(x2) = -0.000000

 Required root is: 2.85519654