TheAlgorithms/Python · error · ValueError

Energy can't be negative.

Error message

Energy can't be negative.

What it means

Raised by mass_from_energy(energy) when energy is negative; it computes m = E/c^2. Negative energy has no mass equivalent in this classical relation, so it is rejected. Zero energy is valid and returns 0.0.

Source

Thrown at physics/mass_energy_equivalence.py:70

    in SI units kg from Energy in J.

    energy (float): Mass of body.

    Usage example:
    >>> mass_from_energy(124.56)
    1.3859169098203872e-15
    >>> mass_from_energy(320)
    3.560480179371579e-15
    >>> mass_from_energy(0)
    0.0
    >>> mass_from_energy(-967.9)
    Traceback (most recent call last):
        ...
    ValueError: Energy can't be negative.

    """
    if energy < 0:
        raise ValueError("Energy can't be negative.")
    return energy / c**2


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass the magnitude of the energy: abs(energy) when the sign only encodes direction of transfer.
  2. Clamp noisy measurements with max(0.0, energy) before calling.
  3. Wrap in try/except ValueError for user-facing input handling.

Example fix

# before
mass_from_energy(-967.9)  # ValueError

# after
mass_from_energy(abs(-967.9))  # 1.076...e-14
Defensive patterns

Strategy: validation

Validate before calling

energy = max(0.0, energy)  # or abs(energy) if sign encodes transfer direction
if energy < 0:
    raise ValueError('energy must be non-negative')
mass_from_energy(energy)

Prevention

When it happens

Trigger: mass_from_energy(-967.9) from the doctest; passing a signed energy delta (e.g. binding energy reported as negative) instead of its magnitude.

Common situations: Binding-energy or potential-energy conventions where released energy is negative; sensor noise producing tiny negative readings near zero; ledger-style sums that go below zero.

Related errors


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