TheAlgorithms/Python · error · ValueError

n is too large

Error message

n is too large

What it means

Raised by fib_binet() in maths/fibonacci.py when n >= 1475. Binet's formula raises phi (about 1.618) to the i-th power in IEEE-754 doubles; for i >= 1475 phi**i overflows the float range (phi**1474 is near 1.8e307, the last representable step), so the function refuses such n with ValueError instead of letting `**` raise OverflowError deep inside the comprehension.

Source

Thrown at maths/fibonacci.py:232

    >>> fib_binet(1)
    [0, 1]
    >>> fib_binet(5)
    [0, 1, 1, 2, 3, 5]
    >>> fib_binet(10)
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    >>> fib_binet(-1)
    Traceback (most recent call last):
        ...
    ValueError: n is negative
    >>> fib_binet(1475)
    Traceback (most recent call last):
        ...
    ValueError: n is too large
    """
    if n < 0:
        raise ValueError("n is negative")
    if n >= 1475:
        raise ValueError("n is too large")
    sqrt_5 = sqrt(5)
    phi = (1 + sqrt_5) / 2
    return [round(phi**i / sqrt_5) for i in range(n + 1)]


def matrix_pow_np(m: ndarray, power: int) -> ndarray:
    """
    Raises a matrix to the power of 'power' using binary exponentiation.

    Args:
        m: Matrix as a numpy array.
        power: The power to which the matrix is to be raised.

    Returns:
        The matrix raised to the power.

    Raises:
        ValueError: If power is negative.

View on GitHub (pinned to f5988cc097)

Solutions

  1. Switch to fib_matrix_np(n) or fib_memoization(n) for n >= 1475 — matrix exponentiation is exact with Python ints.
  2. Cap requested n below 1475 if you must keep Binet's formula.
  3. Use math.fibonacci-style exact algorithms (or fib_iterative for moderate n) when correctness at large indices matters.

Example fix

# before
fib_binet(2000)  # ValueError: n is too large

# after
from maths.fibonacci import fib_binet, fib_matrix_np
result = fib_binet(n) if n < 1475 else fib_matrix_np(n)
Defensive patterns

Strategy: fallback

Validate before calling

if n >= 1475:
    raise ValueError(f'fib_binet supports n < 1475, got {n}')
result = fib_binet(n)

Try / catch

try:
    value = fib_binet(n)
except ValueError as exc:
    if 'too large' in str(exc):
        value = fib_matrix_np(n)  # exact for large n
    else:
        raise

Prevention

When it happens

Trigger: Calling fib_binet(1475) or larger (per its doctest). The `if n >= 1475` guard fires before computing phi**i / sqrt_5.

Common situations: Using the closed-form formula for large Fibonacci indices (project-euler-style problems, crypto demos, stress tests), or assuming all fib_* helpers in the module share the same domain — fib_matrix_np and fib_iterative handle large n fine while fib_binet does not.

Related errors


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