def test_solve_linear_system_and_get_back_to_earth(): # We need to solve this linear system in order to fly back to the Earth. # Don't ask how, it just works. s = """| 1 1 1 | | 0 2 5 | | 2 5 -1 |""" X = str_to_array(s) Y = [[6], [-4], [27]] det = determinant(X) I, J = len(X), len(X[0]) def cofactor(X, i, j): sgn = (-1)**(i + j) minor = determinant(submatrix(X, i, j)) return sgn * minor cofactor_matrix = [[cofactor(X, i, j) for j in range(J)] for i in range(I)] adjucate_matrix = transpose(cofactor_matrix) det = determinant(X) X_inverse = mul(adjucate_matrix, 1 / det) result = matmul(X_inverse, Y) expected = [[5], [3], [-2]] assert numpy.isclose(result, expected).all() print("Congratulations! You just solved the linear system and can fly " "back to Earth :-)")
def test_100x99_with_99x200_multiplication(self): numpy.random.seed(sum(ord(c) for c in "Drink more coffee")) X = numpy.random.randint(-5, +6, (100, 99)).tolist() Y = numpy.random.randint(-5, +6, (99, 200)).tolist() expected = numpy.matmul(X, Y).tolist() result = matmul(X, Y) assert result == expected
def test_100x100_with_100x_1_multiplication(self): numpy.random.seed(420) X = numpy.random.randint(-5, +6, (100, 100)).tolist() Y = numpy.random.randint(-5, +6, (100, 1)).tolist() expected = numpy.matmul(X, Y).tolist() result = matmul(X, Y) assert result == expected
def test_simple_4x4_multiplication(self): X = [[5, 1, 7, 1], [9, 4, 4, 2], [7, 4, 5, 1], [7, 5, 8, 8]] Y = [[6, 8, 2, 4], [1, 5, 8, 1], [8, 7, 1, 4], [8, 6, 7, 9]] expected = [ [95, 100, 32, 58], [106, 132, 68, 74], [94, 117, 58, 61], [175, 185, 118, 137], ] result = matmul(X, Y) assert result == expected
def test_identity_2x2_returns_same_value(self): X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Y = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] result = matmul(X, Y) assert result == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def test_simple_2x2_multiplication(self): X = [[1, 2], [3, 4]] Y = [[5, 6], [7, 8]] result = matmul(X, Y) assert result == [[19, 22], [43, 50]]