|
| 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