TheAlgorithms/Python · error · ValueError

Mass can't be negative.

Error message

Mass can't be negative.

What it means

Raised by energy_from_mass(mass) when mass is negative; it computes E = m*c^2 with c = 299,792,458 m/s. Negative rest mass is unphysical for this Newtonian-to-relativistic conversion, so it is rejected. Zero mass is valid and returns 0.0.

Source

Thrown at physics/mass_energy_equivalence.py:45

    in SI units J from Mass in kg.

    mass (float): Mass of body.

    Usage example:
    >>> energy_from_mass(124.56)
    1.11948945063458e+19
    >>> energy_from_mass(320)
    2.8760165719578165e+19
    >>> energy_from_mass(0)
    0.0
    >>> energy_from_mass(-967.9)
    Traceback (most recent call last):
        ...
    ValueError: Mass can't be negative.

    """
    if mass < 0:
        raise ValueError("Mass can't be negative.")
    return mass * c**2


def mass_from_energy(energy: float) -> float:
    """
    Calculates the Mass equivalence of the Energy using m = E/c²
    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)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass mass as a non-negative magnitude; apply your own sign convention to the result if needed.
  2. Pre-validate mass >= 0 for data-driven or user-supplied inputs.
  3. Catch ValueError and re-raise with context about the offending value.

Example fix

# before
energy_from_mass(-967.9)  # ValueError

# after
energy_from_mass(967.9)   # 8.6908...e+19
Defensive patterns

Strategy: validation

Validate before calling

if mass < 0:
    raise ValueError(f'mass must be non-negative, got {mass}')
energy_from_mass(mass)

Prevention

When it happens

Trigger: energy_from_mass(-967.9) from the doctest; any pipeline where a signed mass (e.g. mass defect with a sign convention) is passed directly.

Common situations: Mass-defect calculations in nuclear physics where the defect is sometimes reported negative; sign conventions in accounting-style mass balances; unit tests sweeping negative ranges.

Related errors


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