statistics.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. """
  2. Basic statistics module.
  3. This module provides functions for calculating statistics of data, including
  4. averages, variance, and standard deviation.
  5. Calculating averages
  6. --------------------
  7. ================== ==================================================
  8. Function Description
  9. ================== ==================================================
  10. mean Arithmetic mean (average) of data.
  11. fmean Fast, floating point arithmetic mean.
  12. geometric_mean Geometric mean of data.
  13. harmonic_mean Harmonic mean of data.
  14. median Median (middle value) of data.
  15. median_low Low median of data.
  16. median_high High median of data.
  17. median_grouped Median, or 50th percentile, of grouped data.
  18. mode Mode (most common value) of data.
  19. multimode List of modes (most common values of data).
  20. quantiles Divide data into intervals with equal probability.
  21. ================== ==================================================
  22. Calculate the arithmetic mean ("the average") of data:
  23. >>> mean([-1.0, 2.5, 3.25, 5.75])
  24. 2.625
  25. Calculate the standard median of discrete data:
  26. >>> median([2, 3, 4, 5])
  27. 3.5
  28. Calculate the median, or 50th percentile, of data grouped into class intervals
  29. centred on the data values provided. E.g. if your data points are rounded to
  30. the nearest whole number:
  31. >>> median_grouped([2, 2, 3, 3, 3, 4]) #doctest: +ELLIPSIS
  32. 2.8333333333...
  33. This should be interpreted in this way: you have two data points in the class
  34. interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
  35. the class interval 3.5-4.5. The median of these data points is 2.8333...
  36. Calculating variability or spread
  37. ---------------------------------
  38. ================== =============================================
  39. Function Description
  40. ================== =============================================
  41. pvariance Population variance of data.
  42. variance Sample variance of data.
  43. pstdev Population standard deviation of data.
  44. stdev Sample standard deviation of data.
  45. ================== =============================================
  46. Calculate the standard deviation of sample data:
  47. >>> stdev([2.5, 3.25, 5.5, 11.25, 11.75]) #doctest: +ELLIPSIS
  48. 4.38961843444...
  49. If you have previously calculated the mean, you can pass it as the optional
  50. second argument to the four "spread" functions to avoid recalculating it:
  51. >>> data = [1, 2, 2, 4, 4, 4, 5, 6]
  52. >>> mu = mean(data)
  53. >>> pvariance(data, mu)
  54. 2.5
  55. Exceptions
  56. ----------
  57. A single exception is defined: StatisticsError is a subclass of ValueError.
  58. """
  59. __all__ = [
  60. 'NormalDist',
  61. 'StatisticsError',
  62. 'fmean',
  63. 'geometric_mean',
  64. 'harmonic_mean',
  65. 'mean',
  66. 'median',
  67. 'median_grouped',
  68. 'median_high',
  69. 'median_low',
  70. 'mode',
  71. 'multimode',
  72. 'pstdev',
  73. 'pvariance',
  74. 'quantiles',
  75. 'stdev',
  76. 'variance',
  77. ]
  78. import math
  79. import numbers
  80. import random
  81. from fractions import Fraction
  82. from decimal import Decimal
  83. from itertools import groupby
  84. from bisect import bisect_left, bisect_right
  85. from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum
  86. from operator import itemgetter
  87. from collections import Counter
  88. # === Exceptions ===
  89. class StatisticsError(ValueError):
  90. pass
  91. # === Private utilities ===
  92. def _sum(data, start=0):
  93. """_sum(data [, start]) -> (type, sum, count)
  94. Return a high-precision sum of the given numeric data as a fraction,
  95. together with the type to be converted to and the count of items.
  96. If optional argument ``start`` is given, it is added to the total.
  97. If ``data`` is empty, ``start`` (defaulting to 0) is returned.
  98. Examples
  99. --------
  100. >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
  101. (<class 'float'>, Fraction(11, 1), 5)
  102. Some sources of round-off error will be avoided:
  103. # Built-in sum returns zero.
  104. >>> _sum([1e50, 1, -1e50] * 1000)
  105. (<class 'float'>, Fraction(1000, 1), 3000)
  106. Fractions and Decimals are also supported:
  107. >>> from fractions import Fraction as F
  108. >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
  109. (<class 'fractions.Fraction'>, Fraction(63, 20), 4)
  110. >>> from decimal import Decimal as D
  111. >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
  112. >>> _sum(data)
  113. (<class 'decimal.Decimal'>, Fraction(6963, 10000), 4)
  114. Mixed types are currently treated as an error, except that int is
  115. allowed.
  116. """
  117. count = 0
  118. n, d = _exact_ratio(start)
  119. partials = {d: n}
  120. partials_get = partials.get
  121. T = _coerce(int, type(start))
  122. for typ, values in groupby(data, type):
  123. T = _coerce(T, typ) # or raise TypeError
  124. for n, d in map(_exact_ratio, values):
  125. count += 1
  126. partials[d] = partials_get(d, 0) + n
  127. if None in partials:
  128. # The sum will be a NAN or INF. We can ignore all the finite
  129. # partials, and just look at this special one.
  130. total = partials[None]
  131. assert not _isfinite(total)
  132. else:
  133. # Sum all the partial sums using builtin sum.
  134. # FIXME is this faster if we sum them in order of the denominator?
  135. total = sum(Fraction(n, d) for d, n in sorted(partials.items()))
  136. return (T, total, count)
  137. def _isfinite(x):
  138. try:
  139. return x.is_finite() # Likely a Decimal.
  140. except AttributeError:
  141. return math.isfinite(x) # Coerces to float first.
  142. def _coerce(T, S):
  143. """Coerce types T and S to a common type, or raise TypeError.
  144. Coercion rules are currently an implementation detail. See the CoerceTest
  145. test class in test_statistics for details.
  146. """
  147. # See http://bugs.python.org/issue24068.
  148. assert T is not bool, "initial type T is bool"
  149. # If the types are the same, no need to coerce anything. Put this
  150. # first, so that the usual case (no coercion needed) happens as soon
  151. # as possible.
  152. if T is S: return T
  153. # Mixed int & other coerce to the other type.
  154. if S is int or S is bool: return T
  155. if T is int: return S
  156. # If one is a (strict) subclass of the other, coerce to the subclass.
  157. if issubclass(S, T): return S
  158. if issubclass(T, S): return T
  159. # Ints coerce to the other type.
  160. if issubclass(T, int): return S
  161. if issubclass(S, int): return T
  162. # Mixed fraction & float coerces to float (or float subclass).
  163. if issubclass(T, Fraction) and issubclass(S, float):
  164. return S
  165. if issubclass(T, float) and issubclass(S, Fraction):
  166. return T
  167. # Any other combination is disallowed.
  168. msg = "don't know how to coerce %s and %s"
  169. raise TypeError(msg % (T.__name__, S.__name__))
  170. def _exact_ratio(x):
  171. """Return Real number x to exact (numerator, denominator) pair.
  172. >>> _exact_ratio(0.25)
  173. (1, 4)
  174. x is expected to be an int, Fraction, Decimal or float.
  175. """
  176. try:
  177. # Optimise the common case of floats. We expect that the most often
  178. # used numeric type will be builtin floats, so try to make this as
  179. # fast as possible.
  180. if type(x) is float or type(x) is Decimal:
  181. return x.as_integer_ratio()
  182. try:
  183. # x may be an int, Fraction, or Integral ABC.
  184. return (x.numerator, x.denominator)
  185. except AttributeError:
  186. try:
  187. # x may be a float or Decimal subclass.
  188. return x.as_integer_ratio()
  189. except AttributeError:
  190. # Just give up?
  191. pass
  192. except (OverflowError, ValueError):
  193. # float NAN or INF.
  194. assert not _isfinite(x)
  195. return (x, None)
  196. msg = "can't convert type '{}' to numerator/denominator"
  197. raise TypeError(msg.format(type(x).__name__))
  198. def _convert(value, T):
  199. """Convert value to given numeric type T."""
  200. if type(value) is T:
  201. # This covers the cases where T is Fraction, or where value is
  202. # a NAN or INF (Decimal or float).
  203. return value
  204. if issubclass(T, int) and value.denominator != 1:
  205. T = float
  206. try:
  207. # FIXME: what do we do if this overflows?
  208. return T(value)
  209. except TypeError:
  210. if issubclass(T, Decimal):
  211. return T(value.numerator) / T(value.denominator)
  212. else:
  213. raise
  214. def _find_lteq(a, x):
  215. 'Locate the leftmost value exactly equal to x'
  216. i = bisect_left(a, x)
  217. if i != len(a) and a[i] == x:
  218. return i
  219. raise ValueError
  220. def _find_rteq(a, l, x):
  221. 'Locate the rightmost value exactly equal to x'
  222. i = bisect_right(a, x, lo=l)
  223. if i != (len(a) + 1) and a[i - 1] == x:
  224. return i - 1
  225. raise ValueError
  226. def _fail_neg(values, errmsg='negative value'):
  227. """Iterate over values, failing if any are less than zero."""
  228. for x in values:
  229. if x < 0:
  230. raise StatisticsError(errmsg)
  231. yield x
  232. # === Measures of central tendency (averages) ===
  233. def mean(data):
  234. """Return the sample arithmetic mean of data.
  235. >>> mean([1, 2, 3, 4, 4])
  236. 2.8
  237. >>> from fractions import Fraction as F
  238. >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
  239. Fraction(13, 21)
  240. >>> from decimal import Decimal as D
  241. >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
  242. Decimal('0.5625')
  243. If ``data`` is empty, StatisticsError will be raised.
  244. """
  245. if iter(data) is data:
  246. data = list(data)
  247. n = len(data)
  248. if n < 1:
  249. raise StatisticsError('mean requires at least one data point')
  250. T, total, count = _sum(data)
  251. assert count == n
  252. return _convert(total / n, T)
  253. def fmean(data):
  254. """Convert data to floats and compute the arithmetic mean.
  255. This runs faster than the mean() function and it always returns a float.
  256. If the input dataset is empty, it raises a StatisticsError.
  257. >>> fmean([3.5, 4.0, 5.25])
  258. 4.25
  259. """
  260. try:
  261. n = len(data)
  262. except TypeError:
  263. # Handle iterators that do not define __len__().
  264. n = 0
  265. def count(iterable):
  266. nonlocal n
  267. for n, x in enumerate(iterable, start=1):
  268. yield x
  269. total = fsum(count(data))
  270. else:
  271. total = fsum(data)
  272. try:
  273. return total / n
  274. except ZeroDivisionError:
  275. raise StatisticsError('fmean requires at least one data point') from None
  276. def geometric_mean(data):
  277. """Convert data to floats and compute the geometric mean.
  278. Raises a StatisticsError if the input dataset is empty,
  279. if it contains a zero, or if it contains a negative value.
  280. No special efforts are made to achieve exact results.
  281. (However, this may change in the future.)
  282. >>> round(geometric_mean([54, 24, 36]), 9)
  283. 36.0
  284. """
  285. try:
  286. return exp(fmean(map(log, data)))
  287. except ValueError:
  288. raise StatisticsError('geometric mean requires a non-empty dataset '
  289. 'containing positive numbers') from None
  290. def harmonic_mean(data):
  291. """Return the harmonic mean of data.
  292. The harmonic mean, sometimes called the subcontrary mean, is the
  293. reciprocal of the arithmetic mean of the reciprocals of the data,
  294. and is often appropriate when averaging quantities which are rates
  295. or ratios, for example speeds. Example:
  296. Suppose an investor purchases an equal value of shares in each of
  297. three companies, with P/E (price/earning) ratios of 2.5, 3 and 10.
  298. What is the average P/E ratio for the investor's portfolio?
  299. >>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
  300. 3.6
  301. Using the arithmetic mean would give an average of about 5.167, which
  302. is too high.
  303. If ``data`` is empty, or any element is less than zero,
  304. ``harmonic_mean`` will raise ``StatisticsError``.
  305. """
  306. # For a justification for using harmonic mean for P/E ratios, see
  307. # http://fixthepitch.pellucid.com/comps-analysis-the-missing-harmony-of-summary-statistics/
  308. # http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2621087
  309. if iter(data) is data:
  310. data = list(data)
  311. errmsg = 'harmonic mean does not support negative values'
  312. n = len(data)
  313. if n < 1:
  314. raise StatisticsError('harmonic_mean requires at least one data point')
  315. elif n == 1:
  316. x = data[0]
  317. if isinstance(x, (numbers.Real, Decimal)):
  318. if x < 0:
  319. raise StatisticsError(errmsg)
  320. return x
  321. else:
  322. raise TypeError('unsupported type')
  323. try:
  324. T, total, count = _sum(1 / x for x in _fail_neg(data, errmsg))
  325. except ZeroDivisionError:
  326. return 0
  327. assert count == n
  328. return _convert(n / total, T)
  329. # FIXME: investigate ways to calculate medians without sorting? Quickselect?
  330. def median(data):
  331. """Return the median (middle value) of numeric data.
  332. When the number of data points is odd, return the middle data point.
  333. When the number of data points is even, the median is interpolated by
  334. taking the average of the two middle values:
  335. >>> median([1, 3, 5])
  336. 3
  337. >>> median([1, 3, 5, 7])
  338. 4.0
  339. """
  340. data = sorted(data)
  341. n = len(data)
  342. if n == 0:
  343. raise StatisticsError("no median for empty data")
  344. if n % 2 == 1:
  345. return data[n // 2]
  346. else:
  347. i = n // 2
  348. return (data[i - 1] + data[i]) / 2
  349. def median_low(data):
  350. """Return the low median of numeric data.
  351. When the number of data points is odd, the middle value is returned.
  352. When it is even, the smaller of the two middle values is returned.
  353. >>> median_low([1, 3, 5])
  354. 3
  355. >>> median_low([1, 3, 5, 7])
  356. 3
  357. """
  358. data = sorted(data)
  359. n = len(data)
  360. if n == 0:
  361. raise StatisticsError("no median for empty data")
  362. if n % 2 == 1:
  363. return data[n // 2]
  364. else:
  365. return data[n // 2 - 1]
  366. def median_high(data):
  367. """Return the high median of data.
  368. When the number of data points is odd, the middle value is returned.
  369. When it is even, the larger of the two middle values is returned.
  370. >>> median_high([1, 3, 5])
  371. 3
  372. >>> median_high([1, 3, 5, 7])
  373. 5
  374. """
  375. data = sorted(data)
  376. n = len(data)
  377. if n == 0:
  378. raise StatisticsError("no median for empty data")
  379. return data[n // 2]
  380. def median_grouped(data, interval=1):
  381. """Return the 50th percentile (median) of grouped continuous data.
  382. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
  383. 3.7
  384. >>> median_grouped([52, 52, 53, 54])
  385. 52.5
  386. This calculates the median as the 50th percentile, and should be
  387. used when your data is continuous and grouped. In the above example,
  388. the values 1, 2, 3, etc. actually represent the midpoint of classes
  389. 0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in
  390. class 3.5-4.5, and interpolation is used to estimate it.
  391. Optional argument ``interval`` represents the class interval, and
  392. defaults to 1. Changing the class interval naturally will change the
  393. interpolated 50th percentile value:
  394. >>> median_grouped([1, 3, 3, 5, 7], interval=1)
  395. 3.25
  396. >>> median_grouped([1, 3, 3, 5, 7], interval=2)
  397. 3.5
  398. This function does not check whether the data points are at least
  399. ``interval`` apart.
  400. """
  401. data = sorted(data)
  402. n = len(data)
  403. if n == 0:
  404. raise StatisticsError("no median for empty data")
  405. elif n == 1:
  406. return data[0]
  407. # Find the value at the midpoint. Remember this corresponds to the
  408. # centre of the class interval.
  409. x = data[n // 2]
  410. for obj in (x, interval):
  411. if isinstance(obj, (str, bytes)):
  412. raise TypeError('expected number but got %r' % obj)
  413. try:
  414. L = x - interval / 2 # The lower limit of the median interval.
  415. except TypeError:
  416. # Mixed type. For now we just coerce to float.
  417. L = float(x) - float(interval) / 2
  418. # Uses bisection search to search for x in data with log(n) time complexity
  419. # Find the position of leftmost occurrence of x in data
  420. l1 = _find_lteq(data, x)
  421. # Find the position of rightmost occurrence of x in data[l1...len(data)]
  422. # Assuming always l1 <= l2
  423. l2 = _find_rteq(data, l1, x)
  424. cf = l1
  425. f = l2 - l1 + 1
  426. return L + interval * (n / 2 - cf) / f
  427. def mode(data):
  428. """Return the most common data point from discrete or nominal data.
  429. ``mode`` assumes discrete data, and returns a single value. This is the
  430. standard treatment of the mode as commonly taught in schools:
  431. >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
  432. 3
  433. This also works with nominal (non-numeric) data:
  434. >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
  435. 'red'
  436. If there are multiple modes with same frequency, return the first one
  437. encountered:
  438. >>> mode(['red', 'red', 'green', 'blue', 'blue'])
  439. 'red'
  440. If *data* is empty, ``mode``, raises StatisticsError.
  441. """
  442. pairs = Counter(iter(data)).most_common(1)
  443. try:
  444. return pairs[0][0]
  445. except IndexError:
  446. raise StatisticsError('no mode for empty data') from None
  447. def multimode(data):
  448. """Return a list of the most frequently occurring values.
  449. Will return more than one result if there are multiple modes
  450. or an empty list if *data* is empty.
  451. >>> multimode('aabbbbbbbbcc')
  452. ['b']
  453. >>> multimode('aabbbbccddddeeffffgg')
  454. ['b', 'd', 'f']
  455. >>> multimode('')
  456. []
  457. """
  458. counts = Counter(iter(data)).most_common()
  459. maxcount, mode_items = next(groupby(counts, key=itemgetter(1)), (0, []))
  460. return list(map(itemgetter(0), mode_items))
  461. # Notes on methods for computing quantiles
  462. # ----------------------------------------
  463. #
  464. # There is no one perfect way to compute quantiles. Here we offer
  465. # two methods that serve common needs. Most other packages
  466. # surveyed offered at least one or both of these two, making them
  467. # "standard" in the sense of "widely-adopted and reproducible".
  468. # They are also easy to explain, easy to compute manually, and have
  469. # straight-forward interpretations that aren't surprising.
  470. # The default method is known as "R6", "PERCENTILE.EXC", or "expected
  471. # value of rank order statistics". The alternative method is known as
  472. # "R7", "PERCENTILE.INC", or "mode of rank order statistics".
  473. # For sample data where there is a positive probability for values
  474. # beyond the range of the data, the R6 exclusive method is a
  475. # reasonable choice. Consider a random sample of nine values from a
  476. # population with a uniform distribution from 0.0 to 1.0. The
  477. # distribution of the third ranked sample point is described by
  478. # betavariate(alpha=3, beta=7) which has mode=0.250, median=0.286, and
  479. # mean=0.300. Only the latter (which corresponds with R6) gives the
  480. # desired cut point with 30% of the population falling below that
  481. # value, making it comparable to a result from an inv_cdf() function.
  482. # The R6 exclusive method is also idempotent.
  483. # For describing population data where the end points are known to
  484. # be included in the data, the R7 inclusive method is a reasonable
  485. # choice. Instead of the mean, it uses the mode of the beta
  486. # distribution for the interior points. Per Hyndman & Fan, "One nice
  487. # property is that the vertices of Q7(p) divide the range into n - 1
  488. # intervals, and exactly 100p% of the intervals lie to the left of
  489. # Q7(p) and 100(1 - p)% of the intervals lie to the right of Q7(p)."
  490. # If needed, other methods could be added. However, for now, the
  491. # position is that fewer options make for easier choices and that
  492. # external packages can be used for anything more advanced.
  493. def quantiles(data, *, n=4, method='exclusive'):
  494. """Divide *data* into *n* continuous intervals with equal probability.
  495. Returns a list of (n - 1) cut points separating the intervals.
  496. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles.
  497. Set *n* to 100 for percentiles which gives the 99 cuts points that
  498. separate *data* in to 100 equal sized groups.
  499. The *data* can be any iterable containing sample.
  500. The cut points are linearly interpolated between data points.
  501. If *method* is set to *inclusive*, *data* is treated as population
  502. data. The minimum value is treated as the 0th percentile and the
  503. maximum value is treated as the 100th percentile.
  504. """
  505. if n < 1:
  506. raise StatisticsError('n must be at least 1')
  507. data = sorted(data)
  508. ld = len(data)
  509. if ld < 2:
  510. raise StatisticsError('must have at least two data points')
  511. if method == 'inclusive':
  512. m = ld - 1
  513. result = []
  514. for i in range(1, n):
  515. j, delta = divmod(i * m, n)
  516. interpolated = (data[j] * (n - delta) + data[j + 1] * delta) / n
  517. result.append(interpolated)
  518. return result
  519. if method == 'exclusive':
  520. m = ld + 1
  521. result = []
  522. for i in range(1, n):
  523. j = i * m // n # rescale i to m/n
  524. j = 1 if j < 1 else ld-1 if j > ld-1 else j # clamp to 1 .. ld-1
  525. delta = i*m - j*n # exact integer math
  526. interpolated = (data[j - 1] * (n - delta) + data[j] * delta) / n
  527. result.append(interpolated)
  528. return result
  529. raise ValueError(f'Unknown method: {method!r}')
  530. # === Measures of spread ===
  531. # See http://mathworld.wolfram.com/Variance.html
  532. # http://mathworld.wolfram.com/SampleVariance.html
  533. # http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  534. #
  535. # Under no circumstances use the so-called "computational formula for
  536. # variance", as that is only suitable for hand calculations with a small
  537. # amount of low-precision data. It has terrible numeric properties.
  538. #
  539. # See a comparison of three computational methods here:
  540. # http://www.johndcook.com/blog/2008/09/26/comparing-three-methods-of-computing-standard-deviation/
  541. def _ss(data, c=None):
  542. """Return sum of square deviations of sequence data.
  543. If ``c`` is None, the mean is calculated in one pass, and the deviations
  544. from the mean are calculated in a second pass. Otherwise, deviations are
  545. calculated from ``c`` as given. Use the second case with care, as it can
  546. lead to garbage results.
  547. """
  548. if c is not None:
  549. T, total, count = _sum((x-c)**2 for x in data)
  550. return (T, total)
  551. c = mean(data)
  552. T, total, count = _sum((x-c)**2 for x in data)
  553. # The following sum should mathematically equal zero, but due to rounding
  554. # error may not.
  555. U, total2, count2 = _sum((x - c) for x in data)
  556. assert T == U and count == count2
  557. total -= total2 ** 2 / len(data)
  558. assert not total < 0, 'negative sum of square deviations: %f' % total
  559. return (T, total)
  560. def variance(data, xbar=None):
  561. """Return the sample variance of data.
  562. data should be an iterable of Real-valued numbers, with at least two
  563. values. The optional argument xbar, if given, should be the mean of
  564. the data. If it is missing or None, the mean is automatically calculated.
  565. Use this function when your data is a sample from a population. To
  566. calculate the variance from the entire population, see ``pvariance``.
  567. Examples:
  568. >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
  569. >>> variance(data)
  570. 1.3720238095238095
  571. If you have already calculated the mean of your data, you can pass it as
  572. the optional second argument ``xbar`` to avoid recalculating it:
  573. >>> m = mean(data)
  574. >>> variance(data, m)
  575. 1.3720238095238095
  576. This function does not check that ``xbar`` is actually the mean of
  577. ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
  578. impossible results.
  579. Decimals and Fractions are supported:
  580. >>> from decimal import Decimal as D
  581. >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  582. Decimal('31.01875')
  583. >>> from fractions import Fraction as F
  584. >>> variance([F(1, 6), F(1, 2), F(5, 3)])
  585. Fraction(67, 108)
  586. """
  587. if iter(data) is data:
  588. data = list(data)
  589. n = len(data)
  590. if n < 2:
  591. raise StatisticsError('variance requires at least two data points')
  592. T, ss = _ss(data, xbar)
  593. return _convert(ss / (n - 1), T)
  594. def pvariance(data, mu=None):
  595. """Return the population variance of ``data``.
  596. data should be a sequence or iterable of Real-valued numbers, with at least one
  597. value. The optional argument mu, if given, should be the mean of
  598. the data. If it is missing or None, the mean is automatically calculated.
  599. Use this function to calculate the variance from the entire population.
  600. To estimate the variance from a sample, the ``variance`` function is
  601. usually a better choice.
  602. Examples:
  603. >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
  604. >>> pvariance(data)
  605. 1.25
  606. If you have already calculated the mean of the data, you can pass it as
  607. the optional second argument to avoid recalculating it:
  608. >>> mu = mean(data)
  609. >>> pvariance(data, mu)
  610. 1.25
  611. Decimals and Fractions are supported:
  612. >>> from decimal import Decimal as D
  613. >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  614. Decimal('24.815')
  615. >>> from fractions import Fraction as F
  616. >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
  617. Fraction(13, 72)
  618. """
  619. if iter(data) is data:
  620. data = list(data)
  621. n = len(data)
  622. if n < 1:
  623. raise StatisticsError('pvariance requires at least one data point')
  624. T, ss = _ss(data, mu)
  625. return _convert(ss / n, T)
  626. def stdev(data, xbar=None):
  627. """Return the square root of the sample variance.
  628. See ``variance`` for arguments and other details.
  629. >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  630. 1.0810874155219827
  631. """
  632. var = variance(data, xbar)
  633. try:
  634. return var.sqrt()
  635. except AttributeError:
  636. return math.sqrt(var)
  637. def pstdev(data, mu=None):
  638. """Return the square root of the population variance.
  639. See ``pvariance`` for arguments and other details.
  640. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  641. 0.986893273527251
  642. """
  643. var = pvariance(data, mu)
  644. try:
  645. return var.sqrt()
  646. except AttributeError:
  647. return math.sqrt(var)
  648. ## Normal Distribution #####################################################
  649. def _normal_dist_inv_cdf(p, mu, sigma):
  650. # There is no closed-form solution to the inverse CDF for the normal
  651. # distribution, so we use a rational approximation instead:
  652. # Wichura, M.J. (1988). "Algorithm AS241: The Percentage Points of the
  653. # Normal Distribution". Applied Statistics. Blackwell Publishing. 37
  654. # (3): 477–484. doi:10.2307/2347330. JSTOR 2347330.
  655. q = p - 0.5
  656. if fabs(q) <= 0.425:
  657. r = 0.180625 - q * q
  658. # Hash sum: 55.88319_28806_14901_4439
  659. num = (((((((2.50908_09287_30122_6727e+3 * r +
  660. 3.34305_75583_58812_8105e+4) * r +
  661. 6.72657_70927_00870_0853e+4) * r +
  662. 4.59219_53931_54987_1457e+4) * r +
  663. 1.37316_93765_50946_1125e+4) * r +
  664. 1.97159_09503_06551_4427e+3) * r +
  665. 1.33141_66789_17843_7745e+2) * r +
  666. 3.38713_28727_96366_6080e+0) * q
  667. den = (((((((5.22649_52788_52854_5610e+3 * r +
  668. 2.87290_85735_72194_2674e+4) * r +
  669. 3.93078_95800_09271_0610e+4) * r +
  670. 2.12137_94301_58659_5867e+4) * r +
  671. 5.39419_60214_24751_1077e+3) * r +
  672. 6.87187_00749_20579_0830e+2) * r +
  673. 4.23133_30701_60091_1252e+1) * r +
  674. 1.0)
  675. x = num / den
  676. return mu + (x * sigma)
  677. r = p if q <= 0.0 else 1.0 - p
  678. r = sqrt(-log(r))
  679. if r <= 5.0:
  680. r = r - 1.6
  681. # Hash sum: 49.33206_50330_16102_89036
  682. num = (((((((7.74545_01427_83414_07640e-4 * r +
  683. 2.27238_44989_26918_45833e-2) * r +
  684. 2.41780_72517_74506_11770e-1) * r +
  685. 1.27045_82524_52368_38258e+0) * r +
  686. 3.64784_83247_63204_60504e+0) * r +
  687. 5.76949_72214_60691_40550e+0) * r +
  688. 4.63033_78461_56545_29590e+0) * r +
  689. 1.42343_71107_49683_57734e+0)
  690. den = (((((((1.05075_00716_44416_84324e-9 * r +
  691. 5.47593_80849_95344_94600e-4) * r +
  692. 1.51986_66563_61645_71966e-2) * r +
  693. 1.48103_97642_74800_74590e-1) * r +
  694. 6.89767_33498_51000_04550e-1) * r +
  695. 1.67638_48301_83803_84940e+0) * r +
  696. 2.05319_16266_37758_82187e+0) * r +
  697. 1.0)
  698. else:
  699. r = r - 5.0
  700. # Hash sum: 47.52583_31754_92896_71629
  701. num = (((((((2.01033_43992_92288_13265e-7 * r +
  702. 2.71155_55687_43487_57815e-5) * r +
  703. 1.24266_09473_88078_43860e-3) * r +
  704. 2.65321_89526_57612_30930e-2) * r +
  705. 2.96560_57182_85048_91230e-1) * r +
  706. 1.78482_65399_17291_33580e+0) * r +
  707. 5.46378_49111_64114_36990e+0) * r +
  708. 6.65790_46435_01103_77720e+0)
  709. den = (((((((2.04426_31033_89939_78564e-15 * r +
  710. 1.42151_17583_16445_88870e-7) * r +
  711. 1.84631_83175_10054_68180e-5) * r +
  712. 7.86869_13114_56132_59100e-4) * r +
  713. 1.48753_61290_85061_48525e-2) * r +
  714. 1.36929_88092_27358_05310e-1) * r +
  715. 5.99832_20655_58879_37690e-1) * r +
  716. 1.0)
  717. x = num / den
  718. if q < 0.0:
  719. x = -x
  720. return mu + (x * sigma)
  721. # If available, use C implementation
  722. try:
  723. from _statistics import _normal_dist_inv_cdf
  724. except ImportError:
  725. pass
  726. class NormalDist:
  727. "Normal distribution of a random variable"
  728. # https://en.wikipedia.org/wiki/Normal_distribution
  729. # https://en.wikipedia.org/wiki/Variance#Properties
  730. __slots__ = {
  731. '_mu': 'Arithmetic mean of a normal distribution',
  732. '_sigma': 'Standard deviation of a normal distribution',
  733. }
  734. def __init__(self, mu=0.0, sigma=1.0):
  735. "NormalDist where mu is the mean and sigma is the standard deviation."
  736. if sigma < 0.0:
  737. raise StatisticsError('sigma must be non-negative')
  738. self._mu = float(mu)
  739. self._sigma = float(sigma)
  740. @classmethod
  741. def from_samples(cls, data):
  742. "Make a normal distribution instance from sample data."
  743. if not isinstance(data, (list, tuple)):
  744. data = list(data)
  745. xbar = fmean(data)
  746. return cls(xbar, stdev(data, xbar))
  747. def samples(self, n, *, seed=None):
  748. "Generate *n* samples for a given mean and standard deviation."
  749. gauss = random.gauss if seed is None else random.Random(seed).gauss
  750. mu, sigma = self._mu, self._sigma
  751. return [gauss(mu, sigma) for i in range(n)]
  752. def pdf(self, x):
  753. "Probability density function. P(x <= X < x+dx) / dx"
  754. variance = self._sigma ** 2.0
  755. if not variance:
  756. raise StatisticsError('pdf() not defined when sigma is zero')
  757. return exp((x - self._mu)**2.0 / (-2.0*variance)) / sqrt(tau*variance)
  758. def cdf(self, x):
  759. "Cumulative distribution function. P(X <= x)"
  760. if not self._sigma:
  761. raise StatisticsError('cdf() not defined when sigma is zero')
  762. return 0.5 * (1.0 + erf((x - self._mu) / (self._sigma * sqrt(2.0))))
  763. def inv_cdf(self, p):
  764. """Inverse cumulative distribution function. x : P(X <= x) = p
  765. Finds the value of the random variable such that the probability of
  766. the variable being less than or equal to that value equals the given
  767. probability.
  768. This function is also called the percent point function or quantile
  769. function.
  770. """
  771. if p <= 0.0 or p >= 1.0:
  772. raise StatisticsError('p must be in the range 0.0 < p < 1.0')
  773. if self._sigma <= 0.0:
  774. raise StatisticsError('cdf() not defined when sigma at or below zero')
  775. return _normal_dist_inv_cdf(p, self._mu, self._sigma)
  776. def quantiles(self, n=4):
  777. """Divide into *n* continuous intervals with equal probability.
  778. Returns a list of (n - 1) cut points separating the intervals.
  779. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles.
  780. Set *n* to 100 for percentiles which gives the 99 cuts points that
  781. separate the normal distribution in to 100 equal sized groups.
  782. """
  783. return [self.inv_cdf(i / n) for i in range(1, n)]
  784. def overlap(self, other):
  785. """Compute the overlapping coefficient (OVL) between two normal distributions.
  786. Measures the agreement between two normal probability distributions.
  787. Returns a value between 0.0 and 1.0 giving the overlapping area in
  788. the two underlying probability density functions.
  789. >>> N1 = NormalDist(2.4, 1.6)
  790. >>> N2 = NormalDist(3.2, 2.0)
  791. >>> N1.overlap(N2)
  792. 0.8035050657330205
  793. """
  794. # See: "The overlapping coefficient as a measure of agreement between
  795. # probability distributions and point estimation of the overlap of two
  796. # normal densities" -- Henry F. Inman and Edwin L. Bradley Jr
  797. # http://dx.doi.org/10.1080/03610928908830127
  798. if not isinstance(other, NormalDist):
  799. raise TypeError('Expected another NormalDist instance')
  800. X, Y = self, other
  801. if (Y._sigma, Y._mu) < (X._sigma, X._mu): # sort to assure commutativity
  802. X, Y = Y, X
  803. X_var, Y_var = X.variance, Y.variance
  804. if not X_var or not Y_var:
  805. raise StatisticsError('overlap() not defined when sigma is zero')
  806. dv = Y_var - X_var
  807. dm = fabs(Y._mu - X._mu)
  808. if not dv:
  809. return 1.0 - erf(dm / (2.0 * X._sigma * sqrt(2.0)))
  810. a = X._mu * Y_var - Y._mu * X_var
  811. b = X._sigma * Y._sigma * sqrt(dm**2.0 + dv * log(Y_var / X_var))
  812. x1 = (a + b) / dv
  813. x2 = (a - b) / dv
  814. return 1.0 - (fabs(Y.cdf(x1) - X.cdf(x1)) + fabs(Y.cdf(x2) - X.cdf(x2)))
  815. def zscore(self, x):
  816. """Compute the Standard Score. (x - mean) / stdev
  817. Describes *x* in terms of the number of standard deviations
  818. above or below the mean of the normal distribution.
  819. """
  820. # https://www.statisticshowto.com/probability-and-statistics/z-score/
  821. if not self._sigma:
  822. raise StatisticsError('zscore() not defined when sigma is zero')
  823. return (x - self._mu) / self._sigma
  824. @property
  825. def mean(self):
  826. "Arithmetic mean of the normal distribution."
  827. return self._mu
  828. @property
  829. def median(self):
  830. "Return the median of the normal distribution"
  831. return self._mu
  832. @property
  833. def mode(self):
  834. """Return the mode of the normal distribution
  835. The mode is the value x where which the probability density
  836. function (pdf) takes its maximum value.
  837. """
  838. return self._mu
  839. @property
  840. def stdev(self):
  841. "Standard deviation of the normal distribution."
  842. return self._sigma
  843. @property
  844. def variance(self):
  845. "Square of the standard deviation."
  846. return self._sigma ** 2.0
  847. def __add__(x1, x2):
  848. """Add a constant or another NormalDist instance.
  849. If *other* is a constant, translate mu by the constant,
  850. leaving sigma unchanged.
  851. If *other* is a NormalDist, add both the means and the variances.
  852. Mathematically, this works only if the two distributions are
  853. independent or if they are jointly normally distributed.
  854. """
  855. if isinstance(x2, NormalDist):
  856. return NormalDist(x1._mu + x2._mu, hypot(x1._sigma, x2._sigma))
  857. return NormalDist(x1._mu + x2, x1._sigma)
  858. def __sub__(x1, x2):
  859. """Subtract a constant or another NormalDist instance.
  860. If *other* is a constant, translate by the constant mu,
  861. leaving sigma unchanged.
  862. If *other* is a NormalDist, subtract the means and add the variances.
  863. Mathematically, this works only if the two distributions are
  864. independent or if they are jointly normally distributed.
  865. """
  866. if isinstance(x2, NormalDist):
  867. return NormalDist(x1._mu - x2._mu, hypot(x1._sigma, x2._sigma))
  868. return NormalDist(x1._mu - x2, x1._sigma)
  869. def __mul__(x1, x2):
  870. """Multiply both mu and sigma by a constant.
  871. Used for rescaling, perhaps to change measurement units.
  872. Sigma is scaled with the absolute value of the constant.
  873. """
  874. return NormalDist(x1._mu * x2, x1._sigma * fabs(x2))
  875. def __truediv__(x1, x2):
  876. """Divide both mu and sigma by a constant.
  877. Used for rescaling, perhaps to change measurement units.
  878. Sigma is scaled with the absolute value of the constant.
  879. """
  880. return NormalDist(x1._mu / x2, x1._sigma / fabs(x2))
  881. def __pos__(x1):
  882. "Return a copy of the instance."
  883. return NormalDist(x1._mu, x1._sigma)
  884. def __neg__(x1):
  885. "Negates mu while keeping sigma the same."
  886. return NormalDist(-x1._mu, x1._sigma)
  887. __radd__ = __add__
  888. def __rsub__(x1, x2):
  889. "Subtract a NormalDist from a constant or another NormalDist."
  890. return -(x1 - x2)
  891. __rmul__ = __mul__
  892. def __eq__(x1, x2):
  893. "Two NormalDist objects are equal if their mu and sigma are both equal."
  894. if not isinstance(x2, NormalDist):
  895. return NotImplemented
  896. return x1._mu == x2._mu and x1._sigma == x2._sigma
  897. def __hash__(self):
  898. "NormalDist objects hash equal if their mu and sigma are both equal."
  899. return hash((self._mu, self._sigma))
  900. def __repr__(self):
  901. return f'{type(self).__name__}(mu={self._mu!r}, sigma={self._sigma!r})'