Convert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. If the input dataset is empty, it raises a StatisticsError. >>> fmean([3.5, 4.0, 5.25]) 4.25
(data, weights=None)
| 434 | |
| 435 | |
| 436 | def fmean(data, weights=None): |
| 437 | """Convert data to floats and compute the arithmetic mean. |
| 438 | |
| 439 | This runs faster than the mean() function and it always returns a float. |
| 440 | If the input dataset is empty, it raises a StatisticsError. |
| 441 | |
| 442 | >>> fmean([3.5, 4.0, 5.25]) |
| 443 | 4.25 |
| 444 | """ |
| 445 | try: |
| 446 | n = len(data) |
| 447 | except TypeError: |
| 448 | # Handle iterators that do not define __len__(). |
| 449 | n = 0 |
| 450 | def count(iterable): |
| 451 | nonlocal n |
| 452 | for n, x in enumerate(iterable, start=1): |
| 453 | yield x |
| 454 | data = count(data) |
| 455 | if weights is None: |
| 456 | total = fsum(data) |
| 457 | if not n: |
| 458 | raise StatisticsError('fmean requires at least one data point') |
| 459 | return total / n |
| 460 | try: |
| 461 | num_weights = len(weights) |
| 462 | except TypeError: |
| 463 | weights = list(weights) |
| 464 | num_weights = len(weights) |
| 465 | num = fsum(map(mul, data, weights)) |
| 466 | if n != num_weights: |
| 467 | raise StatisticsError('data and weights must be the same length') |
| 468 | den = fsum(weights) |
| 469 | if not den: |
| 470 | raise StatisticsError('sum of weights must be non-zero') |
| 471 | return num / den |
| 472 | |
| 473 | |
| 474 | def geometric_mean(data): |
no test coverage detected