TheAlgorithms/Python · error · ValueError

vol_cuboid() only accepts non-negative values

Error message

vol_cuboid() only accepts non-negative values

What it means

Raised by vol_cuboid(width, height, length) in maths/volume.py when any of the three dimensions is negative. A cuboid with a negative edge has no physical meaning, so the function guards all three inputs before returning float(width * height * length).

Source

Thrown at maths/volume.py:201

    >>> vol_cuboid(1.6, 2.6, 3.6)
    14.976
    >>> vol_cuboid(0, 0, 0)
    0.0
    >>> vol_cuboid(-1, 2, 3)
    Traceback (most recent call last):
        ...
    ValueError: vol_cuboid() only accepts non-negative values
    >>> vol_cuboid(1, -2, 3)
    Traceback (most recent call last):
        ...
    ValueError: vol_cuboid() only accepts non-negative values
    >>> vol_cuboid(1, 2, -3)
    Traceback (most recent call last):
        ...
    ValueError: vol_cuboid() only accepts non-negative values
    """
    if width < 0 or height < 0 or length < 0:
        raise ValueError("vol_cuboid() only accepts non-negative values")
    return float(width * height * length)


def vol_cone(area_of_base: float, height: float) -> float:
    r"""
    | Calculate the Volume of a Cone.
    | Wikipedia reference: https://en.wikipedia.org/wiki/Cone

    :return: :math:`\frac{1}{3} \cdot area\_of\_base \cdot height`

    >>> vol_cone(10, 3)
    10.0
    >>> vol_cone(1, 1)
    0.3333333333333333
    >>> vol_cone(1.6, 1.6)
    0.8533333333333335
    >>> vol_cone(0, 0)
    0.0

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate width, height, length are all >= 0 at the call site before invoking vol_cuboid.
  2. When dimensions come from coordinate pairs, compute them as abs(max - min) or sort the pair first.
  3. Sanitize input files/scripts so sign errors are caught at parse time with a clearer message.

Example fix

# before
vol = vol_cuboid(x2 - x1, y2 - y1, z2 - z1)  # ValueError if any max < min

# after
vol = vol_cuboid(abs(x2 - x1), abs(y2 - y1), abs(z2 - z1))
Defensive patterns

Strategy: validation

Validate before calling

w, h, l = abs(x2 - x1), abs(y2 - y1), abs(z2 - z1)
assert min(w, h, l) >= 0  # abs() already guarantees it
vol = vol_cuboid(w, h, l)

Try / catch

try:
    vol = vol_cuboid(w, h, l)
except ValueError:
    log.error('cuboid dimensions must be non-negative: %s', (w, h, l))
    raise

Prevention

When it happens

Trigger: Calling vol_cuboid(-1, 2, 3), vol_cuboid(1, -2, 3) or vol_cuboid(1, 2, -3); dimensions computed as differences (max_x - min_x) where the ordering is inverted.

Common situations: Box dimensions derived from min/max coordinates with the operands swapped; CSV or JSON data with sign errors; unit conversions (e.g. inches to a signed delta) producing negatives.

Related errors


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