statistics.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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. Statistics for relations between two inputs
  56. -------------------------------------------
  57. ================== ====================================================
  58. Function Description
  59. ================== ====================================================
  60. covariance Sample covariance for two variables.
  61. correlation Pearson's correlation coefficient for two variables.
  62. linear_regression Intercept and slope for simple linear regression.
  63. ================== ====================================================
  64. Calculate covariance, Pearson's correlation, and simple linear regression
  65. for two inputs:
  66. >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  67. >>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
  68. >>> covariance(x, y)
  69. 0.75
  70. >>> correlation(x, y) #doctest: +ELLIPSIS
  71. 0.31622776601...
  72. >>> linear_regression(x, y) #doctest:
  73. LinearRegression(slope=0.1, intercept=1.5)
  74. Exceptions
  75. ----------
  76. A single exception is defined: StatisticsError is a subclass of ValueError.
  77. """
  78. __all__ = [
  79. 'NormalDist',
  80. 'StatisticsError',
  81. 'correlation',
  82. 'covariance',
  83. 'fmean',
  84. 'geometric_mean',
  85. 'harmonic_mean',
  86. 'linear_regression',
  87. 'mean',
  88. 'median',
  89. 'median_grouped',
  90. 'median_high',
  91. 'median_low',
  92. 'mode',
  93. 'multimode',
  94. 'pstdev',
  95. 'pvariance',
  96. 'quantiles',
  97. 'stdev',
  98. 'variance',
  99. ]
  100. import math
  101. import numbers
  102. import random
  103. import sys
  104. from fractions import Fraction
  105. from decimal import Decimal
  106. from itertools import count, groupby, repeat
  107. from bisect import bisect_left, bisect_right
  108. from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum, sumprod
  109. from functools import reduce
  110. from operator import itemgetter
  111. from collections import Counter, namedtuple, defaultdict
  112. _SQRT2 = sqrt(2.0)
  113. # === Exceptions ===
  114. class StatisticsError(ValueError):
  115. pass
  116. # === Private utilities ===
  117. def _sum(data):
  118. """_sum(data) -> (type, sum, count)
  119. Return a high-precision sum of the given numeric data as a fraction,
  120. together with the type to be converted to and the count of items.
  121. Examples
  122. --------
  123. >>> _sum([3, 2.25, 4.5, -0.5, 0.25])
  124. (<class 'float'>, Fraction(19, 2), 5)
  125. Some sources of round-off error will be avoided:
  126. # Built-in sum returns zero.
  127. >>> _sum([1e50, 1, -1e50] * 1000)
  128. (<class 'float'>, Fraction(1000, 1), 3000)
  129. Fractions and Decimals are also supported:
  130. >>> from fractions import Fraction as F
  131. >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
  132. (<class 'fractions.Fraction'>, Fraction(63, 20), 4)
  133. >>> from decimal import Decimal as D
  134. >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
  135. >>> _sum(data)
  136. (<class 'decimal.Decimal'>, Fraction(6963, 10000), 4)
  137. Mixed types are currently treated as an error, except that int is
  138. allowed.
  139. """
  140. count = 0
  141. types = set()
  142. types_add = types.add
  143. partials = {}
  144. partials_get = partials.get
  145. for typ, values in groupby(data, type):
  146. types_add(typ)
  147. for n, d in map(_exact_ratio, values):
  148. count += 1
  149. partials[d] = partials_get(d, 0) + n
  150. if None in partials:
  151. # The sum will be a NAN or INF. We can ignore all the finite
  152. # partials, and just look at this special one.
  153. total = partials[None]
  154. assert not _isfinite(total)
  155. else:
  156. # Sum all the partial sums using builtin sum.
  157. total = sum(Fraction(n, d) for d, n in partials.items())
  158. T = reduce(_coerce, types, int) # or raise TypeError
  159. return (T, total, count)
  160. def _ss(data, c=None):
  161. """Return the exact mean and sum of square deviations of sequence data.
  162. Calculations are done in a single pass, allowing the input to be an iterator.
  163. If given *c* is used the mean; otherwise, it is calculated from the data.
  164. Use the *c* argument with care, as it can lead to garbage results.
  165. """
  166. if c is not None:
  167. T, ssd, count = _sum((d := x - c) * d for x in data)
  168. return (T, ssd, c, count)
  169. count = 0
  170. types = set()
  171. types_add = types.add
  172. sx_partials = defaultdict(int)
  173. sxx_partials = defaultdict(int)
  174. for typ, values in groupby(data, type):
  175. types_add(typ)
  176. for n, d in map(_exact_ratio, values):
  177. count += 1
  178. sx_partials[d] += n
  179. sxx_partials[d] += n * n
  180. if not count:
  181. ssd = c = Fraction(0)
  182. elif None in sx_partials:
  183. # The sum will be a NAN or INF. We can ignore all the finite
  184. # partials, and just look at this special one.
  185. ssd = c = sx_partials[None]
  186. assert not _isfinite(ssd)
  187. else:
  188. sx = sum(Fraction(n, d) for d, n in sx_partials.items())
  189. sxx = sum(Fraction(n, d*d) for d, n in sxx_partials.items())
  190. # This formula has poor numeric properties for floats,
  191. # but with fractions it is exact.
  192. ssd = (count * sxx - sx * sx) / count
  193. c = sx / count
  194. T = reduce(_coerce, types, int) # or raise TypeError
  195. return (T, ssd, c, count)
  196. def _isfinite(x):
  197. try:
  198. return x.is_finite() # Likely a Decimal.
  199. except AttributeError:
  200. return math.isfinite(x) # Coerces to float first.
  201. def _coerce(T, S):
  202. """Coerce types T and S to a common type, or raise TypeError.
  203. Coercion rules are currently an implementation detail. See the CoerceTest
  204. test class in test_statistics for details.
  205. """
  206. # See http://bugs.python.org/issue24068.
  207. assert T is not bool, "initial type T is bool"
  208. # If the types are the same, no need to coerce anything. Put this
  209. # first, so that the usual case (no coercion needed) happens as soon
  210. # as possible.
  211. if T is S: return T
  212. # Mixed int & other coerce to the other type.
  213. if S is int or S is bool: return T
  214. if T is int: return S
  215. # If one is a (strict) subclass of the other, coerce to the subclass.
  216. if issubclass(S, T): return S
  217. if issubclass(T, S): return T
  218. # Ints coerce to the other type.
  219. if issubclass(T, int): return S
  220. if issubclass(S, int): return T
  221. # Mixed fraction & float coerces to float (or float subclass).
  222. if issubclass(T, Fraction) and issubclass(S, float):
  223. return S
  224. if issubclass(T, float) and issubclass(S, Fraction):
  225. return T
  226. # Any other combination is disallowed.
  227. msg = "don't know how to coerce %s and %s"
  228. raise TypeError(msg % (T.__name__, S.__name__))
  229. def _exact_ratio(x):
  230. """Return Real number x to exact (numerator, denominator) pair.
  231. >>> _exact_ratio(0.25)
  232. (1, 4)
  233. x is expected to be an int, Fraction, Decimal or float.
  234. """
  235. # XXX We should revisit whether using fractions to accumulate exact
  236. # ratios is the right way to go.
  237. # The integer ratios for binary floats can have numerators or
  238. # denominators with over 300 decimal digits. The problem is more
  239. # acute with decimal floats where the default decimal context
  240. # supports a huge range of exponents from Emin=-999999 to
  241. # Emax=999999. When expanded with as_integer_ratio(), numbers like
  242. # Decimal('3.14E+5000') and Decimal('3.14E-5000') have large
  243. # numerators or denominators that will slow computation.
  244. # When the integer ratios are accumulated as fractions, the size
  245. # grows to cover the full range from the smallest magnitude to the
  246. # largest. For example, Fraction(3.14E+300) + Fraction(3.14E-300),
  247. # has a 616 digit numerator. Likewise,
  248. # Fraction(Decimal('3.14E+5000')) + Fraction(Decimal('3.14E-5000'))
  249. # has 10,003 digit numerator.
  250. # This doesn't seem to have been problem in practice, but it is a
  251. # potential pitfall.
  252. try:
  253. return x.as_integer_ratio()
  254. except AttributeError:
  255. pass
  256. except (OverflowError, ValueError):
  257. # float NAN or INF.
  258. assert not _isfinite(x)
  259. return (x, None)
  260. try:
  261. # x may be an Integral ABC.
  262. return (x.numerator, x.denominator)
  263. except AttributeError:
  264. msg = f"can't convert type '{type(x).__name__}' to numerator/denominator"
  265. raise TypeError(msg)
  266. def _convert(value, T):
  267. """Convert value to given numeric type T."""
  268. if type(value) is T:
  269. # This covers the cases where T is Fraction, or where value is
  270. # a NAN or INF (Decimal or float).
  271. return value
  272. if issubclass(T, int) and value.denominator != 1:
  273. T = float
  274. try:
  275. # FIXME: what do we do if this overflows?
  276. return T(value)
  277. except TypeError:
  278. if issubclass(T, Decimal):
  279. return T(value.numerator) / T(value.denominator)
  280. else:
  281. raise
  282. def _fail_neg(values, errmsg='negative value'):
  283. """Iterate over values, failing if any are less than zero."""
  284. for x in values:
  285. if x < 0:
  286. raise StatisticsError(errmsg)
  287. yield x
  288. def _rank(data, /, *, key=None, reverse=False, ties='average', start=1) -> list[float]:
  289. """Rank order a dataset. The lowest value has rank 1.
  290. Ties are averaged so that equal values receive the same rank:
  291. >>> data = [31, 56, 31, 25, 75, 18]
  292. >>> _rank(data)
  293. [3.5, 5.0, 3.5, 2.0, 6.0, 1.0]
  294. The operation is idempotent:
  295. >>> _rank([3.5, 5.0, 3.5, 2.0, 6.0, 1.0])
  296. [3.5, 5.0, 3.5, 2.0, 6.0, 1.0]
  297. It is possible to rank the data in reverse order so that the
  298. highest value has rank 1. Also, a key-function can extract
  299. the field to be ranked:
  300. >>> goals = [('eagles', 45), ('bears', 48), ('lions', 44)]
  301. >>> _rank(goals, key=itemgetter(1), reverse=True)
  302. [2.0, 1.0, 3.0]
  303. Ranks are conventionally numbered starting from one; however,
  304. setting *start* to zero allows the ranks to be used as array indices:
  305. >>> prize = ['Gold', 'Silver', 'Bronze', 'Certificate']
  306. >>> scores = [8.1, 7.3, 9.4, 8.3]
  307. >>> [prize[int(i)] for i in _rank(scores, start=0, reverse=True)]
  308. ['Bronze', 'Certificate', 'Gold', 'Silver']
  309. """
  310. # If this function becomes public at some point, more thought
  311. # needs to be given to the signature. A list of ints is
  312. # plausible when ties is "min" or "max". When ties is "average",
  313. # either list[float] or list[Fraction] is plausible.
  314. # Default handling of ties matches scipy.stats.mstats.spearmanr.
  315. if ties != 'average':
  316. raise ValueError(f'Unknown tie resolution method: {ties!r}')
  317. if key is not None:
  318. data = map(key, data)
  319. val_pos = sorted(zip(data, count()), reverse=reverse)
  320. i = start - 1
  321. result = [0] * len(val_pos)
  322. for _, g in groupby(val_pos, key=itemgetter(0)):
  323. group = list(g)
  324. size = len(group)
  325. rank = i + (size + 1) / 2
  326. for value, orig_pos in group:
  327. result[orig_pos] = rank
  328. i += size
  329. return result
  330. def _integer_sqrt_of_frac_rto(n: int, m: int) -> int:
  331. """Square root of n/m, rounded to the nearest integer using round-to-odd."""
  332. # Reference: https://www.lri.fr/~melquion/doc/05-imacs17_1-expose.pdf
  333. a = math.isqrt(n // m)
  334. return a | (a*a*m != n)
  335. # For 53 bit precision floats, the bit width used in
  336. # _float_sqrt_of_frac() is 109.
  337. _sqrt_bit_width: int = 2 * sys.float_info.mant_dig + 3
  338. def _float_sqrt_of_frac(n: int, m: int) -> float:
  339. """Square root of n/m as a float, correctly rounded."""
  340. # See principle and proof sketch at: https://bugs.python.org/msg407078
  341. q = (n.bit_length() - m.bit_length() - _sqrt_bit_width) // 2
  342. if q >= 0:
  343. numerator = _integer_sqrt_of_frac_rto(n, m << 2 * q) << q
  344. denominator = 1
  345. else:
  346. numerator = _integer_sqrt_of_frac_rto(n << -2 * q, m)
  347. denominator = 1 << -q
  348. return numerator / denominator # Convert to float
  349. def _decimal_sqrt_of_frac(n: int, m: int) -> Decimal:
  350. """Square root of n/m as a Decimal, correctly rounded."""
  351. # Premise: For decimal, computing (n/m).sqrt() can be off
  352. # by 1 ulp from the correctly rounded result.
  353. # Method: Check the result, moving up or down a step if needed.
  354. if n <= 0:
  355. if not n:
  356. return Decimal('0.0')
  357. n, m = -n, -m
  358. root = (Decimal(n) / Decimal(m)).sqrt()
  359. nr, dr = root.as_integer_ratio()
  360. plus = root.next_plus()
  361. np, dp = plus.as_integer_ratio()
  362. # test: n / m > ((root + plus) / 2) ** 2
  363. if 4 * n * (dr*dp)**2 > m * (dr*np + dp*nr)**2:
  364. return plus
  365. minus = root.next_minus()
  366. nm, dm = minus.as_integer_ratio()
  367. # test: n / m < ((root + minus) / 2) ** 2
  368. if 4 * n * (dr*dm)**2 < m * (dr*nm + dm*nr)**2:
  369. return minus
  370. return root
  371. # === Measures of central tendency (averages) ===
  372. def mean(data):
  373. """Return the sample arithmetic mean of data.
  374. >>> mean([1, 2, 3, 4, 4])
  375. 2.8
  376. >>> from fractions import Fraction as F
  377. >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
  378. Fraction(13, 21)
  379. >>> from decimal import Decimal as D
  380. >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
  381. Decimal('0.5625')
  382. If ``data`` is empty, StatisticsError will be raised.
  383. """
  384. T, total, n = _sum(data)
  385. if n < 1:
  386. raise StatisticsError('mean requires at least one data point')
  387. return _convert(total / n, T)
  388. def fmean(data, weights=None):
  389. """Convert data to floats and compute the arithmetic mean.
  390. This runs faster than the mean() function and it always returns a float.
  391. If the input dataset is empty, it raises a StatisticsError.
  392. >>> fmean([3.5, 4.0, 5.25])
  393. 4.25
  394. """
  395. if weights is None:
  396. try:
  397. n = len(data)
  398. except TypeError:
  399. # Handle iterators that do not define __len__().
  400. n = 0
  401. def count(iterable):
  402. nonlocal n
  403. for n, x in enumerate(iterable, start=1):
  404. yield x
  405. data = count(data)
  406. total = fsum(data)
  407. if not n:
  408. raise StatisticsError('fmean requires at least one data point')
  409. return total / n
  410. if not isinstance(weights, (list, tuple)):
  411. weights = list(weights)
  412. try:
  413. num = sumprod(data, weights)
  414. except ValueError:
  415. raise StatisticsError('data and weights must be the same length')
  416. den = fsum(weights)
  417. if not den:
  418. raise StatisticsError('sum of weights must be non-zero')
  419. return num / den
  420. def geometric_mean(data):
  421. """Convert data to floats and compute the geometric mean.
  422. Raises a StatisticsError if the input dataset is empty,
  423. if it contains a zero, or if it contains a negative value.
  424. No special efforts are made to achieve exact results.
  425. (However, this may change in the future.)
  426. >>> round(geometric_mean([54, 24, 36]), 9)
  427. 36.0
  428. """
  429. try:
  430. return exp(fmean(map(log, data)))
  431. except ValueError:
  432. raise StatisticsError('geometric mean requires a non-empty dataset '
  433. 'containing positive numbers') from None
  434. def harmonic_mean(data, weights=None):
  435. """Return the harmonic mean of data.
  436. The harmonic mean is the reciprocal of the arithmetic mean of the
  437. reciprocals of the data. It can be used for averaging ratios or
  438. rates, for example speeds.
  439. Suppose a car travels 40 km/hr for 5 km and then speeds-up to
  440. 60 km/hr for another 5 km. What is the average speed?
  441. >>> harmonic_mean([40, 60])
  442. 48.0
  443. Suppose a car travels 40 km/hr for 5 km, and when traffic clears,
  444. speeds-up to 60 km/hr for the remaining 30 km of the journey. What
  445. is the average speed?
  446. >>> harmonic_mean([40, 60], weights=[5, 30])
  447. 56.0
  448. If ``data`` is empty, or any element is less than zero,
  449. ``harmonic_mean`` will raise ``StatisticsError``.
  450. """
  451. if iter(data) is data:
  452. data = list(data)
  453. errmsg = 'harmonic mean does not support negative values'
  454. n = len(data)
  455. if n < 1:
  456. raise StatisticsError('harmonic_mean requires at least one data point')
  457. elif n == 1 and weights is None:
  458. x = data[0]
  459. if isinstance(x, (numbers.Real, Decimal)):
  460. if x < 0:
  461. raise StatisticsError(errmsg)
  462. return x
  463. else:
  464. raise TypeError('unsupported type')
  465. if weights is None:
  466. weights = repeat(1, n)
  467. sum_weights = n
  468. else:
  469. if iter(weights) is weights:
  470. weights = list(weights)
  471. if len(weights) != n:
  472. raise StatisticsError('Number of weights does not match data size')
  473. _, sum_weights, _ = _sum(w for w in _fail_neg(weights, errmsg))
  474. try:
  475. data = _fail_neg(data, errmsg)
  476. T, total, count = _sum(w / x if w else 0 for w, x in zip(weights, data))
  477. except ZeroDivisionError:
  478. return 0
  479. if total <= 0:
  480. raise StatisticsError('Weighted sum must be positive')
  481. return _convert(sum_weights / total, T)
  482. # FIXME: investigate ways to calculate medians without sorting? Quickselect?
  483. def median(data):
  484. """Return the median (middle value) of numeric data.
  485. When the number of data points is odd, return the middle data point.
  486. When the number of data points is even, the median is interpolated by
  487. taking the average of the two middle values:
  488. >>> median([1, 3, 5])
  489. 3
  490. >>> median([1, 3, 5, 7])
  491. 4.0
  492. """
  493. data = sorted(data)
  494. n = len(data)
  495. if n == 0:
  496. raise StatisticsError("no median for empty data")
  497. if n % 2 == 1:
  498. return data[n // 2]
  499. else:
  500. i = n // 2
  501. return (data[i - 1] + data[i]) / 2
  502. def median_low(data):
  503. """Return the low median of numeric data.
  504. When the number of data points is odd, the middle value is returned.
  505. When it is even, the smaller of the two middle values is returned.
  506. >>> median_low([1, 3, 5])
  507. 3
  508. >>> median_low([1, 3, 5, 7])
  509. 3
  510. """
  511. data = sorted(data)
  512. n = len(data)
  513. if n == 0:
  514. raise StatisticsError("no median for empty data")
  515. if n % 2 == 1:
  516. return data[n // 2]
  517. else:
  518. return data[n // 2 - 1]
  519. def median_high(data):
  520. """Return the high median of data.
  521. When the number of data points is odd, the middle value is returned.
  522. When it is even, the larger of the two middle values is returned.
  523. >>> median_high([1, 3, 5])
  524. 3
  525. >>> median_high([1, 3, 5, 7])
  526. 5
  527. """
  528. data = sorted(data)
  529. n = len(data)
  530. if n == 0:
  531. raise StatisticsError("no median for empty data")
  532. return data[n // 2]
  533. def median_grouped(data, interval=1.0):
  534. """Estimates the median for numeric data binned around the midpoints
  535. of consecutive, fixed-width intervals.
  536. The *data* can be any iterable of numeric data with each value being
  537. exactly the midpoint of a bin. At least one value must be present.
  538. The *interval* is width of each bin.
  539. For example, demographic information may have been summarized into
  540. consecutive ten-year age groups with each group being represented
  541. by the 5-year midpoints of the intervals:
  542. >>> demographics = Counter({
  543. ... 25: 172, # 20 to 30 years old
  544. ... 35: 484, # 30 to 40 years old
  545. ... 45: 387, # 40 to 50 years old
  546. ... 55: 22, # 50 to 60 years old
  547. ... 65: 6, # 60 to 70 years old
  548. ... })
  549. The 50th percentile (median) is the 536th person out of the 1071
  550. member cohort. That person is in the 30 to 40 year old age group.
  551. The regular median() function would assume that everyone in the
  552. tricenarian age group was exactly 35 years old. A more tenable
  553. assumption is that the 484 members of that age group are evenly
  554. distributed between 30 and 40. For that, we use median_grouped().
  555. >>> data = list(demographics.elements())
  556. >>> median(data)
  557. 35
  558. >>> round(median_grouped(data, interval=10), 1)
  559. 37.5
  560. The caller is responsible for making sure the data points are separated
  561. by exact multiples of *interval*. This is essential for getting a
  562. correct result. The function does not check this precondition.
  563. Inputs may be any numeric type that can be coerced to a float during
  564. the interpolation step.
  565. """
  566. data = sorted(data)
  567. n = len(data)
  568. if not n:
  569. raise StatisticsError("no median for empty data")
  570. # Find the value at the midpoint. Remember this corresponds to the
  571. # midpoint of the class interval.
  572. x = data[n // 2]
  573. # Using O(log n) bisection, find where all the x values occur in the data.
  574. # All x will lie within data[i:j].
  575. i = bisect_left(data, x)
  576. j = bisect_right(data, x, lo=i)
  577. # Coerce to floats, raising a TypeError if not possible
  578. try:
  579. interval = float(interval)
  580. x = float(x)
  581. except ValueError:
  582. raise TypeError(f'Value cannot be converted to a float')
  583. # Interpolate the median using the formula found at:
  584. # https://www.cuemath.com/data/median-of-grouped-data/
  585. L = x - interval / 2.0 # Lower limit of the median interval
  586. cf = i # Cumulative frequency of the preceding interval
  587. f = j - i # Number of elements in the median internal
  588. return L + interval * (n / 2 - cf) / f
  589. def mode(data):
  590. """Return the most common data point from discrete or nominal data.
  591. ``mode`` assumes discrete data, and returns a single value. This is the
  592. standard treatment of the mode as commonly taught in schools:
  593. >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
  594. 3
  595. This also works with nominal (non-numeric) data:
  596. >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
  597. 'red'
  598. If there are multiple modes with same frequency, return the first one
  599. encountered:
  600. >>> mode(['red', 'red', 'green', 'blue', 'blue'])
  601. 'red'
  602. If *data* is empty, ``mode``, raises StatisticsError.
  603. """
  604. pairs = Counter(iter(data)).most_common(1)
  605. try:
  606. return pairs[0][0]
  607. except IndexError:
  608. raise StatisticsError('no mode for empty data') from None
  609. def multimode(data):
  610. """Return a list of the most frequently occurring values.
  611. Will return more than one result if there are multiple modes
  612. or an empty list if *data* is empty.
  613. >>> multimode('aabbbbbbbbcc')
  614. ['b']
  615. >>> multimode('aabbbbccddddeeffffgg')
  616. ['b', 'd', 'f']
  617. >>> multimode('')
  618. []
  619. """
  620. counts = Counter(iter(data))
  621. if not counts:
  622. return []
  623. maxcount = max(counts.values())
  624. return [value for value, count in counts.items() if count == maxcount]
  625. # Notes on methods for computing quantiles
  626. # ----------------------------------------
  627. #
  628. # There is no one perfect way to compute quantiles. Here we offer
  629. # two methods that serve common needs. Most other packages
  630. # surveyed offered at least one or both of these two, making them
  631. # "standard" in the sense of "widely-adopted and reproducible".
  632. # They are also easy to explain, easy to compute manually, and have
  633. # straight-forward interpretations that aren't surprising.
  634. # The default method is known as "R6", "PERCENTILE.EXC", or "expected
  635. # value of rank order statistics". The alternative method is known as
  636. # "R7", "PERCENTILE.INC", or "mode of rank order statistics".
  637. # For sample data where there is a positive probability for values
  638. # beyond the range of the data, the R6 exclusive method is a
  639. # reasonable choice. Consider a random sample of nine values from a
  640. # population with a uniform distribution from 0.0 to 1.0. The
  641. # distribution of the third ranked sample point is described by
  642. # betavariate(alpha=3, beta=7) which has mode=0.250, median=0.286, and
  643. # mean=0.300. Only the latter (which corresponds with R6) gives the
  644. # desired cut point with 30% of the population falling below that
  645. # value, making it comparable to a result from an inv_cdf() function.
  646. # The R6 exclusive method is also idempotent.
  647. # For describing population data where the end points are known to
  648. # be included in the data, the R7 inclusive method is a reasonable
  649. # choice. Instead of the mean, it uses the mode of the beta
  650. # distribution for the interior points. Per Hyndman & Fan, "One nice
  651. # property is that the vertices of Q7(p) divide the range into n - 1
  652. # intervals, and exactly 100p% of the intervals lie to the left of
  653. # Q7(p) and 100(1 - p)% of the intervals lie to the right of Q7(p)."
  654. # If needed, other methods could be added. However, for now, the
  655. # position is that fewer options make for easier choices and that
  656. # external packages can be used for anything more advanced.
  657. def quantiles(data, *, n=4, method='exclusive'):
  658. """Divide *data* into *n* continuous intervals with equal probability.
  659. Returns a list of (n - 1) cut points separating the intervals.
  660. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles.
  661. Set *n* to 100 for percentiles which gives the 99 cuts points that
  662. separate *data* in to 100 equal sized groups.
  663. The *data* can be any iterable containing sample.
  664. The cut points are linearly interpolated between data points.
  665. If *method* is set to *inclusive*, *data* is treated as population
  666. data. The minimum value is treated as the 0th percentile and the
  667. maximum value is treated as the 100th percentile.
  668. """
  669. if n < 1:
  670. raise StatisticsError('n must be at least 1')
  671. data = sorted(data)
  672. ld = len(data)
  673. if ld < 2:
  674. raise StatisticsError('must have at least two data points')
  675. if method == 'inclusive':
  676. m = ld - 1
  677. result = []
  678. for i in range(1, n):
  679. j, delta = divmod(i * m, n)
  680. interpolated = (data[j] * (n - delta) + data[j + 1] * delta) / n
  681. result.append(interpolated)
  682. return result
  683. if method == 'exclusive':
  684. m = ld + 1
  685. result = []
  686. for i in range(1, n):
  687. j = i * m // n # rescale i to m/n
  688. j = 1 if j < 1 else ld-1 if j > ld-1 else j # clamp to 1 .. ld-1
  689. delta = i*m - j*n # exact integer math
  690. interpolated = (data[j - 1] * (n - delta) + data[j] * delta) / n
  691. result.append(interpolated)
  692. return result
  693. raise ValueError(f'Unknown method: {method!r}')
  694. # === Measures of spread ===
  695. # See http://mathworld.wolfram.com/Variance.html
  696. # http://mathworld.wolfram.com/SampleVariance.html
  697. def variance(data, xbar=None):
  698. """Return the sample variance of data.
  699. data should be an iterable of Real-valued numbers, with at least two
  700. values. The optional argument xbar, if given, should be the mean of
  701. the data. If it is missing or None, the mean is automatically calculated.
  702. Use this function when your data is a sample from a population. To
  703. calculate the variance from the entire population, see ``pvariance``.
  704. Examples:
  705. >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
  706. >>> variance(data)
  707. 1.3720238095238095
  708. If you have already calculated the mean of your data, you can pass it as
  709. the optional second argument ``xbar`` to avoid recalculating it:
  710. >>> m = mean(data)
  711. >>> variance(data, m)
  712. 1.3720238095238095
  713. This function does not check that ``xbar`` is actually the mean of
  714. ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
  715. impossible results.
  716. Decimals and Fractions are supported:
  717. >>> from decimal import Decimal as D
  718. >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  719. Decimal('31.01875')
  720. >>> from fractions import Fraction as F
  721. >>> variance([F(1, 6), F(1, 2), F(5, 3)])
  722. Fraction(67, 108)
  723. """
  724. T, ss, c, n = _ss(data, xbar)
  725. if n < 2:
  726. raise StatisticsError('variance requires at least two data points')
  727. return _convert(ss / (n - 1), T)
  728. def pvariance(data, mu=None):
  729. """Return the population variance of ``data``.
  730. data should be a sequence or iterable of Real-valued numbers, with at least one
  731. value. The optional argument mu, if given, should be the mean of
  732. the data. If it is missing or None, the mean is automatically calculated.
  733. Use this function to calculate the variance from the entire population.
  734. To estimate the variance from a sample, the ``variance`` function is
  735. usually a better choice.
  736. Examples:
  737. >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
  738. >>> pvariance(data)
  739. 1.25
  740. If you have already calculated the mean of the data, you can pass it as
  741. the optional second argument to avoid recalculating it:
  742. >>> mu = mean(data)
  743. >>> pvariance(data, mu)
  744. 1.25
  745. Decimals and Fractions are supported:
  746. >>> from decimal import Decimal as D
  747. >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  748. Decimal('24.815')
  749. >>> from fractions import Fraction as F
  750. >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
  751. Fraction(13, 72)
  752. """
  753. T, ss, c, n = _ss(data, mu)
  754. if n < 1:
  755. raise StatisticsError('pvariance requires at least one data point')
  756. return _convert(ss / n, T)
  757. def stdev(data, xbar=None):
  758. """Return the square root of the sample variance.
  759. See ``variance`` for arguments and other details.
  760. >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  761. 1.0810874155219827
  762. """
  763. T, ss, c, n = _ss(data, xbar)
  764. if n < 2:
  765. raise StatisticsError('stdev requires at least two data points')
  766. mss = ss / (n - 1)
  767. if issubclass(T, Decimal):
  768. return _decimal_sqrt_of_frac(mss.numerator, mss.denominator)
  769. return _float_sqrt_of_frac(mss.numerator, mss.denominator)
  770. def pstdev(data, mu=None):
  771. """Return the square root of the population variance.
  772. See ``pvariance`` for arguments and other details.
  773. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  774. 0.986893273527251
  775. """
  776. T, ss, c, n = _ss(data, mu)
  777. if n < 1:
  778. raise StatisticsError('pstdev requires at least one data point')
  779. mss = ss / n
  780. if issubclass(T, Decimal):
  781. return _decimal_sqrt_of_frac(mss.numerator, mss.denominator)
  782. return _float_sqrt_of_frac(mss.numerator, mss.denominator)
  783. def _mean_stdev(data):
  784. """In one pass, compute the mean and sample standard deviation as floats."""
  785. T, ss, xbar, n = _ss(data)
  786. if n < 2:
  787. raise StatisticsError('stdev requires at least two data points')
  788. mss = ss / (n - 1)
  789. try:
  790. return float(xbar), _float_sqrt_of_frac(mss.numerator, mss.denominator)
  791. except AttributeError:
  792. # Handle Nans and Infs gracefully
  793. return float(xbar), float(xbar) / float(ss)
  794. # === Statistics for relations between two inputs ===
  795. # See https://en.wikipedia.org/wiki/Covariance
  796. # https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
  797. # https://en.wikipedia.org/wiki/Simple_linear_regression
  798. def covariance(x, y, /):
  799. """Covariance
  800. Return the sample covariance of two inputs *x* and *y*. Covariance
  801. is a measure of the joint variability of two inputs.
  802. >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  803. >>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
  804. >>> covariance(x, y)
  805. 0.75
  806. >>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1]
  807. >>> covariance(x, z)
  808. -7.5
  809. >>> covariance(z, x)
  810. -7.5
  811. """
  812. n = len(x)
  813. if len(y) != n:
  814. raise StatisticsError('covariance requires that both inputs have same number of data points')
  815. if n < 2:
  816. raise StatisticsError('covariance requires at least two data points')
  817. xbar = fsum(x) / n
  818. ybar = fsum(y) / n
  819. sxy = sumprod((xi - xbar for xi in x), (yi - ybar for yi in y))
  820. return sxy / (n - 1)
  821. def correlation(x, y, /, *, method='linear'):
  822. """Pearson's correlation coefficient
  823. Return the Pearson's correlation coefficient for two inputs. Pearson's
  824. correlation coefficient *r* takes values between -1 and +1. It measures
  825. the strength and direction of a linear relationship.
  826. >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  827. >>> y = [9, 8, 7, 6, 5, 4, 3, 2, 1]
  828. >>> correlation(x, x)
  829. 1.0
  830. >>> correlation(x, y)
  831. -1.0
  832. If *method* is "ranked", computes Spearman's rank correlation coefficient
  833. for two inputs. The data is replaced by ranks. Ties are averaged
  834. so that equal values receive the same rank. The resulting coefficient
  835. measures the strength of a monotonic relationship.
  836. Spearman's rank correlation coefficient is appropriate for ordinal
  837. data or for continuous data that doesn't meet the linear proportion
  838. requirement for Pearson's correlation coefficient.
  839. """
  840. n = len(x)
  841. if len(y) != n:
  842. raise StatisticsError('correlation requires that both inputs have same number of data points')
  843. if n < 2:
  844. raise StatisticsError('correlation requires at least two data points')
  845. if method not in {'linear', 'ranked'}:
  846. raise ValueError(f'Unknown method: {method!r}')
  847. if method == 'ranked':
  848. start = (n - 1) / -2 # Center rankings around zero
  849. x = _rank(x, start=start)
  850. y = _rank(y, start=start)
  851. else:
  852. xbar = fsum(x) / n
  853. ybar = fsum(y) / n
  854. x = [xi - xbar for xi in x]
  855. y = [yi - ybar for yi in y]
  856. sxy = sumprod(x, y)
  857. sxx = sumprod(x, x)
  858. syy = sumprod(y, y)
  859. try:
  860. return sxy / sqrt(sxx * syy)
  861. except ZeroDivisionError:
  862. raise StatisticsError('at least one of the inputs is constant')
  863. LinearRegression = namedtuple('LinearRegression', ('slope', 'intercept'))
  864. def linear_regression(x, y, /, *, proportional=False):
  865. """Slope and intercept for simple linear regression.
  866. Return the slope and intercept of simple linear regression
  867. parameters estimated using ordinary least squares. Simple linear
  868. regression describes relationship between an independent variable
  869. *x* and a dependent variable *y* in terms of a linear function:
  870. y = slope * x + intercept + noise
  871. where *slope* and *intercept* are the regression parameters that are
  872. estimated, and noise represents the variability of the data that was
  873. not explained by the linear regression (it is equal to the
  874. difference between predicted and actual values of the dependent
  875. variable).
  876. The parameters are returned as a named tuple.
  877. >>> x = [1, 2, 3, 4, 5]
  878. >>> noise = NormalDist().samples(5, seed=42)
  879. >>> y = [3 * x[i] + 2 + noise[i] for i in range(5)]
  880. >>> linear_regression(x, y) #doctest: +ELLIPSIS
  881. LinearRegression(slope=3.09078914170..., intercept=1.75684970486...)
  882. If *proportional* is true, the independent variable *x* and the
  883. dependent variable *y* are assumed to be directly proportional.
  884. The data is fit to a line passing through the origin.
  885. Since the *intercept* will always be 0.0, the underlying linear
  886. function simplifies to:
  887. y = slope * x + noise
  888. >>> y = [3 * x[i] + noise[i] for i in range(5)]
  889. >>> linear_regression(x, y, proportional=True) #doctest: +ELLIPSIS
  890. LinearRegression(slope=3.02447542484..., intercept=0.0)
  891. """
  892. n = len(x)
  893. if len(y) != n:
  894. raise StatisticsError('linear regression requires that both inputs have same number of data points')
  895. if n < 2:
  896. raise StatisticsError('linear regression requires at least two data points')
  897. if not proportional:
  898. xbar = fsum(x) / n
  899. ybar = fsum(y) / n
  900. x = [xi - xbar for xi in x] # List because used three times below
  901. y = (yi - ybar for yi in y) # Generator because only used once below
  902. sxy = sumprod(x, y) + 0.0 # Add zero to coerce result to a float
  903. sxx = sumprod(x, x)
  904. try:
  905. slope = sxy / sxx # equivalent to: covariance(x, y) / variance(x)
  906. except ZeroDivisionError:
  907. raise StatisticsError('x is constant')
  908. intercept = 0.0 if proportional else ybar - slope * xbar
  909. return LinearRegression(slope=slope, intercept=intercept)
  910. ## Normal Distribution #####################################################
  911. def _normal_dist_inv_cdf(p, mu, sigma):
  912. # There is no closed-form solution to the inverse CDF for the normal
  913. # distribution, so we use a rational approximation instead:
  914. # Wichura, M.J. (1988). "Algorithm AS241: The Percentage Points of the
  915. # Normal Distribution". Applied Statistics. Blackwell Publishing. 37
  916. # (3): 477–484. doi:10.2307/2347330. JSTOR 2347330.
  917. q = p - 0.5
  918. if fabs(q) <= 0.425:
  919. r = 0.180625 - q * q
  920. # Hash sum: 55.88319_28806_14901_4439
  921. num = (((((((2.50908_09287_30122_6727e+3 * r +
  922. 3.34305_75583_58812_8105e+4) * r +
  923. 6.72657_70927_00870_0853e+4) * r +
  924. 4.59219_53931_54987_1457e+4) * r +
  925. 1.37316_93765_50946_1125e+4) * r +
  926. 1.97159_09503_06551_4427e+3) * r +
  927. 1.33141_66789_17843_7745e+2) * r +
  928. 3.38713_28727_96366_6080e+0) * q
  929. den = (((((((5.22649_52788_52854_5610e+3 * r +
  930. 2.87290_85735_72194_2674e+4) * r +
  931. 3.93078_95800_09271_0610e+4) * r +
  932. 2.12137_94301_58659_5867e+4) * r +
  933. 5.39419_60214_24751_1077e+3) * r +
  934. 6.87187_00749_20579_0830e+2) * r +
  935. 4.23133_30701_60091_1252e+1) * r +
  936. 1.0)
  937. x = num / den
  938. return mu + (x * sigma)
  939. r = p if q <= 0.0 else 1.0 - p
  940. r = sqrt(-log(r))
  941. if r <= 5.0:
  942. r = r - 1.6
  943. # Hash sum: 49.33206_50330_16102_89036
  944. num = (((((((7.74545_01427_83414_07640e-4 * r +
  945. 2.27238_44989_26918_45833e-2) * r +
  946. 2.41780_72517_74506_11770e-1) * r +
  947. 1.27045_82524_52368_38258e+0) * r +
  948. 3.64784_83247_63204_60504e+0) * r +
  949. 5.76949_72214_60691_40550e+0) * r +
  950. 4.63033_78461_56545_29590e+0) * r +
  951. 1.42343_71107_49683_57734e+0)
  952. den = (((((((1.05075_00716_44416_84324e-9 * r +
  953. 5.47593_80849_95344_94600e-4) * r +
  954. 1.51986_66563_61645_71966e-2) * r +
  955. 1.48103_97642_74800_74590e-1) * r +
  956. 6.89767_33498_51000_04550e-1) * r +
  957. 1.67638_48301_83803_84940e+0) * r +
  958. 2.05319_16266_37758_82187e+0) * r +
  959. 1.0)
  960. else:
  961. r = r - 5.0
  962. # Hash sum: 47.52583_31754_92896_71629
  963. num = (((((((2.01033_43992_92288_13265e-7 * r +
  964. 2.71155_55687_43487_57815e-5) * r +
  965. 1.24266_09473_88078_43860e-3) * r +
  966. 2.65321_89526_57612_30930e-2) * r +
  967. 2.96560_57182_85048_91230e-1) * r +
  968. 1.78482_65399_17291_33580e+0) * r +
  969. 5.46378_49111_64114_36990e+0) * r +
  970. 6.65790_46435_01103_77720e+0)
  971. den = (((((((2.04426_31033_89939_78564e-15 * r +
  972. 1.42151_17583_16445_88870e-7) * r +
  973. 1.84631_83175_10054_68180e-5) * r +
  974. 7.86869_13114_56132_59100e-4) * r +
  975. 1.48753_61290_85061_48525e-2) * r +
  976. 1.36929_88092_27358_05310e-1) * r +
  977. 5.99832_20655_58879_37690e-1) * r +
  978. 1.0)
  979. x = num / den
  980. if q < 0.0:
  981. x = -x
  982. return mu + (x * sigma)
  983. # If available, use C implementation
  984. try:
  985. from _statistics import _normal_dist_inv_cdf
  986. except ImportError:
  987. pass
  988. class NormalDist:
  989. "Normal distribution of a random variable"
  990. # https://en.wikipedia.org/wiki/Normal_distribution
  991. # https://en.wikipedia.org/wiki/Variance#Properties
  992. __slots__ = {
  993. '_mu': 'Arithmetic mean of a normal distribution',
  994. '_sigma': 'Standard deviation of a normal distribution',
  995. }
  996. def __init__(self, mu=0.0, sigma=1.0):
  997. "NormalDist where mu is the mean and sigma is the standard deviation."
  998. if sigma < 0.0:
  999. raise StatisticsError('sigma must be non-negative')
  1000. self._mu = float(mu)
  1001. self._sigma = float(sigma)
  1002. @classmethod
  1003. def from_samples(cls, data):
  1004. "Make a normal distribution instance from sample data."
  1005. return cls(*_mean_stdev(data))
  1006. def samples(self, n, *, seed=None):
  1007. "Generate *n* samples for a given mean and standard deviation."
  1008. gauss = random.gauss if seed is None else random.Random(seed).gauss
  1009. mu, sigma = self._mu, self._sigma
  1010. return [gauss(mu, sigma) for _ in repeat(None, n)]
  1011. def pdf(self, x):
  1012. "Probability density function. P(x <= X < x+dx) / dx"
  1013. variance = self._sigma * self._sigma
  1014. if not variance:
  1015. raise StatisticsError('pdf() not defined when sigma is zero')
  1016. diff = x - self._mu
  1017. return exp(diff * diff / (-2.0 * variance)) / sqrt(tau * variance)
  1018. def cdf(self, x):
  1019. "Cumulative distribution function. P(X <= x)"
  1020. if not self._sigma:
  1021. raise StatisticsError('cdf() not defined when sigma is zero')
  1022. return 0.5 * (1.0 + erf((x - self._mu) / (self._sigma * _SQRT2)))
  1023. def inv_cdf(self, p):
  1024. """Inverse cumulative distribution function. x : P(X <= x) = p
  1025. Finds the value of the random variable such that the probability of
  1026. the variable being less than or equal to that value equals the given
  1027. probability.
  1028. This function is also called the percent point function or quantile
  1029. function.
  1030. """
  1031. if p <= 0.0 or p >= 1.0:
  1032. raise StatisticsError('p must be in the range 0.0 < p < 1.0')
  1033. return _normal_dist_inv_cdf(p, self._mu, self._sigma)
  1034. def quantiles(self, n=4):
  1035. """Divide into *n* continuous intervals with equal probability.
  1036. Returns a list of (n - 1) cut points separating the intervals.
  1037. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles.
  1038. Set *n* to 100 for percentiles which gives the 99 cuts points that
  1039. separate the normal distribution in to 100 equal sized groups.
  1040. """
  1041. return [self.inv_cdf(i / n) for i in range(1, n)]
  1042. def overlap(self, other):
  1043. """Compute the overlapping coefficient (OVL) between two normal distributions.
  1044. Measures the agreement between two normal probability distributions.
  1045. Returns a value between 0.0 and 1.0 giving the overlapping area in
  1046. the two underlying probability density functions.
  1047. >>> N1 = NormalDist(2.4, 1.6)
  1048. >>> N2 = NormalDist(3.2, 2.0)
  1049. >>> N1.overlap(N2)
  1050. 0.8035050657330205
  1051. """
  1052. # See: "The overlapping coefficient as a measure of agreement between
  1053. # probability distributions and point estimation of the overlap of two
  1054. # normal densities" -- Henry F. Inman and Edwin L. Bradley Jr
  1055. # http://dx.doi.org/10.1080/03610928908830127
  1056. if not isinstance(other, NormalDist):
  1057. raise TypeError('Expected another NormalDist instance')
  1058. X, Y = self, other
  1059. if (Y._sigma, Y._mu) < (X._sigma, X._mu): # sort to assure commutativity
  1060. X, Y = Y, X
  1061. X_var, Y_var = X.variance, Y.variance
  1062. if not X_var or not Y_var:
  1063. raise StatisticsError('overlap() not defined when sigma is zero')
  1064. dv = Y_var - X_var
  1065. dm = fabs(Y._mu - X._mu)
  1066. if not dv:
  1067. return 1.0 - erf(dm / (2.0 * X._sigma * _SQRT2))
  1068. a = X._mu * Y_var - Y._mu * X_var
  1069. b = X._sigma * Y._sigma * sqrt(dm * dm + dv * log(Y_var / X_var))
  1070. x1 = (a + b) / dv
  1071. x2 = (a - b) / dv
  1072. return 1.0 - (fabs(Y.cdf(x1) - X.cdf(x1)) + fabs(Y.cdf(x2) - X.cdf(x2)))
  1073. def zscore(self, x):
  1074. """Compute the Standard Score. (x - mean) / stdev
  1075. Describes *x* in terms of the number of standard deviations
  1076. above or below the mean of the normal distribution.
  1077. """
  1078. # https://www.statisticshowto.com/probability-and-statistics/z-score/
  1079. if not self._sigma:
  1080. raise StatisticsError('zscore() not defined when sigma is zero')
  1081. return (x - self._mu) / self._sigma
  1082. @property
  1083. def mean(self):
  1084. "Arithmetic mean of the normal distribution."
  1085. return self._mu
  1086. @property
  1087. def median(self):
  1088. "Return the median of the normal distribution"
  1089. return self._mu
  1090. @property
  1091. def mode(self):
  1092. """Return the mode of the normal distribution
  1093. The mode is the value x where which the probability density
  1094. function (pdf) takes its maximum value.
  1095. """
  1096. return self._mu
  1097. @property
  1098. def stdev(self):
  1099. "Standard deviation of the normal distribution."
  1100. return self._sigma
  1101. @property
  1102. def variance(self):
  1103. "Square of the standard deviation."
  1104. return self._sigma * self._sigma
  1105. def __add__(x1, x2):
  1106. """Add a constant or another NormalDist instance.
  1107. If *other* is a constant, translate mu by the constant,
  1108. leaving sigma unchanged.
  1109. If *other* is a NormalDist, add both the means and the variances.
  1110. Mathematically, this works only if the two distributions are
  1111. independent or if they are jointly normally distributed.
  1112. """
  1113. if isinstance(x2, NormalDist):
  1114. return NormalDist(x1._mu + x2._mu, hypot(x1._sigma, x2._sigma))
  1115. return NormalDist(x1._mu + x2, x1._sigma)
  1116. def __sub__(x1, x2):
  1117. """Subtract a constant or another NormalDist instance.
  1118. If *other* is a constant, translate by the constant mu,
  1119. leaving sigma unchanged.
  1120. If *other* is a NormalDist, subtract the means and add the variances.
  1121. Mathematically, this works only if the two distributions are
  1122. independent or if they are jointly normally distributed.
  1123. """
  1124. if isinstance(x2, NormalDist):
  1125. return NormalDist(x1._mu - x2._mu, hypot(x1._sigma, x2._sigma))
  1126. return NormalDist(x1._mu - x2, x1._sigma)
  1127. def __mul__(x1, x2):
  1128. """Multiply both mu and sigma by a constant.
  1129. Used for rescaling, perhaps to change measurement units.
  1130. Sigma is scaled with the absolute value of the constant.
  1131. """
  1132. return NormalDist(x1._mu * x2, x1._sigma * fabs(x2))
  1133. def __truediv__(x1, x2):
  1134. """Divide both mu and sigma by a constant.
  1135. Used for rescaling, perhaps to change measurement units.
  1136. Sigma is scaled with the absolute value of the constant.
  1137. """
  1138. return NormalDist(x1._mu / x2, x1._sigma / fabs(x2))
  1139. def __pos__(x1):
  1140. "Return a copy of the instance."
  1141. return NormalDist(x1._mu, x1._sigma)
  1142. def __neg__(x1):
  1143. "Negates mu while keeping sigma the same."
  1144. return NormalDist(-x1._mu, x1._sigma)
  1145. __radd__ = __add__
  1146. def __rsub__(x1, x2):
  1147. "Subtract a NormalDist from a constant or another NormalDist."
  1148. return -(x1 - x2)
  1149. __rmul__ = __mul__
  1150. def __eq__(x1, x2):
  1151. "Two NormalDist objects are equal if their mu and sigma are both equal."
  1152. if not isinstance(x2, NormalDist):
  1153. return NotImplemented
  1154. return x1._mu == x2._mu and x1._sigma == x2._sigma
  1155. def __hash__(self):
  1156. "NormalDist objects hash equal if their mu and sigma are both equal."
  1157. return hash((self._mu, self._sigma))
  1158. def __repr__(self):
  1159. return f'{type(self).__name__}(mu={self._mu!r}, sigma={self._sigma!r})'
  1160. def __getstate__(self):
  1161. return self._mu, self._sigma
  1162. def __setstate__(self, state):
  1163. self._mu, self._sigma = state