MCPcopy Index your code
hub / github.com/python/cpython / geometric_mean

Function geometric_mean

Lib/statistics.py:224–261  ·  view source on GitHub ↗

Convert data to floats and compute the geometric mean. Raises a StatisticsError if the input dataset is empty or if it contains a negative value. Returns zero if the product of inputs is zero. No special efforts are made to achieve exact results. (However, this may change in t

(data)

Source from the content-addressed store, hash-verified

222
223
224def geometric_mean(data):
225 """Convert data to floats and compute the geometric mean.
226
227 Raises a StatisticsError if the input dataset is empty
228 or if it contains a negative value.
229
230 Returns zero if the product of inputs is zero.
231
232 No special efforts are made to achieve exact results.
233 (However, this may change in the future.)
234
235 >>> round(geometric_mean([54, 24, 36]), 9)
236 36.0
237
238 """
239 n = 0
240 found_zero = False
241
242 def count_positive(iterable):
243 nonlocal n, found_zero
244 for n, x in enumerate(iterable, start=1):
245 if x > 0.0 or math.isnan(x):
246 yield x
247 elif x == 0.0:
248 found_zero = True
249 else:
250 raise StatisticsError('No negative inputs allowed', x)
251
252 total = fsum(map(log, count_positive(data)))
253
254 if not n:
255 raise StatisticsError('Must have a non-empty dataset')
256 if math.isnan(total):
257 return math.nan
258 if found_zero:
259 return math.nan if total == math.inf else 0.0
260
261 return exp(total / n)
262
263
264def harmonic_mean(data, weights=None):

Callers 6

test_basicsMethod · 0.85
test_big_and_smallMethod · 0.85
test_error_casesMethod · 0.85
test_special_valuesMethod · 0.85

Calls 2

count_positiveFunction · 0.85
StatisticsErrorClass · 0.85

Tested by 6

test_basicsMethod · 0.68
test_big_and_smallMethod · 0.68
test_error_casesMethod · 0.68
test_special_valuesMethod · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…