TheAlgorithms/Python · error · ValueError

Only invertable matrices can be raised to a negative power

Error message

Only invertable matrices can be raised to a negative power

What it means

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.

Source

Thrown at matrix/matrix_class.py:350

                    for row in self.rows
                ]
            )
        else:
            raise TypeError(
                "A Matrix can only be multiplied by an int, float, or another matrix"
            )

    def __pow__(self, other: int) -> Matrix:
        if not isinstance(other, int):
            raise TypeError("A Matrix can only be raised to the power of an int")
        if not self.is_square:
            raise ValueError("Only square matrices can be raised to a power")
        if other == 0:
            return self.identity()
        if other < 0:
            if self.is_invertable():
                return self.inverse() ** (-other)
            raise ValueError(
                "Only invertable matrices can be raised to a negative power"
            )
        result = self
        for _ in range(other - 1):
            result *= self
        return result

    @classmethod
    def dot_product(cls, row: list[int], column: list[int]) -> int:
        return sum(row[i] * column[i] for i in range(len(row)))


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check invertibility before powering: if not matrix.is_invertable(), do not use negative exponents.
  2. 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.
  3. 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).
  4. For near-singular numeric data, consider regularization (add a small value to the diagonal) if an approximate inverse is acceptable.

Example fix

# before
result = matrix ** -1  # ValueError if singular

# after
if matrix.is_invertable():
    result = matrix ** -1
else:
    raise ValueError("matrix is singular; cannot invert")  # or use a solver
Defensive patterns

Strategy: validation

Validate before calling

if exponent < 0 and not matrix.is_invertable():
    raise ValueError("matrix is singular; negative powers require an inverse")
result = matrix ** exponent

Type guard

def is_invertible_square(m: Matrix) -> bool:
    """Guard: square and invertible, i.e. safe for negative exponents."""
    return isinstance(m, Matrix) and m.is_square and m.is_invertable()

Try / catch

try:
    result = matrix ** -1
except ValueError as e:
    if "invertable" in str(e):
        # singular matrix: fall back to a least-squares solver instead of inversion
        result = None  # handle singular case explicitly
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/e039b8824b51dca5. Report an issue: GitHub.