TheAlgorithms/Python · error · ValueError

power is negative

Error message

power is negative

What it means

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.

Source

Thrown at maths/fibonacci.py:273

           [0, 1]])

    >>> matrix_pow_np(m, 1)  # Same matrix when raised to the power of 1
    array([[1, 1],
           [1, 0]])

    >>> matrix_pow_np(m, 5)
    array([[8, 5],
           [5, 3]])

    >>> matrix_pow_np(m, -1)
    Traceback (most recent call last):
        ...
    ValueError: power is negative
    """
    result = np.array([[1, 0], [0, 1]], dtype=int)  # Identity Matrix
    base = m
    if power < 0:  # Negative power is not allowed
        raise ValueError("power is negative")
    while power:
        if power % 2 == 1:
            result = np.dot(result, base)
        base = np.dot(base, base)
        power //= 2
    return result


def fib_matrix_np(n: int) -> int:
    """
    Calculates the n-th Fibonacci number using matrix exponentiation.
    https://www.nayuki.io/page/fast-fibonacci-algorithms#:~:text=
    Summary:%20The%20two%20fast%20Fibonacci%20algorithms%20are%20matrix

    Args:
        n: Fibonacci sequence index

    Returns:

View on GitHub (pinned to f5988cc097)

Solutions

  1. If you genuinely need negative powers, use np.linalg.matrix_power(m, power), which inverts the matrix first.
  2. Fix the exponent computation so it cannot go negative (validate a - b >= 0).
  3. For negative Fibonacci indices use the identity fib(-n) = (-1)**(n+1) * fib(n) rather than negative matrix powers.

Example fix

# before
matrix_pow_np(m, k - 1)  # k = 0 -> power -1 -> ValueError

# after
import numpy as np
result = matrix_pow_np(m, k - 1) if k >= 1 else np.linalg.matrix_power(m, k - 1)
Defensive patterns

Strategy: validation

Validate before calling

if power < 0:
    raise ValueError(f'matrix_pow_np requires power >= 0, got {power}')
result = matrix_pow_np(m, power)

Prevention

When it happens

Trigger: Calling matrix_pow_np(m, -1) (per its doctest) with any negative exponent. The `if power < 0` check fires before the exponentiation loop.

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

Related errors


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