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)
| 222 | |
| 223 | |
| 224 | def 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 | |
| 264 | def harmonic_mean(data, weights=None): |
searching dependent graphs…