-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLinearSystemSolver.py
72 lines (58 loc) · 2.37 KB
/
LinearSystemSolver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def gaussian_elimination(matrix):
n = len(matrix)
# Forward elimination to convert the matrix into upper triangular form
for k in range(n):
for i in range(k + 1, n):
factor = matrix[i][k] / matrix[k][k]
for j in range(k, n + 1):
matrix[i][j] -= factor * matrix[k][j]
# Backward substitution to find the solution with row swapping
solution = [0] * n
for i in range(n - 1, -1, -1):
# Check if the coefficient is zero and swap rows if needed
if matrix[i][i] == 0:
for m in range(i - 1, -1, -1):
if matrix[m][i] != 0:
# Swap rows i and m
matrix[i], matrix[m] = matrix[m], matrix[i]
break
# Continue with the backward substitution
solution[i] = matrix[i][n]
for j in range(i + 1, n):
solution[i] -= matrix[i][j] * solution[j]
solution[i] /= matrix[i][i]
return solution
def main():
print("Linear System Solver - Task Assignment")
print("Second Level - First Semester: 2023-2024\n")
print("Name: Amr Bedir Taher")
print("ID: 1000264365")
print("Group: 2, Section: 12")
print("\n____________________\n")
n = int(input("Enter the number of equations: "))
# Create a matrix to store the coefficients and constants of the linear system
matrix = [[0] * (n + 1) for _ in range(n)]
# Input coefficients and constants for each equation
for i in range(n):
print(f"Enter coefficients for equation {i + 1}:")
for j in range(n):
matrix[i][j] = float(input(f"a{i + 1}{j + 1}: "))
matrix[i][n] = float(input(f"Enter the constant (b{i + 1}): "))
# Perform Gaussian elimination to convert the matrix into upper triangular form
matrix = gaussian_elimination(matrix)
# Display the solution with steps
print("\n____________________\n")
print("Solution with Steps:")
for i in range(n):
print(f"x{i + 1} = ({matrix[i][n] / matrix[i][i]:0.2f})", end="")
for j in range(n):
if j != i:
print(f" - ({matrix[i][j]:0.2f} * x{j + 1})", end="")
print()
# Display the final solution
print("\n____________________\n")
print("Final Solution:")
for i in range(n):
print(f"x{i + 1} = {matrix[i][n]:0.2f}")
if __name__ == "__main__":
main()