-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathlinear_systems.py
113 lines (79 loc) · 2.61 KB
/
linear_systems.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""Iterative Methods for Linear Systems."""
import math
import numpy as np
def backward_substitution(upper, d):
"""Solve the upper linear system ux=d.
Args:
upper (numpy.ndarray): upper triangular matrix.
d (numpy.ndarray): d values.
Returns:
x (float): solution of linear the system.
"""
[n, m] = upper.shape
b = d.astype(float)
if n != m:
raise ValueError("'upper' must be a square matrix.")
x = np.zeros(n)
for i in range(n - 1, -1, -1):
if upper[i, i] == 0:
raise ValueError("'upper' is a singular matrix.")
x[i] = b[i] / upper[i, i]
b[0:i] = b[0:i] - upper[0:i, i] * x[i]
return x
def forward_substitution(lower, c):
"""Solve the lower linear system lx=c.
Args:
lower (numpy.ndarray): lower triangular matrix.
c (numpy.ndarray): c values.
Returns:
x (float): solution of linear the system.
"""
[n, m] = lower.shape
b = c.astype(float)
if n != m:
raise ValueError("'lower' must be a square matrix.")
x = np.zeros(n)
for i in range(0, n):
if lower[i, i] == 0:
raise ValueError("'lower' is a singular matrix.")
x[i] = b[i] / lower[i, i]
b[i + 1:n] = b[i + 1:n] - lower[i + 1:n, i] * x[i]
return x
def gauss_elimination_pp(a, b):
"""Gaussian Elimination with Partial Pivoting.
Calculate the upper triangular matrix from linear system Ax=b (make a row
reduction).
Args:
a (numpy.ndarray): matrix A from system Ax=b.
b (numpy.ndarray): b values.
Returns:
a (numpy.ndarray): augmented upper triangular matrix.
"""
[n, m] = a.shape
if n != m:
raise ValueError("'a' must be a square matrix.")
# Produces the augmented matrix
a = np.concatenate((a, b[:, None]), axis=1).astype(float)
# Elimination process starts
for i in range(0, n - 1):
p = i
# Comparison to select the pivot
for j in range(i + 1, n):
if math.fabs(a[j, i]) > math.fabs(a[i, i]):
# Swap rows
a[[i, j]] = a[[j, i]]
# Checking for nullity of the pivots
while p < n and a[p, i] == 0:
p += 1
if p == n:
print("Info: No unique solution.")
else:
if p != i:
# Swap rows
a[[i, p]] = a[[p, i]]
for j in range(i + 1, n):
a[j, :] = a[j, :] - a[i, :] * (a[j, i] / a[i, i])
# Checking for nonzero of last entry
if a[n - 1, n - 1] == 0:
print("Info: No unique solution.")
return a