{"record":{"id":"dd6aed0ade846e35","repo":"TheAlgorithms/Python","slug":"cannot-compute-geometric-mean-for-these-numbers","errorCode":null,"errorMessage":"Cannot Compute Geometric Mean for these numbers.","messagePattern":"Cannot Compute Geometric Mean for these numbers\\.","errorType":"exception","errorClass":"ArithmeticError","httpStatus":null,"severity":"error","filePath":"maths/geometric_mean.py","lineNumber":38,"sourceCode":"    0.0\n    >>> compute_geometric_mean(1, 5, 25, 5)\n    5.0\n    >>> compute_geometric_mean(2, -2)\n    Traceback (most recent call last):\n        ...\n    ArithmeticError: Cannot Compute Geometric Mean for these numbers.\n    >>> compute_geometric_mean(-5, 25, 1)\n    -5.0\n    \"\"\"\n    product = 1\n    for number in args:\n        if not isinstance(number, int) and not isinstance(number, float):\n            raise TypeError(\"Not a Number\")\n        product *= number\n    # Cannot calculate the even root for negative product.\n    # Frequently they are restricted to being positive.\n    if product < 0 and len(args) % 2 == 0:\n        raise ArithmeticError(\"Cannot Compute Geometric Mean for these numbers.\")\n    mean = abs(product) ** (1 / len(args))\n    # Since python calculates complex roots for negative products with odd roots.\n    if product < 0:\n        mean = -mean\n    # Since it does floating point arithmetic, it gives 64**(1/3) as 3.99999996\n    possible_mean = float(round(mean))\n    # To check if the rounded number is actually the mean.\n    if possible_mean ** len(args) == product:\n        mean = possible_mean\n    return mean\n\n\nif __name__ == \"__main__\":\n    from doctest import testmod\n\n    testmod(name=\"compute_geometric_mean\")\n    print(compute_geometric_mean(-3, -27))\n","sourceCodeStart":20,"sourceCodeEnd":56,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/geometric_mean.py#L20-L56","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Filter or transform negative inputs before calling, e.g. use only positive values if your domain requires a real geometric mean.","Switch to abs() values if magnitude is what matters: compute_geometric_mean(*map(abs, nums)).","Catch ArithmeticError explicitly and fall back to another central-tendency measure (arithmetic mean) when it fires."],"exampleFix":"// before\nmean = compute_geometric_mean(2, -2)  # ArithmeticError\n\n// after\nnums = [abs(n) for n in nums]  # if magnitudes are what you need\nmean = compute_geometric_mean(*nums)","handlingStrategy":"validation","validationCode":"from math import prod\ndef has_real_geometric_mean(nums) -> bool:\n    p = prod(nums)\n    return p >= 0 or len(nums) % 2 == 1","typeGuard":null,"tryCatchPattern":"try:\n    m = compute_geometric_mean(*nums)\nexcept ArithmeticError:\n    m = sum(nums) / len(nums)  # fallback: arithmetic mean","preventionTips":["Check product sign against argument count before calling","Sanitize negative values if your domain defines geometric mean only for positives"],"tags":["math","statistics","geometric-mean","domain-error","negative-values"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}