TheAlgorithms/Python · error · ArithmeticError

Cannot Compute Geometric Mean for these numbers.

Error message

Cannot Compute Geometric Mean for these numbers.

What it means

Raised by compute_geometric_mean in maths/geometric_mean.py when the product of the arguments is negative and the count of arguments is even. An even root of a negative number is not real, so the geometric mean is undefined over the reals in that case; the library raises ArithmeticError rather than returning a complex value. Odd counts with negative product are allowed and return a negative real mean.

Source

Thrown at maths/geometric_mean.py:38

    0.0
    >>> compute_geometric_mean(1, 5, 25, 5)
    5.0
    >>> compute_geometric_mean(2, -2)
    Traceback (most recent call last):
        ...
    ArithmeticError: Cannot Compute Geometric Mean for these numbers.
    >>> compute_geometric_mean(-5, 25, 1)
    -5.0
    """
    product = 1
    for number in args:
        if not isinstance(number, int) and not isinstance(number, float):
            raise TypeError("Not a Number")
        product *= number
    # Cannot calculate the even root for negative product.
    # Frequently they are restricted to being positive.
    if product < 0 and len(args) % 2 == 0:
        raise ArithmeticError("Cannot Compute Geometric Mean for these numbers.")
    mean = abs(product) ** (1 / len(args))
    # Since python calculates complex roots for negative products with odd roots.
    if product < 0:
        mean = -mean
    # Since it does floating point arithmetic, it gives 64**(1/3) as 3.99999996
    possible_mean = float(round(mean))
    # To check if the rounded number is actually the mean.
    if possible_mean ** len(args) == product:
        mean = possible_mean
    return mean


if __name__ == "__main__":
    from doctest import testmod

    testmod(name="compute_geometric_mean")
    print(compute_geometric_mean(-3, -27))

View on GitHub (pinned to f5988cc097)

Solutions

  1. Filter or transform negative inputs before calling, e.g. use only positive values if your domain requires a real geometric mean.
  2. Switch to abs() values if magnitude is what matters: compute_geometric_mean(*map(abs, nums)).
  3. Catch ArithmeticError explicitly and fall back to another central-tendency measure (arithmetic mean) when it fires.

Example fix

// before
mean = compute_geometric_mean(2, -2)  # ArithmeticError

// after
nums = [abs(n) for n in nums]  # if magnitudes are what you need
mean = compute_geometric_mean(*nums)
Defensive patterns

Strategy: validation

Validate before calling

from math import prod
def has_real_geometric_mean(nums) -> bool:
    p = prod(nums)
    return p >= 0 or len(nums) % 2 == 1

Try / catch

try:
    m = compute_geometric_mean(*nums)
except ArithmeticError:
    m = sum(nums) / len(nums)  # fallback: arithmetic mean

Prevention

When it happens

Trigger: Calling compute_geometric_mean(2, -2) (product -4, 2 args -> even root) or any even-length argument list whose product is negative, e.g. (-1, 3, -2, 5).

Common situations: Feeding raw sensor/financial data containing negative values without sanitization; assuming the function mirrors numpy semantics (numpy returns nan with a warning instead); even-sized datasets where sign flips occur naturally.

Related errors


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