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)
| 179 | |
| 180 | |
| 181 | def fmean(data, weights=None): |
| 182 | """Convert data to floats and compute the arithmetic mean. |
| 183 | |
| 184 | This runs faster than the mean() function and it always returns a float. |
| 185 | If the input dataset is empty, it raises a StatisticsError. |
| 186 | |
| 187 | >>> fmean([3.5, 4.0, 5.25]) |
| 188 | 4.25 |
| 189 | |
| 190 | """ |
| 191 | if weights is None: |
| 192 | |
| 193 | try: |
| 194 | n = len(data) |
| 195 | except TypeError: |
| 196 | # Handle iterators that do not define __len__(). |
| 197 | counter = count() |
| 198 | total = fsum(map(itemgetter(0), zip(data, counter))) |
| 199 | n = next(counter) |
| 200 | else: |
| 201 | total = fsum(data) |
| 202 | |
| 203 | if not n: |
| 204 | raise StatisticsError('fmean requires at least one data point') |
| 205 | |
| 206 | return total / n |
| 207 | |
| 208 | if not isinstance(weights, (list, tuple)): |
| 209 | weights = list(weights) |
| 210 | |
| 211 | try: |
| 212 | num = sumprod(data, weights) |
| 213 | except ValueError: |
| 214 | raise StatisticsError('data and weights must be the same length') |
| 215 | |
| 216 | den = fsum(weights) |
| 217 | |
| 218 | if not den: |
| 219 | raise StatisticsError('sum of weights must be non-zero') |
| 220 | |
| 221 | return num / den |
| 222 | |
| 223 | |
| 224 | def geometric_mean(data): |
searching dependent graphs…