TheAlgorithms/Python · error · ValueError
The height above the ground cannot be negative
Error message
The height above the ground cannot be negative
What it means
Raised by potential_energy(mass, height) in physics/potential_energy.py when height < 0. Height is measured above the ground reference, so negative heights are rejected; height 0 with any non-negative mass returns 0.0. The mass check runs first, so a negative mass masks a negative height error.
Source
Thrown at physics/potential_energy.py:54
>>> potential_energy(0,5)
0.0
>>> potential_energy(8,0)
0.0
>>> potential_energy(10,5)
490.3325
>>> potential_energy(0,0)
0.0
>>> potential_energy(2,8)
156.9064
>>> potential_energy(20,100)
19613.3
"""
if mass < 0:
# handling of negative values of mass
raise ValueError("The mass of a body cannot be negative")
if height < 0:
# handling of negative values of height
raise ValueError("The height above the ground cannot be negative")
return mass * g * height
if __name__ == "__main__":
from doctest import testmod
testmod(name="potential_energy")
View on GitHub (pinned to f5988cc097)
Solutions
- Rebase heights to your reference level: height = y_object - y_reference, ensuring it is >= 0 for the configurations you model
- If negative heights are meaningful in your reference frame, shift them: height = y - min_y before calling
- Validate height >= 0 where the data enters your program
Example fix
# before potential_energy(10, ground_y - object_y) # negative when object below ground # after potential_energy(10, max(0.0, object_y - ground_y)) # or rebase reference explicitly
Defensive patterns
Strategy: validation
Validate before calling
height = object_y - reference_y # choose the reference explicitly
if height < 0:
raise ValueError(f"height above reference must be >= 0, got {height}")
potential_energy(mass, height) Try / catch
try:
potential_energy(mass, height)
except ValueError as e:
if "height" in str(e):
height = abs(height) # or rebase the reference level
potential_energy(mass, height)
else:
raise Prevention
- Pick one reference level and always pass height relative to it
- Depths below ground are negative — rebase before calling
When it happens
Trigger: potential_energy(10, -5); height computed as y_object - y_ground with operands swapped, or depth/underground positions passed without rebasing to the chosen reference level.
Common situations: World-coordinate systems where ground is not at y=0; choosing a different potential-energy reference level without shifting heights; depth values (below ground, naturally negative) passed as heights.
Related errors
- Gravitational force can not be negative
- Distance can not be negative
- Mass can not be negative
- The length should be non-negative
- The mass of a body cannot be negative
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/59ed49911094eeed.
Report an issue: GitHub.