{"record":{"id":"14ee96dc1f05dd47","repo":"TheAlgorithms/Python","slug":"matrix-is-not-invertible","errorCode":null,"errorMessage":"Matrix is not invertible","messagePattern":"Matrix is not invertible","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"linear_algebra/matrix_inversion.py","lineNumber":26,"sourceCode":"    Parameters:\n    matrix (list[list[float]]): A square matrix.\n\n    Returns:\n    list[list[float]]: Inverted matrix if invertible, else raises error.\n\n    >>> invert_matrix([[4.0, 7.0], [2.0, 6.0]])\n    [[0.6000000000000001, -0.7000000000000001], [-0.2, 0.4]]\n    >>> invert_matrix([[1.0, 2.0], [0.0, 0.0]])\n    Traceback (most recent call last):\n        ...\n    ValueError: Matrix is not invertible\n    \"\"\"\n    np_matrix = np.array(matrix)\n\n    try:\n        inv_matrix = np.linalg.inv(np_matrix)\n    except np.linalg.LinAlgError:\n        raise ValueError(\"Matrix is not invertible\")\n\n    return inv_matrix.tolist()\n\n\nif __name__ == \"__main__\":\n    mat = [[4.0, 7.0], [2.0, 6.0]]\n    print(\"Original Matrix:\")\n    print(mat)\n    print(\"Inverted Matrix:\")\n    print(invert_matrix(mat))\n","sourceCodeStart":8,"sourceCodeEnd":37,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/matrix_inversion.py#L8-L37","documentation":"Raised by invert_matrix() in linear_algebra/matrix_inversion.py:26. The function calls np.linalg.inv() and translates NumPy's np.linalg.LinAlgError into a plain ValueError with the message 'Matrix is not invertible'. NumPy raises that LinAlgError when the input matrix is exactly singular (determinant 0), so no inverse exists.","triggerScenarios":"Calling invert_matrix([[1.0, 2.0], [0.0, 0.0]]) or any square matrix with linearly dependent rows/columns (determinant 0), e.g. [[1,2],[2,4]]. It is only raised for exact singularity; near-singular matrices return huge, numerically garbage values instead of raising.","commonSituations":"Feeding user-supplied or measured data whose rows are linearly dependent (duplicate rows, a column that is a multiple of another), constructing covariance/normal matrices from fewer samples than features (rank deficient), or unit tests that pass degenerate fixtures.","solutions":["Check the matrix condition/determinant before calling: np.linalg.cond(matrix) — if it is very large (e.g. > 1e12), treat the matrix as (numerically) singular.","If a pseudo-inverse is acceptable, use np.linalg.pinv(matrix) which never raises for singular input.","Remove or fix linearly dependent rows/columns in the source data so the matrix has full rank.","Catch ValueError at the call site to handle degenerate input explicitly."],"exampleFix":"// before\ninv = invert_matrix([[1.0, 2.0], [2.0, 4.0]])  # ValueError\n\n// after\nimport numpy as np\nif np.linalg.cond(np.array(mat)) < 1e12:\n    inv = invert_matrix(mat)\nelse:\n    inv = np.linalg.pinv(np.array(mat)).tolist()  # least-squares fallback","handlingStrategy":"try-catch","validationCode":"import numpy as np\n\ndef is_invertible(mat: list[list[float]], tol: float = 1e12) -> bool:\n    a = np.asarray(mat, dtype=float)\n    return a.ndim == 2 and a.shape[0] == a.shape[1] and np.linalg.cond(a) < tol","typeGuard":"def is_square_float_matrix(x) -> bool:\n    return (\n        isinstance(x, (list, tuple))\n        and len(x) > 0\n        and all(isinstance(r, (list, tuple)) and len(r) == len(x) for r in x)\n    )","tryCatchPattern":"try:\n    inv = invert_matrix(mat)\nexcept ValueError:\n    inv = np.linalg.pinv(np.asarray(mat, dtype=float)).tolist()  # least-squares fallback","preventionTips":["Check np.linalg.cond(matrix) before inverting; cond > ~1e12 means the result would be numerically meaningless even if it does not raise.","Validate input is a square nested list of numbers before calling.","For rank-deficient data (fewer samples than features, collinear columns), use np.linalg.pinv by design instead of catching after the fact.","Remember this only catches exact singularity — near-singular matrices silently return huge values, so a condition check is the real guard."],"tags":["linear-algebra","matrix-inverse","singular-matrix","numpy","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}