TheAlgorithms/Python · error · ValueError

Frequency can't be negative.

Error message

Frequency can't be negative.

What it means

Raised by maximum_kinetic_energy(frequency, work_function, in_ev) in physics/photoelectric_effect.py when frequency < 0. The photoelectric equation K_max = h*f - W needs a non-negative frequency; negative frequencies are unphysical and rejected before the max() clamp runs. Note the sibling doctest shows non-numeric work_function raises TypeError from the subtraction, not a dedicated message.

Source

Thrown at physics/photoelectric_effect.py:58

    >>> maximum_kinetic_energy(1000000,2)
    0
    >>> maximum_kinetic_energy(1000000,2,True)
    0
    >>> maximum_kinetic_energy(10000000000000000,2,True)
    39.357000000000006
    >>> maximum_kinetic_energy(-9,20)
    Traceback (most recent call last):
        ...
    ValueError: Frequency can't be negative.

    >>> maximum_kinetic_energy(1000,"a")
    Traceback (most recent call last):
        ...
    TypeError: unsupported operand type(s) for -: 'float' and 'str'

    """
    if frequency < 0:
        raise ValueError("Frequency can't be negative.")
    if in_ev:
        return max(PLANCK_CONSTANT_EVS * frequency - work_function, 0)
    return max(PLANCK_CONSTANT_JS * frequency - work_function, 0)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a non-negative frequency in Hz, e.g. maximum_kinetic_energy(1e15, 2.0)
  2. If your data is wavelengths, convert first: frequency = 299792458 / wavelength, and validate wavelength > 0
  3. Filter sentinel values (frequency < 0) out of datasets before computing

Example fix

# before
maximum_kinetic_energy(-9, 20)
# ValueError: Frequency can't be negative.

# after
frequency = 299792458 / wavelength  # wavelength must be > 0
maximum_kinetic_energy(frequency, 20)
Defensive patterns

Strategy: validation

Validate before calling

if frequency < 0:
    raise ValueError(f"frequency must be >= 0 Hz, got {frequency}")
maximum_kinetic_energy(frequency, work_function)

Try / catch

try:
    ke = maximum_kinetic_energy(frequency, work_function)
except ValueError as e:
    if "Frequency" in str(e):
        raise ValueError("check wavelength->frequency conversion") from e
    raise

Prevention

When it happens

Trigger: maximum_kinetic_energy(-9, 20) — negative frequency as in the doctest; frequencies derived from wavelength via f = c/wavelength where a negative wavelength was passed in; data arrays containing sentinel values like -1.

Common situations: Unit confusion between wavelength and frequency passed into the frequency slot; spectroscopy datasets using -1 as a missing-value marker; sign conventions from Doppler-shift code (blueshift/redshift as signed deltas) reused directly.

Related errors


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