{"record":{"id":"090c3016fae80ac4","repo":"TheAlgorithms/Python","slug":"a-matrix-can-only-be-raised-to-the-power-of-an-int","errorCode":null,"errorMessage":"A Matrix can only be raised to the power of an int","messagePattern":"A Matrix can only be raised to the power of an int","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_class.py","lineNumber":342,"sourceCode":"            if self.num_columns != other.num_rows:\n                raise ValueError(\n                    \"The number of columns in the first matrix must \"\n                    \"be equal to the number of rows in the second\"\n                )\n            return Matrix(\n                [\n                    [Matrix.dot_product(row, column) for column in other.columns()]\n                    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)))","sourceCodeStart":324,"sourceCodeEnd":360,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_class.py#L324-L360","documentation":"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.","triggerScenarios":"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.","commonSituations":"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).","solutions":["Convert the exponent to a plain Python int before the power operation: matrix ** int(exponent).","If the exponent arrived as a string from input/config, validate and cast with int(str) inside a try block for bad input.","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.","Watch out for NumPy scalars: use int(np.int64(3)) or .item() to get a native int."],"exampleFix":"# before\npower = np.int64(3)\nresult = matrix ** power  # TypeError\n\n# after\nresult = matrix ** int(power)","handlingStrategy":"type-guard","validationCode":"exponent = int(exponent) if hasattr(exponent, \"__int__\") else exponent\nif not isinstance(exponent, int):\n    raise TypeError(f\"exponent must be int, got {type(exponent).__name__}\")\nresult = matrix ** exponent","typeGuard":"def is_int_exponent(x) -> bool:\n    \"\"\"True for native int (and numpy ints); False for float/str even if integral-looking.\"\"\"\n    return isinstance(x, int) and not isinstance(x, bool)","tryCatchPattern":"try:\n    result = matrix ** power\nexcept TypeError as e:\n    if \"power of an int\" in str(e) and float(power).is_integer():\n        result = matrix ** int(power)\n    else:\n        raise","preventionTips":["Coerce exponents with int() at the boundary where they enter (CLI, config, JSON).","Remember numpy integer scalars are not Python ints — call .item() when passing them.","This class has no fractional powers; pick scipy.linalg.fractional_matrix_power for that need."],"tags":["matrix","typeerror","exponent","numpy-interop"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}