Loading the problem
Before you start
Compute the determinant of a square matrix, without np.linalg.det.
The cofactor expansion you learned by hand costs O(n!), which is hopeless past
about n = 10. Do it by elimination instead, which is O(n^3):
-1 per swap.Use partial pivoting for stability. If the best available pivot in a column is
smaller than 1e-12, the matrix is singular and the determinant is 0.0.
The determinant of an empty (0, 0) matrix is 1.0 by convention.
def determinant(A):
Input
determinant(np.array([[1.0, 2.0], [3.0, 4.0]]))
Output
-2.0
Reasoning
For a 2 by 2 matrix this is 1 * 4 - 2 * 3 = -2. With elimination: pivoting swaps the rows (sign -1), the diagonal becomes 3 and 2/3, and -1 * 3 * 2/3 = -2.
1e-12, return 0.0.(0, 0) matrix is 1.0.np.linalg.det.Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell