Skip to content

Instantly share code, notes, and snippets.

@deoxys314
Created March 11, 2021 12:45
Show Gist options
  • Save deoxys314/0b32144ecb5527883f9de535c390a299 to your computer and use it in GitHub Desktop.
Save deoxys314/0b32144ecb5527883f9de535c390a299 to your computer and use it in GitHub Desktop.
import math
import operator
from functools import reduce
from itertools import combinations
from typing import Union
Number = Union[int, float]
def all_close(*values: Number):
return all(math.isclose(a, b) for a, b in combinations(values, 2))
def gmdn(*values: Number, iteration: int = 1):
n = len(values)
if n <= 1:
raise TypeError(f"Not enough values provided, expected at least 2, got {len(values)}.")
a_mean = sum(values) / n
g_mean = reduce(operator.mul, values) ** (1 / n)
median = values[math.floor((n + 1) / 2)]
if all_close(a_mean, g_mean, median):
return a_mean, iteration
return gmdn(a_mean, g_mean, median)
# testing
def test_xkcd_value():
value, iterations = gmdn(1, 1, 2, 3, 5)
assert math.isclose(value, 2.089)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment