You are on page 1of 6

HAMZA AHMED WAJEEH (12349) NC LAB (111678) ASSIGNMENT 2

Question:
Write a program to find the values of variables in the equations. Take input from the user for the
equations and also the method. User will choose one method from these four methods, Gauss
Elimination, Gauss Jordon, Jacobi & Gauss Seidel. In output print the equations, augmented Matrix,
values of variable & in Gauss elimination or in Gauss Jordon final matrix after solution.

Submit code, output screen shots, and maximum one page description about your code.

Code:
import numpy as np
def gauss_elimination(A, b):
n = len(A)
for i in range(n):
if A[i][i] == 0.0:
raise ValueError("Divide by zero detected!")
for j in range(i+1, n):
ratio = A[j][i] / A[i][i]
for k in range(n):
A[j][k] = A[j][k] - ratio * A[i][k]
b[j] = b[j] - ratio * b[i]
x = np.zeros(n)
x[n-1] = b[n-1] / A[n-1][n-1]
for i in range(n-2,-1,-1):
x[i] = b[i]
for j in range(i+1,n):
x[i] = x[i] - A[i][j]*x[j]
x[i] = x[i] / A[i][i]
return x
def gauss_jordan(A, b):
n = len(A)
Ab = np.column_stack((A, b))
for i in range(n):
if Ab[i][i] == 0.0:
raise ValueError("Divide by zero detected!")
Ab[i] = Ab[i] / Ab[i][i]
for j in range(n):
if j != i:
ratio = Ab[j][i]
Ab[j] = Ab[j] - ratio * Ab[i]
x = Ab[:, -1]
return x
def jacobi(A, b, x0, max_iterations, tolerance):
n = len(A)
x = np.copy(x0)
for iteration in range(max_iterations):
x_new = np.zeros(n)
for i in range(n):
HAMZA AHMED WAJEEH (12349) NC LAB (111678) ASSIGNMENT 2
sum_val = b[i]
for j in range(n):
if i != j:
sum_val -= A[i][j] * x[j]
x_new[i] = sum_val / A[i][i]
if np.linalg.norm(x - x_new) < tolerance:
return x_new
x = np.copy(x_new)
raise ValueError("Jacobi method did not converge within the specified maximum
iterations.")
def gauss_seidel(A, b, x0, max_iterations, tolerance):
n = len(A)
x = np.copy(x0)
for iteration in range(max_iterations):
for i in range(n):
sum_val = b[i]
for j in range(n):
if i != j:
sum_val -= A[i][j] * x[j]
x[i] = sum_val / A[i][i]
if np.linalg.norm(A @ x - b) < tolerance:
return x
raise ValueError("Gauss-Seidel method did not converge within the specified
maximum iterations.")
equations = int(input("Enter the number of equations: "))
variables = int(input("Enter the number of variables: "))
A = np.zeros((equations, variables))
b = np.zeros(equations)
print("Enter the coefficients of the equations:")
for i in range(equations):
for j in range(variables):
A[i][j] = float(input(f"A[{i+1}][{j+1}]: "))
print("Enter the constants (b vector):")
for i in range(equations):
b[i] = float(input(f"b[{i+1}]: "))
method = input("Choose a method (1. Gauss Elimination, 2. Gauss Jordan, 3. Jacobi,
4. Gauss Seidel): ")
if method == "1":
x = gauss_elimination(A, b)
print("Gauss Elimination:")
print("Augmented Matrix:")
print(np.column_stack((A, b)))
print("Values of Variables:")
for i in range(len(x)):
print(f"x{i+1} = {x[i]}")
elif method == "2":
x = gauss_jordan(A, b)
print("Gauss Jordan:")
print("Final Matrix after Solution:")
print(np.column_stack((A, b)))
print("Values of Variables:")
HAMZA AHMED WAJEEH (12349) NC LAB (111678) ASSIGNMENT 2
for i in range(len(x)):
print(f"x{i+1} = {x[i]}")
elif method == "3":
max_iterations = int(input("Enter the maximum number of iterations: "))
tolerance = float(input("Enter the tolerance: "))
x0 = np.zeros(variables)
x = jacobi(A, b, x0, max_iterations, tolerance)
print("Jacobi:")
print("Values of Variables:")
for i in range(len(x)):
print(f"x{i+1} = {x[i]}")
elif method == "4":
max_iterations = int(input("Enter the maximum number of iterations: "))
tolerance = float(input("Enter the tolerance: "))
x0 = np.zeros(variables)
x = gauss_seidel(A, b, x0, max_iterations, tolerance)
print("Gauss-Seidel:")
print("Values of Variables:")
for i in range(len(x)):
print(f"x{i+1} = {x[i]}")
else:
print("Invalid method chosen. Please try again.")

Outputs:
HAMZA AHMED WAJEEH (12349) NC LAB (111678) ASSIGNMENT 2
HAMZA AHMED WAJEEH (12349) NC LAB (111678) ASSIGNMENT 2
HAMZA AHMED WAJEEH (12349) NC LAB (111678) ASSIGNMENT 2

Project Description:

The code above implements numerical methods for solving linear equation systems. It has
four methods available for use: Gauss Elimination, Gauss-Jordan Elimination, Jacobi
Iteration, and Gauss-Seidel Iteration.

Gauss elimination: is used to transform the system into an upper triangular form by
performing Gaussian elimination on the coefficient matrix and the constant vector. The
system is then solved using back-substitution to determine the values of the variables.

Gauss Jordan: This method is used to convert the augmented matrix into a reduced row-
echelon form. By performing row operations to eliminate variables and solve the system, this
method directly provides solutions.

Jacobi: Iteratively updates the values of variables based on an initial guess until a specified
tolerance or the maximum number of iterations is reached. To ensure convergence, this
method uses a diagonal dominant version of the coefficient matrix.

Seidel: is similar to the Jacobi iteration, but it updates the variables in a different order. It
incorporates the most recent values as soon as they are available, rather than the values
from the previous iteration. For some systems, this method converges faster than Jacobi
iteration.

The user is asked for the number of equations, variables, coefficients, and constant vectors.
They can then select the preferred method for resolving the system. The code computes the
variables' values and displays them as output.

You might also like