TheAlgorithms/Python · error · ValueError

Capacitance cannot be 0 or negative

Error message

Capacitance cannot be 0 or negative

What it means

Raised by resonant_frequency() in electronics/resonant_frequency.py when capacitance <= 0 (the inductance check runs first, so this fires only when L is already valid). Same rationale as the L check: f = 1/(2*pi*sqrt(L*C)) is undefined for C <= 0, and a zero capacitor means no LC tank exists.

Source

Thrown at electronics/resonant_frequency.py:38

    Examples are given below:
    >>> resonant_frequency(inductance=10, capacitance=5)
    ('Resonant frequency', 0.022507907903927652)
    >>> resonant_frequency(inductance=0, capacitance=5)
    Traceback (most recent call last):
      ...
    ValueError: Inductance cannot be 0 or negative
    >>> resonant_frequency(inductance=10, capacitance=0)
    Traceback (most recent call last):
      ...
    ValueError: Capacitance cannot be 0 or negative
    """

    if inductance <= 0:
        raise ValueError("Inductance cannot be 0 or negative")

    elif capacitance <= 0:
        raise ValueError("Capacitance cannot be 0 or negative")

    else:
        return (
            "Resonant frequency",
            float(1 / (2 * pi * (sqrt(inductance * capacitance)))),
        )


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a strictly positive capacitance in farads.
  2. Call with keywords (inductance=..., capacitance=...) to avoid positional swaps.
  3. Pre-check both values: `assert L > 0 and C > 0` before the call in test/setup code.

Example fix

# before
resonant_frequency(10, 0)  # ValueError: Capacitance cannot be 0 or negative

# after
freq = resonant_frequency(inductance=10, capacitance=5)
Defensive patterns

Strategy: validation

Validate before calling

if not (capacitance > 0):
    raise ConfigError("capacitance must be > 0 farads")

Type guard

def valid_capacitance(c) -> bool:
    return isinstance(c, (int, float)) and c > 0

Try / catch

try:
    _, freq = resonant_frequency(inductance=L, capacitance=C)
except ValueError as exc:
    # inductance is checked first; if you get here, L was fine and C is bad
    raise SimulationConfigError(str(exc)) from exc

Prevention

When it happens

Trigger: resonant_frequency(inductance=10, capacitance=0); negative capacitance from a bad parse; swapping arguments positionally so a 0 meant for another parameter lands in capacitance.

Common situations: Permutations of positional args (L and C are both plain floats, so a swap type-checks fine); optional capacitance defaulting to 0 in a GUI form; tolerance deltas subtracted down to or below zero.

Related errors


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