TheAlgorithms/Python · error · ValueError

vol_hemisphere() only accepts non-negative values

Error message

vol_hemisphere() only accepts non-negative values

What it means

Raised by vol_hemisphere(radius) in maths/volume.py when radius is negative. The function returns radius**3 * pi * 2 / 3 and guards its single argument; radius 0 is valid (0.0).

Source

Thrown at maths/volume.py:367

    | Other references: https://www.cuemath.com/geometry/hemisphere

    :return: :math:`\frac{2}{3} \cdot \pi \cdot radius^3`

    >>> vol_hemisphere(1)
    2.0943951023931953
    >>> vol_hemisphere(7)
    718.377520120866
    >>> vol_hemisphere(1.6)
    8.57864233940253
    >>> vol_hemisphere(0)
    0.0
    >>> vol_hemisphere(-1)
    Traceback (most recent call last):
        ...
    ValueError: vol_hemisphere() only accepts non-negative values
    """
    if radius < 0:
        raise ValueError("vol_hemisphere() only accepts non-negative values")
    # Volume is radius cubed * pi * 2/3
    return pow(radius, 3) * pi * 2 / 3


def vol_circular_cylinder(radius: float, height: float) -> float:
    r"""
    | Calculate the Volume of a Circular Cylinder.
    | Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder

    :return: :math:`\pi \cdot radius^2 \cdot height`

    >>> vol_circular_cylinder(1, 1)
    3.141592653589793
    >>> vol_circular_cylinder(4, 3)
    150.79644737231007
    >>> vol_circular_cylinder(1.6, 1.6)
    12.867963509103795
    >>> vol_circular_cylinder(0, 0)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate radius >= 0 at the call site or input boundary.
  2. Use abs() when the negative is purely a sign artifact of a directional computation.
  3. Reject negative numeric fields during parsing with a message that identifies the source record.

Example fix

# before
v = vol_hemisphere(user_radius)

# after
r = abs(float(user_radius))
v = vol_hemisphere(r)
Defensive patterns

Strategy: type-guard

Validate before calling

def is_valid_radius(r) -> bool:
    return isinstance(r, (int, float)) and not isinstance(r, bool) and r >= 0

Type guard

def is_valid_radius(r) -> TypeGuard[float]:
    return isinstance(r, (int, float)) and not isinstance(r, bool) and r >= 0

Try / catch

try:
    v = vol_hemisphere(r)
except ValueError as e:
    raise ValueError(f'hemisphere radius must be >= 0, got {r}') from e

Prevention

When it happens

Trigger: Calling vol_hemisphere(-1) or vol_hemisphere(-0.2); dome/cutout radii from user input or derived computations that end up negative.

Common situations: Form inputs allowing '-2'; radius computed from a subtraction with swapped operands; mirroring geometry along an axis and accidentally keeping the sign.

Related errors


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