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
- Pass mass as a non-negative magnitude; direction of velocity does not matter here.
- Add a pre-call check `if mass < 0: ...` for data-driven pipelines.
- 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
- Only mass is sign-checked; any velocity sign is fine because abs() is applied.
- Check argument order — (mass, velocity), not (velocity, mass).
- For vector inputs, pass the mass scalar and the velocity magnitude or signed component as suits your formula.
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
- Expected a_coeffs to have {self.order + 1} elements for {sel
- n must not be negative
- Depth cannot be less than 0
- Invalid velocity. Should be a positive number.
- All input parameters must be positive
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/e6a3d58ab897df3e.
Report an issue: GitHub.