NC-Assignment No 1
NC-Assignment No 1
Numerical Computing
T0
Mr.Umer Hayat
BY
Hannan Khalid
(20014119-026)
Submission Date:24-June-2024
BS Computer Science (A)
UNIVERSITY OF GUJRAT
1) Write a function to perform Gaussian Elimination on a given system of
linear equations. Your function should return the solution vector.
2) Test your function with the following system of equations:
2x+3y−z=5
4x+y+2z=6
−x+y+z=0
SOLUTION:
❖ PYTHON-CODE :
import numpy as np
from sympy import Matrix
def gaussian_elimination(A, b):
n = len(A)
for i in range(n):
j=i+1
while j < n and abs(A[j][i]) < 1e-9:
j += 1
if j == n:
return None
for k in range(n):
A[i][k], A[j][k] = A[j][k], A[i][k]
x = [0] * n
for i in range(n - 1, -1, -1):
# Check for division by zero (may indicate inconsistent system)
if abs(A[i][i]) < 1e-9:
return None # Inconsistent system
sum = 0
for j in range(i + 1, n):
sum += A[i][j] * x[j]
x[i] = (b[i] - sum) / A[i][i]
return x
Test case:
solution = gaussian_elimination(A, b)
if solution is None:
print("Singular or inconsistent system of equations")
else:
print("Solution vector:", solution)
1. Forward Elimination:
2. Back Substitution:
• Start from the last row (n - 1) of the upper triangular matrix (obtained after
forward elimination).
• Iterate backwards (-1 step size) through the rows.
• For each row (i), check the diagonal element (A[i][i]). If it's close to zero, the
system might be inconsistent (no solution).
• The function returns None in this case.
• Calculate the value of x[i] using the formula: x[i] = (b[i] - sum(A[i][j] * x[j] for
j in range(i + 1, n))) / A[i][i]
• This involves iterating through the elements in the current row (i) to the right
(excluding the diagonal), multiplying them by the corresponding solved
variables (x[j]), and subtracting the sum from b[i].
• Finally, divide by the diagonal element (`A[i]).