statistics.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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. data = iter(data)
  443. pairs = Counter(data).most_common(1)
  444. try:
  445. return pairs[0][0]
  446. except IndexError:
  447. raise StatisticsError('no mode for empty data') from None
  448. def multimode(data):
  449. """Return a list of the most frequently occurring values.
  450. Will return more than one result if there are multiple modes
  451. or an empty list if *data* is empty.
  452. >>> multimode('aabbbbbbbbcc')
  453. ['b']
  454. >>> multimode('aabbbbccddddeeffffgg')
  455. ['b', 'd', 'f']
  456. >>> multimode('')
  457. []
  458. """
  459. counts = Counter(iter(data)).most_common()
  460. maxcount, mode_items = next(groupby(counts, key=itemgetter(1)), (0, []))
  461. return list(map(itemgetter(0), mode_items))
  462. # Notes on methods for computing quantiles
  463. # ----------------------------------------
  464. #
  465. # There is no one perfect way to compute quantiles. Here we offer
  466. # two methods that serve common needs. Most other packages
  467. # surveyed offered at least one or both of these two, making them
  468. # "standard" in the sense of "widely-adopted and reproducible".
  469. # They are also easy to explain, easy to compute manually, and have
  470. # straight-forward interpretations that aren't surprising.
  471. # The default method is known as "R6", "PERCENTILE.EXC", or "expected
  472. # value of rank order statistics". The alternative method is known as
  473. # "R7", "PERCENTILE.INC", or "mode of rank order statistics".
  474. # For sample data where there is a positive probability for values
  475. # beyond the range of the data, the R6 exclusive method is a
  476. # reasonable choice. Consider a random sample of nine values from a
  477. # population with a uniform distribution from 0.0 to 100.0. The
  478. # distribution of the third ranked sample point is described by
  479. # betavariate(alpha=3, beta=7) which has mode=0.250, median=0.286, and
  480. # mean=0.300. Only the latter (which corresponds with R6) gives the
  481. # desired cut point with 30% of the population falling below that
  482. # value, making it comparable to a result from an inv_cdf() function.
  483. # The R6 exclusive method is also idempotent.
  484. # For describing population data where the end points are known to
  485. # be included in the data, the R7 inclusive method is a reasonable
  486. # choice. Instead of the mean, it uses the mode of the beta
  487. # distribution for the interior points. Per Hyndman & Fan, "One nice
  488. # property is that the vertices of Q7(p) divide the range into n - 1
  489. # intervals, and exactly 100p% of the intervals lie to the left of
  490. # Q7(p) and 100(1 - p)% of the intervals lie to the right of Q7(p)."
  491. # If needed, other methods could be added. However, for now, the
  492. # position is that fewer options make for easier choices and that
  493. # external packages can be used for anything more advanced.
  494. def quantiles(data, *, n=4, method='exclusive'):
  495. """Divide *data* into *n* continuous intervals with equal probability.
  496. Returns a list of (n - 1) cut points separating the intervals.
  497. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles.
  498. Set *n* to 100 for percentiles which gives the 99 cuts points that
  499. separate *data* in to 100 equal sized groups.
  500. The *data* can be any iterable containing sample.
  501. The cut points are linearly interpolated between data points.
  502. If *method* is set to *inclusive*, *data* is treated as population
  503. data. The minimum value is treated as the 0th percentile and the
  504. maximum value is treated as the 100th percentile.
  505. """
  506. if n < 1:
  507. raise StatisticsError('n must be at least 1')
  508. data = sorted(data)
  509. ld = len(data)
  510. if ld < 2:
  511. raise StatisticsError('must have at least two data points')
  512. if method == 'inclusive':
  513. m = ld - 1
  514. result = []
  515. for i in range(1, n):
  516. j = i * m // n
  517. delta = i*m - j*n
  518. interpolated = (data[j] * (n - delta) + data[j+1] * delta) / n
  519. result.append(interpolated)
  520. return result
  521. if method == 'exclusive':
  522. m = ld + 1
  523. result = []
  524. for i in range(1, n):
  525. j = i * m // n # rescale i to m/n
  526. j = 1 if j < 1 else ld-1 if j > ld-1 else j # clamp to 1 .. ld-1
  527. delta = i*m - j*n # exact integer math
  528. interpolated = (data[j-1] * (n - delta) + data[j] * delta) / n
  529. result.append(interpolated)
  530. return result
  531. raise ValueError(f'Unknown method: {method!r}')
  532. # === Measures of spread ===
  533. # See http://mathworld.wolfram.com/Variance.html
  534. # http://mathworld.wolfram.com/SampleVariance.html
  535. # http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  536. #
  537. # Under no circumstances use the so-called "computational formula for
  538. # variance", as that is only suitable for hand calculations with a small
  539. # amount of low-precision data. It has terrible numeric properties.
  540. #
  541. # See a comparison of three computational methods here:
  542. # http://www.johndcook.com/blog/2008/09/26/comparing-three-methods-of-computing-standard-deviation/
  543. def _ss(data, c=None):
  544. """Return sum of square deviations of sequence data.
  545. If ``c`` is None, the mean is calculated in one pass, and the deviations
  546. from the mean are calculated in a second pass. Otherwise, deviations are
  547. calculated from ``c`` as given. Use the second case with care, as it can
  548. lead to garbage results.
  549. """
  550. if c is not None:
  551. T, total, count = _sum((x-c)**2 for x in data)
  552. return (T, total)
  553. c = mean(data)
  554. T, total, count = _sum((x-c)**2 for x in data)
  555. # The following sum should mathematically equal zero, but due to rounding
  556. # error may not.
  557. U, total2, count2 = _sum((x-c) for x in data)
  558. assert T == U and count == count2
  559. total -= total2**2/len(data)
  560. assert not total < 0, 'negative sum of square deviations: %f' % total
  561. return (T, total)
  562. def variance(data, xbar=None):
  563. """Return the sample variance of data.
  564. data should be an iterable of Real-valued numbers, with at least two
  565. values. The optional argument xbar, if given, should be the mean of
  566. the data. If it is missing or None, the mean is automatically calculated.
  567. Use this function when your data is a sample from a population. To
  568. calculate the variance from the entire population, see ``pvariance``.
  569. Examples:
  570. >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
  571. >>> variance(data)
  572. 1.3720238095238095
  573. If you have already calculated the mean of your data, you can pass it as
  574. the optional second argument ``xbar`` to avoid recalculating it:
  575. >>> m = mean(data)
  576. >>> variance(data, m)
  577. 1.3720238095238095
  578. This function does not check that ``xbar`` is actually the mean of
  579. ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
  580. impossible results.
  581. Decimals and Fractions are supported:
  582. >>> from decimal import Decimal as D
  583. >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  584. Decimal('31.01875')
  585. >>> from fractions import Fraction as F
  586. >>> variance([F(1, 6), F(1, 2), F(5, 3)])
  587. Fraction(67, 108)
  588. """
  589. if iter(data) is data:
  590. data = list(data)
  591. n = len(data)
  592. if n < 2:
  593. raise StatisticsError('variance requires at least two data points')
  594. T, ss = _ss(data, xbar)
  595. return _convert(ss/(n-1), T)
  596. def pvariance(data, mu=None):
  597. """Return the population variance of ``data``.
  598. data should be a sequence or iterable of Real-valued numbers, with at least one
  599. value. The optional argument mu, if given, should be the mean of
  600. the data. If it is missing or None, the mean is automatically calculated.
  601. Use this function to calculate the variance from the entire population.
  602. To estimate the variance from a sample, the ``variance`` function is
  603. usually a better choice.
  604. Examples:
  605. >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
  606. >>> pvariance(data)
  607. 1.25
  608. If you have already calculated the mean of the data, you can pass it as
  609. the optional second argument to avoid recalculating it:
  610. >>> mu = mean(data)
  611. >>> pvariance(data, mu)
  612. 1.25
  613. Decimals and Fractions are supported:
  614. >>> from decimal import Decimal as D
  615. >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  616. Decimal('24.815')
  617. >>> from fractions import Fraction as F
  618. >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
  619. Fraction(13, 72)
  620. """
  621. if iter(data) is data:
  622. data = list(data)
  623. n = len(data)
  624. if n < 1:
  625. raise StatisticsError('pvariance requires at least one data point')
  626. T, ss = _ss(data, mu)
  627. return _convert(ss/n, T)
  628. def stdev(data, xbar=None):
  629. """Return the square root of the sample variance.
  630. See ``variance`` for arguments and other details.
  631. >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  632. 1.0810874155219827
  633. """
  634. var = variance(data, xbar)
  635. try:
  636. return var.sqrt()
  637. except AttributeError:
  638. return math.sqrt(var)
  639. def pstdev(data, mu=None):
  640. """Return the square root of the population variance.
  641. See ``pvariance`` for arguments and other details.
  642. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  643. 0.986893273527251
  644. """
  645. var = pvariance(data, mu)
  646. try:
  647. return var.sqrt()
  648. except AttributeError:
  649. return math.sqrt(var)
  650. ## Normal Distribution #####################################################
  651. def _normal_dist_inv_cdf(p, mu, sigma):
  652. # There is no closed-form solution to the inverse CDF for the normal
  653. # distribution, so we use a rational approximation instead:
  654. # Wichura, M.J. (1988). "Algorithm AS241: The Percentage Points of the
  655. # Normal Distribution". Applied Statistics. Blackwell Publishing. 37
  656. # (3): 477–484. doi:10.2307/2347330. JSTOR 2347330.
  657. q = p - 0.5
  658. if fabs(q) <= 0.425:
  659. r = 0.180625 - q * q
  660. # Hash sum: 55.88319_28806_14901_4439
  661. num = (((((((2.50908_09287_30122_6727e+3 * r +
  662. 3.34305_75583_58812_8105e+4) * r +
  663. 6.72657_70927_00870_0853e+4) * r +
  664. 4.59219_53931_54987_1457e+4) * r +
  665. 1.37316_93765_50946_1125e+4) * r +
  666. 1.97159_09503_06551_4427e+3) * r +
  667. 1.33141_66789_17843_7745e+2) * r +
  668. 3.38713_28727_96366_6080e+0) * q
  669. den = (((((((5.22649_52788_52854_5610e+3 * r +
  670. 2.87290_85735_72194_2674e+4) * r +
  671. 3.93078_95800_09271_0610e+4) * r +
  672. 2.12137_94301_58659_5867e+4) * r +
  673. 5.39419_60214_24751_1077e+3) * r +
  674. 6.87187_00749_20579_0830e+2) * r +
  675. 4.23133_30701_60091_1252e+1) * r +
  676. 1.0)
  677. x = num / den
  678. return mu + (x * sigma)
  679. r = p if q <= 0.0 else 1.0 - p
  680. r = sqrt(-log(r))
  681. if r <= 5.0:
  682. r = r - 1.6
  683. # Hash sum: 49.33206_50330_16102_89036
  684. num = (((((((7.74545_01427_83414_07640e-4 * r +
  685. 2.27238_44989_26918_45833e-2) * r +
  686. 2.41780_72517_74506_11770e-1) * r +
  687. 1.27045_82524_52368_38258e+0) * r +
  688. 3.64784_83247_63204_60504e+0) * r +
  689. 5.76949_72214_60691_40550e+0) * r +
  690. 4.63033_78461_56545_29590e+0) * r +
  691. 1.42343_71107_49683_57734e+0)
  692. den = (((((((1.05075_00716_44416_84324e-9 * r +
  693. 5.47593_80849_95344_94600e-4) * r +
  694. 1.51986_66563_61645_71966e-2) * r +
  695. 1.48103_97642_74800_74590e-1) * r +
  696. 6.89767_33498_51000_04550e-1) * r +
  697. 1.67638_48301_83803_84940e+0) * r +
  698. 2.05319_16266_37758_82187e+0) * r +
  699. 1.0)
  700. else:
  701. r = r - 5.0
  702. # Hash sum: 47.52583_31754_92896_71629
  703. num = (((((((2.01033_43992_92288_13265e-7 * r +
  704. 2.71155_55687_43487_57815e-5) * r +
  705. 1.24266_09473_88078_43860e-3) * r +
  706. 2.65321_89526_57612_30930e-2) * r +
  707. 2.96560_57182_85048_91230e-1) * r +
  708. 1.78482_65399_17291_33580e+0) * r +
  709. 5.46378_49111_64114_36990e+0) * r +
  710. 6.65790_46435_01103_77720e+0)
  711. den = (((((((2.04426_31033_89939_78564e-15 * r +
  712. 1.42151_17583_16445_88870e-7) * r +
  713. 1.84631_83175_10054_68180e-5) * r +
  714. 7.86869_13114_56132_59100e-4) * r +
  715. 1.48753_61290_85061_48525e-2) * r +
  716. 1.36929_88092_27358_05310e-1) * r +
  717. 5.99832_20655_58879_37690e-1) * r +
  718. 1.0)
  719. x = num / den
  720. if q < 0.0:
  721. x = -x
  722. return mu + (x * sigma)
  723. class NormalDist:
  724. "Normal distribution of a random variable"
  725. # https://en.wikipedia.org/wiki/Normal_distribution
  726. # https://en.wikipedia.org/wiki/Variance#Properties
  727. __slots__ = {
  728. '_mu': 'Arithmetic mean of a normal distribution',
  729. '_sigma': 'Standard deviation of a normal distribution',
  730. }
  731. def __init__(self, mu=0.0, sigma=1.0):
  732. "NormalDist where mu is the mean and sigma is the standard deviation."
  733. if sigma < 0.0:
  734. raise StatisticsError('sigma must be non-negative')
  735. self._mu = float(mu)
  736. self._sigma = float(sigma)
  737. @classmethod
  738. def from_samples(cls, data):
  739. "Make a normal distribution instance from sample data."
  740. if not isinstance(data, (list, tuple)):
  741. data = list(data)
  742. xbar = fmean(data)
  743. return cls(xbar, stdev(data, xbar))
  744. def samples(self, n, *, seed=None):
  745. "Generate *n* samples for a given mean and standard deviation."
  746. gauss = random.gauss if seed is None else random.Random(seed).gauss
  747. mu, sigma = self._mu, self._sigma
  748. return [gauss(mu, sigma) for i in range(n)]
  749. def pdf(self, x):
  750. "Probability density function. P(x <= X < x+dx) / dx"
  751. variance = self._sigma ** 2.0
  752. if not variance:
  753. raise StatisticsError('pdf() not defined when sigma is zero')
  754. return exp((x - self._mu)**2.0 / (-2.0*variance)) / sqrt(tau*variance)
  755. def cdf(self, x):
  756. "Cumulative distribution function. P(X <= x)"
  757. if not self._sigma:
  758. raise StatisticsError('cdf() not defined when sigma is zero')
  759. return 0.5 * (1.0 + erf((x - self._mu) / (self._sigma * sqrt(2.0))))
  760. def inv_cdf(self, p):
  761. """Inverse cumulative distribution function. x : P(X <= x) = p
  762. Finds the value of the random variable such that the probability of
  763. the variable being less than or equal to that value equals the given
  764. probability.
  765. This function is also called the percent point function or quantile
  766. function.
  767. """
  768. if p <= 0.0 or p >= 1.0:
  769. raise StatisticsError('p must be in the range 0.0 < p < 1.0')
  770. if self._sigma <= 0.0:
  771. raise StatisticsError('cdf() not defined when sigma at or below zero')
  772. return _normal_dist_inv_cdf(p, self._mu, self._sigma)
  773. def quantiles(self, n=4):
  774. """Divide into *n* continuous intervals with equal probability.
  775. Returns a list of (n - 1) cut points separating the intervals.
  776. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles.
  777. Set *n* to 100 for percentiles which gives the 99 cuts points that
  778. separate the normal distribution in to 100 equal sized groups.
  779. """
  780. return [self.inv_cdf(i / n) for i in range(1, n)]
  781. def overlap(self, other):
  782. """Compute the overlapping coefficient (OVL) between two normal distributions.
  783. Measures the agreement between two normal probability distributions.
  784. Returns a value between 0.0 and 1.0 giving the overlapping area in
  785. the two underlying probability density functions.
  786. >>> N1 = NormalDist(2.4, 1.6)
  787. >>> N2 = NormalDist(3.2, 2.0)
  788. >>> N1.overlap(N2)
  789. 0.8035050657330205
  790. """
  791. # See: "The overlapping coefficient as a measure of agreement between
  792. # probability distributions and point estimation of the overlap of two
  793. # normal densities" -- Henry F. Inman and Edwin L. Bradley Jr
  794. # http://dx.doi.org/10.1080/03610928908830127
  795. if not isinstance(other, NormalDist):
  796. raise TypeError('Expected another NormalDist instance')
  797. X, Y = self, other
  798. if (Y._sigma, Y._mu) < (X._sigma, X._mu): # sort to assure commutativity
  799. X, Y = Y, X
  800. X_var, Y_var = X.variance, Y.variance
  801. if not X_var or not Y_var:
  802. raise StatisticsError('overlap() not defined when sigma is zero')
  803. dv = Y_var - X_var
  804. dm = fabs(Y._mu - X._mu)
  805. if not dv:
  806. return 1.0 - erf(dm / (2.0 * X._sigma * sqrt(2.0)))
  807. a = X._mu * Y_var - Y._mu * X_var
  808. b = X._sigma * Y._sigma * sqrt(dm**2.0 + dv * log(Y_var / X_var))
  809. x1 = (a + b) / dv
  810. x2 = (a - b) / dv
  811. return 1.0 - (fabs(Y.cdf(x1) - X.cdf(x1)) + fabs(Y.cdf(x2) - X.cdf(x2)))
  812. @property
  813. def mean(self):
  814. "Arithmetic mean of the normal distribution."
  815. return self._mu
  816. @property
  817. def median(self):
  818. "Return the median of the normal distribution"
  819. return self._mu
  820. @property
  821. def mode(self):
  822. """Return the mode of the normal distribution
  823. The mode is the value x where which the probability density
  824. function (pdf) takes its maximum value.
  825. """
  826. return self._mu
  827. @property
  828. def stdev(self):
  829. "Standard deviation of the normal distribution."
  830. return self._sigma
  831. @property
  832. def variance(self):
  833. "Square of the standard deviation."
  834. return self._sigma ** 2.0
  835. def __add__(x1, x2):
  836. """Add a constant or another NormalDist instance.
  837. If *other* is a constant, translate mu by the constant,
  838. leaving sigma unchanged.
  839. If *other* is a NormalDist, add both the means and the variances.
  840. Mathematically, this works only if the two distributions are
  841. independent or if they are jointly normally distributed.
  842. """
  843. if isinstance(x2, NormalDist):
  844. return NormalDist(x1._mu + x2._mu, hypot(x1._sigma, x2._sigma))
  845. return NormalDist(x1._mu + x2, x1._sigma)
  846. def __sub__(x1, x2):
  847. """Subtract a constant or another NormalDist instance.
  848. If *other* is a constant, translate by the constant mu,
  849. leaving sigma unchanged.
  850. If *other* is a NormalDist, subtract the means and add the variances.
  851. Mathematically, this works only if the two distributions are
  852. independent or if they are jointly normally distributed.
  853. """
  854. if isinstance(x2, NormalDist):
  855. return NormalDist(x1._mu - x2._mu, hypot(x1._sigma, x2._sigma))
  856. return NormalDist(x1._mu - x2, x1._sigma)
  857. def __mul__(x1, x2):
  858. """Multiply both mu and sigma by a constant.
  859. Used for rescaling, perhaps to change measurement units.
  860. Sigma is scaled with the absolute value of the constant.
  861. """
  862. return NormalDist(x1._mu * x2, x1._sigma * fabs(x2))
  863. def __truediv__(x1, x2):
  864. """Divide both mu and sigma by a constant.
  865. Used for rescaling, perhaps to change measurement units.
  866. Sigma is scaled with the absolute value of the constant.
  867. """
  868. return NormalDist(x1._mu / x2, x1._sigma / fabs(x2))
  869. def __pos__(x1):
  870. "Return a copy of the instance."
  871. return NormalDist(x1._mu, x1._sigma)
  872. def __neg__(x1):
  873. "Negates mu while keeping sigma the same."
  874. return NormalDist(-x1._mu, x1._sigma)
  875. __radd__ = __add__
  876. def __rsub__(x1, x2):
  877. "Subtract a NormalDist from a constant or another NormalDist."
  878. return -(x1 - x2)
  879. __rmul__ = __mul__
  880. def __eq__(x1, x2):
  881. "Two NormalDist objects are equal if their mu and sigma are both equal."
  882. if not isinstance(x2, NormalDist):
  883. return NotImplemented
  884. return x1._mu == x2._mu and x1._sigma == x2._sigma
  885. def __hash__(self):
  886. "NormalDist objects hash equal if their mu and sigma are both equal."
  887. return hash((self._mu, self._sigma))
  888. def __repr__(self):
  889. return f'{type(self).__name__}(mu={self._mu!r}, sigma={self._sigma!r})'
  890. # If available, use C implementation
  891. try:
  892. from _statistics import _normal_dist_inv_cdf
  893. except ImportError:
  894. pass
  895. if __name__ == '__main__':
  896. # Show math operations computed analytically in comparsion
  897. # to a monte carlo simulation of the same operations
  898. from math import isclose
  899. from operator import add, sub, mul, truediv
  900. from itertools import repeat
  901. import doctest
  902. g1 = NormalDist(10, 20)
  903. g2 = NormalDist(-5, 25)
  904. # Test scaling by a constant
  905. assert (g1 * 5 / 5).mean == g1.mean
  906. assert (g1 * 5 / 5).stdev == g1.stdev
  907. n = 100_000
  908. G1 = g1.samples(n)
  909. G2 = g2.samples(n)
  910. for func in (add, sub):
  911. print(f'\nTest {func.__name__} with another NormalDist:')
  912. print(func(g1, g2))
  913. print(NormalDist.from_samples(map(func, G1, G2)))
  914. const = 11
  915. for func in (add, sub, mul, truediv):
  916. print(f'\nTest {func.__name__} with a constant:')
  917. print(func(g1, const))
  918. print(NormalDist.from_samples(map(func, G1, repeat(const))))
  919. const = 19
  920. for func in (add, sub, mul):
  921. print(f'\nTest constant with {func.__name__}:')
  922. print(func(const, g1))
  923. print(NormalDist.from_samples(map(func, repeat(const), G1)))
  924. def assert_close(G1, G2):
  925. assert isclose(G1.mean, G1.mean, rel_tol=0.01), (G1, G2)
  926. assert isclose(G1.stdev, G2.stdev, rel_tol=0.01), (G1, G2)
  927. X = NormalDist(-105, 73)
  928. Y = NormalDist(31, 47)
  929. s = 32.75
  930. n = 100_000
  931. S = NormalDist.from_samples([x + s for x in X.samples(n)])
  932. assert_close(X + s, S)
  933. S = NormalDist.from_samples([x - s for x in X.samples(n)])
  934. assert_close(X - s, S)
  935. S = NormalDist.from_samples([x * s for x in X.samples(n)])
  936. assert_close(X * s, S)
  937. S = NormalDist.from_samples([x / s for x in X.samples(n)])
  938. assert_close(X / s, S)
  939. S = NormalDist.from_samples([x + y for x, y in zip(X.samples(n),
  940. Y.samples(n))])
  941. assert_close(X + Y, S)
  942. S = NormalDist.from_samples([x - y for x, y in zip(X.samples(n),
  943. Y.samples(n))])
  944. assert_close(X - Y, S)
  945. print(doctest.testmod())