{"record":{"id":"e039b8824b51dca5","repo":"TheAlgorithms/Python","slug":"only-invertable-matrices-can-be-raised-to-a-negati","errorCode":null,"errorMessage":"Only invertable matrices can be raised to a negative power","messagePattern":"Only invertable matrices can be raised to a negative power","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_class.py","lineNumber":350,"sourceCode":"                    for row in self.rows\n                ]\n            )\n        else:\n            raise TypeError(\n                \"A Matrix can only be multiplied by an int, float, or another matrix\"\n            )\n\n    def __pow__(self, other: int) -> Matrix:\n        if not isinstance(other, int):\n            raise TypeError(\"A Matrix can only be raised to the power of an int\")\n        if not self.is_square:\n            raise ValueError(\"Only square matrices can be raised to a power\")\n        if other == 0:\n            return self.identity()\n        if other < 0:\n            if self.is_invertable():\n                return self.inverse() ** (-other)\n            raise ValueError(\n                \"Only invertable matrices can be raised to a negative power\"\n            )\n        result = self\n        for _ in range(other - 1):\n            result *= self\n        return result\n\n    @classmethod\n    def dot_product(cls, row: list[int], column: list[int]) -> int:\n        return sum(row[i] * column[i] for i in range(len(row)))\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n","sourceCodeStart":332,"sourceCodeEnd":367,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_class.py#L332-L367","documentation":"Raised by Matrix.__pow__ when a negative exponent is requested and the matrix fails the is_invertable() check (singular or non-invertible). Negative powers are implemented as inverse() ** (-other), so an inverse must exist. A matrix is singular typically when its determinant is zero, meaning its rows/columns are linearly dependent.","triggerScenarios":"matrix ** -1 on a matrix with determinant 0 (e.g. [[1, 2], [2, 4]]), or matrix ** -k for any k >= 1 on such a matrix. Only negative exponents hit this path; positive powers of singular matrices work fine.","commonSituations":"Trying to solve linear systems via matrix inversion when the system is under-determined or has redundant equations; near-singular data (collinear features in regression) that becomes exactly singular after rounding; attempting to invert a covariance/adjacency matrix with zero eigenvalues.","solutions":["Check invertibility before powering: if not matrix.is_invertable(), do not use negative exponents.","Compute the determinant to understand why the matrix is singular; look for linearly dependent rows/columns in the source data and remove or fix them.","If you actually need to solve Ax = b, use a solver rather than explicit inversion (e.g. numpy.linalg.solve, or lstsq for singular systems).","For near-singular numeric data, consider regularization (add a small value to the diagonal) if an approximate inverse is acceptable."],"exampleFix":"# before\nresult = matrix ** -1  # ValueError if singular\n\n# after\nif matrix.is_invertable():\n    result = matrix ** -1\nelse:\n    raise ValueError(\"matrix is singular; cannot invert\")  # or use a solver","handlingStrategy":"validation","validationCode":"if exponent < 0 and not matrix.is_invertable():\n    raise ValueError(\"matrix is singular; negative powers require an inverse\")\nresult = matrix ** exponent","typeGuard":"def is_invertible_square(m: Matrix) -> bool:\n    \"\"\"Guard: square and invertible, i.e. safe for negative exponents.\"\"\"\n    return isinstance(m, Matrix) and m.is_square and m.is_invertable()","tryCatchPattern":"try:\n    result = matrix ** -1\nexcept ValueError as e:\n    if \"invertable\" in str(e):\n        # singular matrix: fall back to a least-squares solver instead of inversion\n        result = None  # handle singular case explicitly\n    else:\n        raise","preventionTips":["Check is_invertable() before any negative power, especially on user-supplied data.","Watch for linearly dependent rows/columns (duplicate features, redundant equations) in source data.","Prefer linear solvers over explicit inversion when solving systems; they degrade more gracefully on singular inputs."],"tags":["matrix","singular-matrix","inverse","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}