INPUT:
# Program on Thomas Algorithm for Tridiagonal Matrix using Python
# Assignment No. 2
import numpy as np #Install/ import numpy package (Library) as it is used for
array processing
#sys module provides functions and variables which are used to manipulate different
parts of the Python Runtime Environment.
#It lets us access system-specific parameters and functions.
import sys #First, we have to import the sys module in our program
before running any functions.
n = int(input('Enter number of unknowns: '))
#To create an empty matrix
a = np.zeros((n,n+1)) #Create empty Agumented matrix (A:B) of the form AX=B
print("Enter the values of the given indexes as per the format \"a[row][column]\"")
#Create an augumented matrix
for i in range(n): #Starting value is 0 and last value is n
for j in range(n+1): #Starting value is 0 and last value is n+1
a[i][j] = float(input( 'a['+str(i)+']['+ str(j)+']=')) #Enter the values
of augumented matrix
#To convert augumented matrix to upper triangular matrix
for i in range(n):
if a[i][i] == 0.0: #This line will check all diagonal elements
sys.exit('Divide by zero detected!. Program will exit.')
#If diagonal elements becomes zero, then Above function is used to exit from the
program.
for j in range(i+1, n): #To calculate multiplication factor to each
pivoting point
ratio = a[j][i]/a[i][i]
for k in range(n+1): #To make each element below main diagonal as zero
a[j][k] = a[j][k] - ratio * a[i][k]
for q in range(n+1): #To make a13 zero
a[0][q]= a[0][q] - (a[1][q]/4.5)
#Using Back substituion to prepare equations
z=a[2][3]/a[2][2] #Equation for last row
y=(a[1][3]-(a[1][2]*z))/a[1][1] #Equation for second row
x=(a[0][3]-(a[0][1]*y)-(a[0][2]*z))/a[0][0] #Equation for first row
print("The value of x is","{:.2f}".format(x)) #printing the outcome for x upto 2
decimal places
print("The value of y is","{:.2f}".format(y)) #printing the outcome for y upto 2
decimal places
print("The value of z is","{:.2f}".format(z)) #printing the outcome for z upto 2
decimal places
OUTPUT:
Enter number of unknowns: 3
Enter the values of the given indexes as per the format "a[row][column]"
a[0][0]=5
a[0][1]=-2
a[0][2]=3
a[0][3]=18
a[1][0]=1
a[1][1]=7
a[1][2]=-3
a[1][3]=-22
a[2][0]=2
a[2][1]=-1
a[2][2]=6
a[2][3]=22
The value of x is 1.00
The value of y is -2.00
The value of z is 3.00