TheAlgorithms/Python · error · ValueError

vol_pyramid() only accepts non-negative values

Error message

vol_pyramid() only accepts non-negative values

What it means

Raised by vol_pyramid(area_of_base, height) in maths/volume.py when height or area_of_base is negative. The function computes area_of_base * height / 3.0 and rejects negative inputs; zero values are allowed and return 0.0.

Source

Thrown at maths/volume.py:315

    >>> vol_pyramid(10, 3)
    10.0
    >>> vol_pyramid(1.5, 3)
    1.5
    >>> vol_pyramid(1.6, 1.6)
    0.8533333333333335
    >>> vol_pyramid(0, 0)
    0.0
    >>> vol_pyramid(-1, 1)
    Traceback (most recent call last):
        ...
    ValueError: vol_pyramid() only accepts non-negative values
    >>> vol_pyramid(1, -1)
    Traceback (most recent call last):
        ...
    ValueError: vol_pyramid() only accepts non-negative values
    """
    if height < 0 or area_of_base < 0:
        raise ValueError("vol_pyramid() only accepts non-negative values")
    return area_of_base * height / 3.0


def vol_sphere(radius: float) -> float:
    r"""
    | Calculate the Volume of a Sphere.
    | Wikipedia reference: https://en.wikipedia.org/wiki/Sphere

    :return: :math:`\frac{4}{3} \cdot \pi \cdot r^3`

    >>> vol_sphere(5)
    523.5987755982989
    >>> vol_sphere(1)
    4.1887902047863905
    >>> vol_sphere(1.6)
    17.15728467880506
    >>> vol_sphere(0)
    0.0

View on GitHub (pinned to f5988cc097)

Solutions

  1. Apply abs() to signed base areas and height deltas before calling.
  2. Validate at your data boundary (parser/DB layer) so negatives never reach geometry code.
  3. Wrap the call in try/except ValueError to convert to a domain-specific error for end-user flows.

Example fix

# before
vol = vol_pyramid(base_area, tip_z - base_z)  # ValueError when tip below base

# after
vol = vol_pyramid(abs(base_area), abs(tip_z - base_z))
Defensive patterns

Strategy: validation

Validate before calling

area = abs(area_of_base)
h = abs(tip_z - base_z)
vol = vol_pyramid(area, h)

Try / catch

try:
    vol = vol_pyramid(area, h)
except ValueError:
    log.warning('rejecting pyramid with negative base/height: %s', (area, h))
    raise

Prevention

When it happens

Trigger: Calling vol_pyramid(-1, 1) or vol_pyramid(1, -1); passing a signed base area from a polygon routine or a negative height from an inverted vertical delta.

Common situations: Same family of issues as vol_cone/vol_prism: winding-sensitive area computations and orientation-encoded heights; also copy-paste of test fixtures containing negative placeholder values.

Related errors


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