TheAlgorithms/Python · error · ValueError

The mass of a body cannot be negative

Error message

The mass of a body cannot be negative

What it means

Raised by kinetic_energy(mass, velocity) when mass is negative; kinetic energy KE = 0.5*m*|v|^2 requires non-negative mass. Velocity sign is intentionally allowed — the function applies abs(velocity), and the doctest shows kinetic_energy(20, -20) == 4000.0.

Source

Thrown at physics/kinetic_energy.py:43

    The kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv²

    >>> kinetic_energy(10,10)
    500.0
    >>> kinetic_energy(0,10)
    0.0
    >>> kinetic_energy(10,0)
    0.0
    >>> kinetic_energy(20,-20)
    4000.0
    >>> kinetic_energy(0,0)
    0.0
    >>> kinetic_energy(2,2)
    4.0
    >>> kinetic_energy(100,100)
    500000.0
    """
    if mass < 0:
        raise ValueError("The mass of a body cannot be negative")
    return 0.5 * mass * abs(velocity) * abs(velocity)


if __name__ == "__main__":
    import doctest

    doctest.testmod(verbose=True)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass mass as a non-negative magnitude; direction of velocity does not matter here.
  2. Add a pre-call check `if mass < 0: ...` for data-driven pipelines.
  3. If a negative result from physics computation appears, fix the upstream state, not this guard.

Example fix

# before
kinetic_energy(-10, 0)  # ValueError

# after
kinetic_energy(10, 0)   # 0.0; velocity may be any sign
Defensive patterns

Strategy: validation

Validate before calling

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

Prevention

When it happens

Trigger: kinetic_energy(-5, 10); passing a signed coordinate or momentum-like value where mass is expected. Negative velocity never triggers this error.

Common situations: Vector components with signs fed into a scalar function; mass values from a solver iteration that went negative; confusing the parameter order and passing velocity first.

Related errors


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