TheAlgorithms/Python · error · ValueError

vol_sphere() only accepts non-negative values

Error message

vol_sphere() only accepts non-negative values

What it means

Raised by vol_sphere(radius) in maths/volume.py when radius is negative. The function returns 4/3 * pi * radius**3 and guards the single input; radius 0 is valid and returns 0.0. Note vol_sphere is also called internally by vol_spheres_intersect and vol_spheres_union, but those pre-validate, so in practice this error means you called vol_sphere directly with a negative value.

Source

Thrown at maths/volume.py:340

    | 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
    >>> vol_sphere(-1)
    Traceback (most recent call last):
        ...
    ValueError: vol_sphere() only accepts non-negative values
    """
    if radius < 0:
        raise ValueError("vol_sphere() only accepts non-negative values")
    # Volume is 4/3 * pi * radius cubed
    return 4 / 3 * pi * pow(radius, 3)


def vol_hemisphere(radius: float) -> float:
    r"""
    | Calculate the volume of a hemisphere
    | Wikipedia reference: https://en.wikipedia.org/wiki/Hemisphere
    | 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

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check radius >= 0 before the call; use abs() when the value is known to be a magnitude with a possible sign artifact.
  2. Validate numeric fields at parse time so negative radii fail with your own error identifying the offending row.
  3. If negatives are meaningful in your domain (signed offsets), map them to magnitudes before calling vol_sphere.

Example fix

# before
v = vol_sphere(float(row['radius']))

# after
r = float(row['radius'])
if r < 0:
    raise ValueError(f"negative radius in row {row}: {r}")
v = vol_sphere(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_sphere(r)
except ValueError:
    r = abs(r)  # only if sign is known artifact; otherwise re-raise
    v = vol_sphere(r)

Prevention

When it happens

Trigger: Calling vol_sphere(-1) or vol_sphere(-0.5); radii parsed from strings with a leading '-', or derived from sqrt of mis-signed values, or from differences of unordered points.

Common situations: Parsing 'r: -3' rows from a data file; computing radius as x2 - x1 without abs(); sensor or CAD exports that encode direction in the radius sign.

Related errors


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