TheAlgorithms/Python · error · TypeError

A Matrix can only be raised to the power of an int

Error message

A Matrix can only be raised to the power of an int

What it means

Raised by Matrix.__pow__ when the exponent is not an instance of int. The implementation supports only integer exponents because it computes powers by repeated multiplication (and inverses for negative powers). Note that the check is a strict isinstance test, so NumPy integer types (np.int64), floats like 2.0, and Fraction/Decimal values all fail even when mathematically integral.

Source

Thrown at matrix/matrix_class.py:342

            if self.num_columns != other.num_rows:
                raise ValueError(
                    "The number of columns in the first matrix must "
                    "be equal to the number of rows in the second"
                )
            return Matrix(
                [
                    [Matrix.dot_product(row, column) for column in other.columns()]
                    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)))

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert the exponent to a plain Python int before the power operation: matrix ** int(exponent).
  2. If the exponent arrived as a string from input/config, validate and cast with int(str) inside a try block for bad input.
  3. If you genuinely need fractional powers (e.g. matrix square roots), switch to NumPy/SciPy (scipy.linalg.fractional_matrix_power) since this class cannot do it.
  4. Watch out for NumPy scalars: use int(np.int64(3)) or .item() to get a native int.

Example fix

# before
power = np.int64(3)
result = matrix ** power  # TypeError

# after
result = matrix ** int(power)
Defensive patterns

Strategy: type-guard

Validate before calling

exponent = int(exponent) if hasattr(exponent, "__int__") else exponent
if not isinstance(exponent, int):
    raise TypeError(f"exponent must be int, got {type(exponent).__name__}")
result = matrix ** exponent

Type guard

def is_int_exponent(x) -> bool:
    """True for native int (and numpy ints); False for float/str even if integral-looking."""
    return isinstance(x, int) and not isinstance(x, bool)

Try / catch

try:
    result = matrix ** power
except TypeError as e:
    if "power of an int" in str(e) and float(power).is_integer():
        result = matrix ** int(power)
    else:
        raise

Prevention

When it happens

Trigger: matrix ** 2.0, matrix ** np.int64(3), or matrix ** "2". Also triggered when the exponent comes from a computation that produced a float (e.g. len(items) / 2) or from unmarshalled JSON data.

Common situations: Exponents read from config files or CLI args arrive as strings/floats; mixing NumPy scalars into pure-Python code; using 0.5 expecting a matrix square root (not supported by this class at all).

Related errors


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