Skip to content

Commit 27aeeac

Browse files
committed
fix: select the largest absolute pivot in Gaussian elimination
1 parent 5675c6d commit 27aeeac

2 files changed

Lines changed: 59 additions & 2 deletions

File tree

‎Gauss Elimination with Partial Pivoting/main.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
def gauss_partial(matrix: list, index_column: int):
2+
"""Move the row with the largest remaining pivot magnitude into place."""
23
index_max_val = index_column
34

45
for i in range(index_column, len(matrix)):
5-
if matrix[index_column][index_column] < abs(matrix[i][index_column]):
6+
if abs(matrix[index_max_val][index_column]) < abs(matrix[i][index_column]):
67
index_max_val = i
78

89
if index_column != index_max_val:
@@ -117,4 +118,4 @@ def take_matrix() -> list:
117118
print(*(f'{val}' for val in line), end='')
118119
print("]")
119120

120-
resolve_matrix(matrix)
121+
resolve_matrix(matrix)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import io
2+
import unittest
3+
from contextlib import redirect_stdout
4+
5+
from main import gauss_partial, resolve_matrix
6+
7+
8+
class PartialPivotingTests(unittest.TestCase):
9+
def test_selects_largest_value_even_when_a_smaller_value_follows(self):
10+
matrix = [[1, 1, 0, 2], [10, 0, 0, 10], [2, 0, 1, 3]]
11+
12+
gauss_partial(matrix, 0)
13+
14+
self.assertEqual(matrix, [[10, 0, 0, 10], [1, 1, 0, 2], [2, 0, 1, 3]])
15+
16+
def test_keeps_negative_pivot_with_largest_magnitude(self):
17+
matrix = [[-10, 1, -9], [2, 1, 3]]
18+
19+
gauss_partial(matrix, 0)
20+
21+
self.assertEqual(matrix, [[-10, 1, -9], [2, 1, 3]])
22+
23+
def test_selects_negative_candidate_with_largest_magnitude(self):
24+
matrix = [[1, 1, 0, 2], [-10, 0, 0, -10], [2, 0, 1, 3]]
25+
26+
gauss_partial(matrix, 0)
27+
28+
self.assertEqual(matrix, [[-10, 0, 0, -10], [1, 1, 0, 2], [2, 0, 1, 3]])
29+
30+
def test_keeps_first_row_when_pivot_magnitudes_are_equal(self):
31+
matrix = [[-10, 1, -9], [10, 1, 11]]
32+
33+
gauss_partial(matrix, 0)
34+
35+
self.assertEqual(matrix, [[-10, 1, -9], [10, 1, 11]])
36+
37+
def test_only_swaps_rows_in_the_active_submatrix(self):
38+
matrix = [[100, 100, 0, 200], [0, 1, 1, 2], [0, -10, 1, -9]]
39+
40+
gauss_partial(matrix, 1)
41+
42+
self.assertEqual(matrix, [[100, 100, 0, 200], [0, -10, 1, -9], [0, 1, 1, 2]])
43+
44+
def test_solves_system_with_negative_pivot_and_zero_below_it(self):
45+
matrix = [[-1, 1, 0], [0, 1, 1]]
46+
output = io.StringIO()
47+
48+
with redirect_stdout(output):
49+
resolve_matrix(matrix)
50+
51+
self.assertIn('x_0 = 1.0', output.getvalue())
52+
self.assertIn('x_1 = 1.0', output.getvalue())
53+
54+
55+
if __name__ == '__main__':
56+
unittest.main()

0 commit comments

Comments
 (0)