Python Program for Jacobi Iteration Method with Output


Table of Contents

This program implements Jacobi Iteration Method for solving systems of linear equation in python programming language.

In Jacobi method, we first arrange given system of linear equations in diagonally dominant form. For example, if system of linear equations are:

3x + 20y - z = -18
2x - 3y + 20z = 25
20x + y - 2z = 17

Then they will be arranged like this:

20x + y - 2z = 17
3x + 20y -z = -18
2x - 3y + 20z = 25

After arranging equations in diagonally dominant form, we form equations for x, y, & z like this:

x = (17-y+2z)/20
y = (-18-3x+z)/20
z = (25-2x+3y)/20

These equations are defined later in Jacobi python program using lambda expression.

Python Source Code: Jacobi Method


# Defining equations to be solved
# in diagonally dominant form
f1 = lambda x,y,z: (17-y+2*z)/20
f2 = lambda x,y,z: (-18-3*x+z)/20
f3 = lambda x,y,z: (25-2*x+3*y)/20

# Initial setup
x0 = 0
y0 = 0
z0 = 0
count = 1

# Reading tolerable error
e = float(input('Enter tolerable error: '))

# Implementation of Jacobi Iteration
print('\nCount\tx\ty\tz\n')

condition = True

while condition:
    x1 = f1(x0,y0,z0)
    y1 = f2(x0,y0,z0)
    z1 = f3(x0,y0,z0)
    print('%d\t%0.4f\t%0.4f\t%0.4f\n' %(count, x1,y1,z1))
    e1 = abs(x0-x1);
    e2 = abs(y0-y1);
    e3 = abs(z0-z1);
    
    count += 1
    x0 = x1
    y0 = y1
    z0 = z1
    
    condition = e1>e and e2>e and e3>e

print('\nSolution: x=%0.3f, y=%0.3f and z = %0.3f\n'% (x1,y1,z1))

Python Program Output: Jacobi Method

Enter tolerable error: 0.00001

Count	x	y	z

1	0.8500	-0.9000	1.2500

2	1.0200	-0.9650	1.0300

3	1.0012	-1.0015	1.0032

4	1.0004	-1.0000	0.9996

5	1.0000	-1.0001	1.0000

6	1.0000	-1.0000	1.0000

7	1.0000	-1.0000	1.0000


Solution: x=1.000, y=-1.000 and z = 1.000