-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolveLinearEquation
More file actions
59 lines (49 loc) · 1.43 KB
/
SolveLinearEquation
File metadata and controls
59 lines (49 loc) · 1.43 KB
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
import numpy as np
def gauss_elimination(a, b):
n = len(b)
isSolutionExists = True
errorMessage = "The system has no roots of equations or has an infinite set of them."
# Forward Elimination
for i in range(n):
# Find pivot
max_row = i
for j in range(i+1, n):
if abs(a[j][i]) > abs(a[max_row][i]):
max_row = j
# Swap rows
a[i], a[max_row] = a[max_row], a[i]
b[i], b[max_row] = b[max_row], b[i]
# Check if matrix is singular
if abs(a[i][i]) < 1e-12:
isSolutionExists = False
return (isSolutionExists, errorMessage)
# Eliminate column
for j in range(i+1, n):
ratio = a[j][i]/a[i][i]
for k in range(i, n):
a[j][k] -= ratio * a[i][k]
b[j] -= ratio * b[i]
# Backward Substitution
x = [0 for i in range(n)]
for i in range(n-1, -1, -1):
x[i] = b[i]
for j in range(i+1, n):
x[i] -= a[i][j] * x[j]
x[i] /= a[i][i]
# Calculate residual errors
r = np.dot(a, x) - b
return (isSolutionExists, x, r)
# Example usage:
n = 3
a = [[3.0, 2.0, -4.0], [2.0, 3.0, 3.0], [5.0, -3.0, 1.0]]
b = [3.0, 15.0, 14.0]
result = gauss_elimination(a,b)
if result[0]:
print("x:")
for i in range(n):
print(result[1][i])
print("r:")
for i in range(n):
print(result[2][i])
else:
print(result[1])