TheAlgorithms/Python · error · ValueError

Coefficient 'a' must not be zero.

Error message

Coefficient 'a' must not be zero.

What it means

quadratic_roots() in maths/quadratic_equations_complex_numbers.py solves ax^2 + bx + c = 0 using cmath.sqrt so complex roots are supported. If a == 0 it raises ValueError("Coefficient 'a' must not be zero.") because with a = 0 the equation is linear (bx + c = 0) and the formula (-b +/- sqrt(delta)) / (2a) would divide by zero. This is a domain guard, not a numerical-robustness check: b and c are never validated.

Source

Thrown at maths/quadratic_equations_complex_numbers.py:20

from cmath import sqrt


def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]:
    """
    Given the numerical coefficients a, b and c,
    calculates the roots for any quadratic equation of the form ax^2 + bx + c

    >>> quadratic_roots(a=1, b=3, c=-4)
    (1.0, -4.0)
    >>> quadratic_roots(5, 6, 1)
    (-0.2, -1.0)
    >>> quadratic_roots(1, -6, 25)
    ((3+4j), (3-4j))
    """

    if a == 0:
        raise ValueError("Coefficient 'a' must not be zero.")
    delta = b * b - 4 * a * c

    root_1 = (-b + sqrt(delta)) / (2 * a)
    root_2 = (-b - sqrt(delta)) / (2 * a)

    return (
        root_1.real if not root_1.imag else root_1,
        root_2.real if not root_2.imag else root_2,
    )


def main():
    solution1, solution2 = quadratic_roots(a=5, b=6, c=1)
    print(f"The solutions are: {solution1} and {solution2}")


if __name__ == "__main__":
    main()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Handle the linear case yourself before calling: if a == 0 and b != 0, root is -c/b; if a == b == 0, no/infinitely many solutions depending on c.
  2. Validate a != 0 at the input boundary with a domain-specific message.
  3. Catch ValueError if zero leading coefficients are an expected runtime input.

Example fix

# before
roots = quadratic_roots(a, b, c)  # ValueError when a == 0

# after
if a == 0:
    roots = (-c / b,) if b else ()
else:
    roots = quadratic_roots(a, b, c)
Defensive patterns

Strategy: validation

Validate before calling

if a == 0:
    root = -c / b if b else None  # linear or degenerate
else:
    roots = quadratic_roots(a, b, c)

Try / catch

try:
    quadratic_roots(a, b, c)
except ValueError as exc:
    if "must not be zero" in str(exc):
        # fall back to the linear solution bx + c = 0
        roots = (-c / b,) if b else ()
    else:
        raise

Prevention

When it happens

Trigger: Calling quadratic_roots(a=0, b=2, c=1), or building coefficients from user input / curve fitting where the x^2 term collapses to zero (e.g. fitting a parabola to collinear points).

Common situations: Generic equation solvers accepting arbitrary a, b, c triples; fitting code where the quadratic coefficient legitimately vanishes; forgetting the degenerate linear case entirely.

Related errors


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