{"record":{"id":"9a54ee7f717fd4ac","repo":"TheAlgorithms/Python","slug":"power-is-negative","errorCode":null,"errorMessage":"power is negative","messagePattern":"power is negative","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/fibonacci.py","lineNumber":273,"sourceCode":"           [0, 1]])\n\n    >>> matrix_pow_np(m, 1)  # Same matrix when raised to the power of 1\n    array([[1, 1],\n           [1, 0]])\n\n    >>> matrix_pow_np(m, 5)\n    array([[8, 5],\n           [5, 3]])\n\n    >>> matrix_pow_np(m, -1)\n    Traceback (most recent call last):\n        ...\n    ValueError: power is negative\n    \"\"\"\n    result = np.array([[1, 0], [0, 1]], dtype=int)  # Identity Matrix\n    base = m\n    if power < 0:  # Negative power is not allowed\n        raise ValueError(\"power is negative\")\n    while power:\n        if power % 2 == 1:\n            result = np.dot(result, base)\n        base = np.dot(base, base)\n        power //= 2\n    return result\n\n\ndef fib_matrix_np(n: int) -> int:\n    \"\"\"\n    Calculates the n-th Fibonacci number using matrix exponentiation.\n    https://www.nayuki.io/page/fast-fibonacci-algorithms#:~:text=\n    Summary:%20The%20two%20fast%20Fibonacci%20algorithms%20are%20matrix\n\n    Args:\n        n: Fibonacci sequence index\n\n    Returns:","sourceCodeStart":255,"sourceCodeEnd":291,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/fibonacci.py#L255-L291","documentation":"Raised by matrix_pow_np() in maths/fibonacci.py when the requested power is negative. The helper raises a 2x2 matrix to a power by binary exponentiation, which starts from the identity matrix and only multiplies — it cannot invert a matrix, so power < 0 is rejected with ValueError.","triggerScenarios":"Calling matrix_pow_np(m, -1) (per its doctest) with any negative exponent. The `if power < 0` check fires before the exponentiation loop.","commonSituations":"Computing Fibonacci-style recurrences with negative indices, sign errors in exponent arithmetic (power = a - b with b > a), or generically treating matrix_pow_np like numpy's np.linalg.matrix_power which supports negative powers for invertible matrices.","solutions":["If you genuinely need negative powers, use np.linalg.matrix_power(m, power), which inverts the matrix first.","Fix the exponent computation so it cannot go negative (validate a - b >= 0).","For negative Fibonacci indices use the identity fib(-n) = (-1)**(n+1) * fib(n) rather than negative matrix powers."],"exampleFix":"# before\nmatrix_pow_np(m, k - 1)  # k = 0 -> power -1 -> ValueError\n\n# after\nimport numpy as np\nresult = matrix_pow_np(m, k - 1) if k >= 1 else np.linalg.matrix_power(m, k - 1)","handlingStrategy":"validation","validationCode":"if power < 0:\n    raise ValueError(f'matrix_pow_np requires power >= 0, got {power}')\nresult = matrix_pow_np(m, power)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Use np.linalg.matrix_power for negative powers of invertible matrices.","Check exponent differences (a - b) for negativity before calling.","Model negative Fibonacci indices with the sign identity, not negative powers."],"tags":["math","fibonacci","matrix","linear-algebra","negative-value","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}