TheAlgorithms/Python · error · ValueError

Frequency cannot be negative

Error message

Frequency cannot be negative

What it means

Thrown by ind_reactance() when the frequency argument is negative. Frequency in hertz is a non-negative quantity, so the function validates it after the one-zero sentinel check and refuses negative input before applying X_L = 2*pi*f*L.

Source

Thrown at electronics/ind_reactance.py:53

    ValueError: Inductive reactance cannot be negative

    >>> ind_reactance(0, 10e3, 50)
    {'inductance': 0.0007957747154594767}

    >>> ind_reactance(35e-3, 0, 50)
    {'frequency': 227.36420441699332}

    >>> ind_reactance(35e-6, 1e3, 0)
    {'reactance': 0.2199114857512855}

    """

    if (inductance, frequency, reactance).count(0) != 1:
        raise ValueError("One and only one argument must be 0")
    if inductance < 0:
        raise ValueError("Inductance cannot be negative")
    if frequency < 0:
        raise ValueError("Frequency cannot be negative")
    if reactance < 0:
        raise ValueError("Inductive reactance cannot be negative")
    if inductance == 0:
        return {"inductance": reactance / (2 * pi * frequency)}
    elif frequency == 0:
        return {"frequency": reactance / (2 * pi * inductance)}
    elif reactance == 0:
        return {"reactance": 2 * pi * frequency * inductance}
    else:
        raise ValueError("Exactly one argument must be 0")


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass frequency in Hz as a non-negative number (e.g. 50 for 50 Hz mains).
  2. If using signed FFT bins, take abs(bin) — reactance depends only on magnitude.
  3. Validate frequency >= 0 before the call when values come from external data.

Example fix

# before
ind_reactance(35e-3, -1e3, 0)  # ValueError: Frequency cannot be negative

# after
ind_reactance(35e-3, abs(-1e3), 0)  # {'reactance': 219.9114857512855}
Defensive patterns

Strategy: validation

Validate before calling

if frequency < 0:
    raise ValueError('frequency must be >= 0')

Type guard

def valid_frequency(f: float) -> bool:
    return f >= 0

Try / catch

try:
    out = ind_reactance(l, f, x)
except ValueError as exc:
    if 'Frequency cannot be negative' in str(exc):
        out = ind_reactance(l, abs(f), x)
    else:
        raise

Prevention

When it happens

Trigger: ind_reactance(35e-3, -1e3, 0) or ind_reactance(0, -50, 10) — any call where frequency < 0 and exactly one argument equals 0.

Common situations: Passing signed frequency data from FFT/dSP pipelines where negatives represent one sideband; sign flips from mixing radians/Hz conventions; spreadsheet imports mangling minus signs.

Related errors


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