\dYvUdZgdZddlZddlZddlZddlZddlmZddlm Z ddl m Z m Z ddl mZmZddlmZmZmZmZmZmZmZmZdd lmZdd lmZdd lmZmZmZed Z Gd de!Z"dZ#d?dZ$dZ%dZ&dZ'dZ(d@dZ)de*de*de*fdZ+dej,j-zdzZ.e*e/d<de*de*de0fdZ1de*de*de fdZ2d Z3d?d!Z4d"Z5d?d#Z6d$Z7d%Z8d&Z9dAd(Z:d)Z;d*Zd?d0Z?d?d1Z@d?d2ZAd3ZBd4ZCd5ZDed6d7ZEd8d9d:ZFd;ZG ddZJdS)Ba Basic statistics module. This module provides functions for calculating statistics of data, including averages, variance, and standard deviation. Calculating averages -------------------- ================== ================================================== Function Description ================== ================================================== mean Arithmetic mean (average) of data. fmean Fast, floating point arithmetic mean. geometric_mean Geometric mean of data. harmonic_mean Harmonic mean of data. median Median (middle value) of data. median_low Low median of data. median_high High median of data. median_grouped Median, or 50th percentile, of grouped data. mode Mode (most common value) of data. multimode List of modes (most common values of data). quantiles Divide data into intervals with equal probability. ================== ================================================== Calculate the arithmetic mean ("the average") of data: >>> mean([-1.0, 2.5, 3.25, 5.75]) 2.625 Calculate the standard median of discrete data: >>> median([2, 3, 4, 5]) 3.5 Calculate the median, or 50th percentile, of data grouped into class intervals centred on the data values provided. E.g. if your data points are rounded to the nearest whole number: >>> median_grouped([2, 2, 3, 3, 3, 4]) #doctest: +ELLIPSIS 2.8333333333... This should be interpreted in this way: you have two data points in the class interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in the class interval 3.5-4.5. The median of these data points is 2.8333... Calculating variability or spread --------------------------------- ================== ============================================= Function Description ================== ============================================= pvariance Population variance of data. variance Sample variance of data. pstdev Population standard deviation of data. stdev Sample standard deviation of data. ================== ============================================= Calculate the standard deviation of sample data: >>> stdev([2.5, 3.25, 5.5, 11.25, 11.75]) #doctest: +ELLIPSIS 4.38961843444... If you have previously calculated the mean, you can pass it as the optional second argument to the four "spread" functions to avoid recalculating it: >>> data = [1, 2, 2, 4, 4, 4, 5, 6] >>> mu = mean(data) >>> pvariance(data, mu) 2.5 Statistics for relations between two inputs ------------------------------------------- ================== ==================================================== Function Description ================== ==================================================== covariance Sample covariance for two variables. correlation Pearson's correlation coefficient for two variables. linear_regression Intercept and slope for simple linear regression. ================== ==================================================== Calculate covariance, Pearson's correlation, and simple linear regression for two inputs: >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> covariance(x, y) 0.75 >>> correlation(x, y) #doctest: +ELLIPSIS 0.31622776601... >>> linear_regression(x, y) #doctest: LinearRegression(slope=0.1, intercept=1.5) Exceptions ---------- A single exception is defined: StatisticsError is a subclass of ValueError. ) NormalDistStatisticsError correlation covariancefmeangeometric_mean harmonic_meanlinear_regressionmeanmedianmedian_grouped median_high median_lowmode multimodepstdev pvariance quantilesstdevvarianceNFraction)Decimal)groupbyrepeat) bisect_left bisect_right)hypotsqrtfabsexperftaulogfsum)reduce)mul)Counter namedtuple defaultdict@ceZdZdS)rN)__name__ __module__ __qualname__..\python\lib\statistics.pyrrsDr1rcd}t}|j}i}|j}t|tD]B\}}||t t |D]\}} |dz }|| d|z|| <Cd|vr|d} t| rJn+td| D} tt|t} | | |fS)a_sum(data) -> (type, sum, count) Return a high-precision sum of the given numeric data as a fraction, together with the type to be converted to and the count of items. Examples -------- >>> _sum([3, 2.25, 4.5, -0.5, 0.25]) (, Fraction(19, 2), 5) Some sources of round-off error will be avoided: # Built-in sum returns zero. >>> _sum([1e50, 1, -1e50] * 1000) (, Fraction(1000, 1), 3000) Fractions and Decimals are also supported: >>> from fractions import Fraction as F >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)]) (, Fraction(63, 20), 4) >>> from decimal import Decimal as D >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")] >>> _sum(data) (, Fraction(6963, 10000), 4) Mixed types are currently treated as an error, except that int is allowed. rNc3<K|]\}}t||VdSNr.0dns r2 z_sum..s.@@tq!HQNN@@@@@@r1) setaddgetrtypemap _exact_ratio _isfinitesumitemsr&_coerceint) datacounttypes types_addpartials partials_gettypvaluesr:r9totalTs r2_sumrQs @ E EEE IH.s0<.s.@@DAq!Q@@@@@@r1c3BK|]\}}t|||zVdSr6rr7s r2r;z_ss..s4DDtq!(1ac""DDDDDDr1)rQr<r=r*rFrr?r@rArrBrCrDr&rE)rGrUrPssdrHrIrJ sx_partials sxx_partialsrMrNr:sxsxxr9s ` @r2_ssr]s }<<<<>!!!! @@K,=,=,?,?@@@ @ @DD|/A/A/C/CDDDDDs{R"W$- Jws##A sAu r1ct |S#t$rtj|cYSwxYwr6) is_finiteAttributeErrormathisfinite)rTs r2rBrBsF {{}}    }Q s 77c|tus Jd||ur|S|tus |tur|S|tur|St||r|St||r|St|tr|St|tr|St|trt|tr|St|trt|tr|Sd}t ||j|jfz)zCoerce types T and S to a common type, or raise TypeError. Coercion rules are currently an implementation detail. See the CoerceTest test class in test_statistics for details. zinitial type T is boolz"don't know how to coerce %s and %s)boolrF issubclassrfloat TypeErrorr-)rPSmsgs r2rErEs  D===2=== AvvqCxx199axCxx(!Q"(!Q"(!S$1H!S$1H!X:a#7#7!U 1h 7 7 .C C1:qz22 3 33r1c" |S#t$rYn+ttf$rt |rJ|dfcYSwxYw |j|jfS#t$r(dt|jd}t|wxYw)zReturn Real number x to exact (numerator, denominator) pair. >>> _exact_ratio(0.25) (1, 4) x is expected to be an int, Fraction, Decimal or float. Nzcan't convert type 'z' to numerator/denominator) as_integer_ratior` OverflowError ValueErrorrB numerator denominatorr?r-rg)rTris r2rArAs<!!###      : &Q<<4y Q]++ QT!WW%5QQQnns  A %A  A  A2Bct||ur|St|tr|jdkrt} ||S#t $r:t|t r#||j||jz cYSwxYw)z&Convert value to given numeric type T.r4)r?rerFrorfrgrrn)valuerPs r2_convertrrMs E{{a !Se/144 qxx  a ! ! 1U_%%%*;(<(<< < < <  s AAB  B negative valuec#FK|D]}|dkrt||VdS)z7Iterate over values, failing if any are less than zero.rN)r)rNerrmsgrTs r2 _fail_negrv_sA  q55!&)) )r1r:mreturncNtj||z}|||z|z|kzS)zFSquare root of n/m, rounded to the nearest integer using round-to-odd.)raisqrt)r:rwas r2_integer_sqrt_of_frac_rtor|gs. 16A !A r1_sqrt_bit_widthc||z tz dz}|dkrt||d|zz|z}d}nt|d|zz|}d| z}||z S)z1Square root of n/m as a float, correctly rounded.r}rr4) bit_lengthrr|)r:rwqrnros r2_float_sqrt_of_fracrss !,,.. (? :q@AAvv-aa!e<<A  -a26k1== A2g { ""r1c|dkr|stdS| | }}t|t|z }|\}}|}|\}}d|z||zdzz|||z||zzdzzkr|S|}|\} } d|z|| zdzz||| z| |zzdzzkr|S|S)z3Square root of n/m as a Decimal, correctly rounded.rz0.0r})rrrk next_plus next_minus) r:rwrootnrdrplusnpdpminusnmdms r2_decimal_sqrt_of_fracrs   Avv "5>> !rA21 AJJ # ) ) + +D  " " $ $FB >>  D  " " $ $FB1u2zABB 2222 OO  E  # # % %FB1u2zABB 2222 Kr1cxt|\}}}|dkrtdt||z |S)aReturn the sample arithmetic mean of data. >>> mean([1, 2, 3, 4, 4]) 2.8 >>> from fractions import Fraction as F >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) Fraction(13, 21) >>> from decimal import Decimal as D >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")]) Decimal('0.5625') If ``data`` is empty, StatisticsError will be raised. r4z%mean requires at least one data point)rQrrr)rGrPrOr:s r2r r sA t**KAua1uuEFFF EAIq ! !!r1c t|n"#t$rdfd}||}YnwxYw|%t|}std|z S t|}n.#t$r!t |}t|}YnwxYwtt t ||}|krtdt|}|std||z S)zConvert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. If the input dataset is empty, it raises a StatisticsError. >>> fmean([3.5, 4.0, 5.25]) 4.25 rc3BKt|dD] \}|V dS)Nr4)start) enumerate)iterablerTr:s r2rHzfmean..counts<!(!444  1  r1Nz&fmean requires at least one data pointz(data and weights must be the same lengthzsum of weights must be non-zero)lenrgr%rlistr@r')rGweightsrHrO num_weightsnumdenr:s @r2rrs>  II       uT{{T  L!"JKK Kqy#'ll ###w--'ll # s3g&& ' 'CKHIII w--C A?@@@ 9s22A--(BBc tttt|S#t$rt ddwxYw)aYConvert data to floats and compute the geometric mean. Raises a StatisticsError if the input dataset is empty, if it contains a zero, or if it contains a negative value. No special efforts are made to achieve exact results. (However, this may change in the future.) >>> round(geometric_mean([54, 24, 36]), 9) 36.0 zGgeometric mean requires a non-empty dataset containing positive numbersN)r!rr@r$rmr)rGs r2rrs`G5S$(())) GGG<==BF GGs .1A c,t||urt|}d}t|}|dkrtd|dkrQ|O|d}t |t jtfr|dkrt||Std|td|}|}nmt||urt|}t||krtdtdt||D\}}} t||}td t||D\}}} n#t$rYdSwxYw|dkrtd t||z |S) aReturn the harmonic mean of data. The harmonic mean is the reciprocal of the arithmetic mean of the reciprocals of the data. It can be used for averaging ratios or rates, for example speeds. Suppose a car travels 40 km/hr for 5 km and then speeds-up to 60 km/hr for another 5 km. What is the average speed? >>> harmonic_mean([40, 60]) 48.0 Suppose a car travels 40 km/hr for 5 km, and when traffic clears, speeds-up to 60 km/hr for the remaining 30 km of the journey. What is the average speed? >>> harmonic_mean([40, 60], weights=[5, 30]) 56.0 If ``data`` is empty, or any element is less than zero, ``harmonic_mean`` will raise ``StatisticsError``. z.harmonic mean does not support negative valuesr4z.harmonic_mean requires at least one data pointNrzunsupported typez*Number of weights does not match data sizec3K|]}|VdSr6r0)r8ws r2r;z harmonic_mean..s" G Gq G G G G G Gr1c3.K|]\}}|r||z ndVdS)rNr0)r8rrTs r2r;z harmonic_mean..s3PPTQ0q1uuqPPPPPPr1zWeighted sum must be positive)iterrrr isinstancenumbersRealrrgrrQrvzipZeroDivisionErrorrr) rGrrur:rT sum_weights_rPrOrHs r2rrs. DzzTDzz =F D A1uuNOOO aGO G a',0 1 1 01uu%f---H.// /A,, ==G # #7mmG w<<1  !"NOO O G GIgv,F,F G G GGG;v&&PPS$=O=OPPPPP5%% qq zz=>>> K%' + ++s!;E E+*E+ct|}t|}|dkrtd|dzdkr ||dzS|dz}||dz ||zdz S)aBReturn the median (middle value) of numeric data. When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values: >>> median([1, 3, 5]) 3 >>> median([1, 3, 5, 7]) 4.0 rno median for empty datar}r4sortedrr)rGr:is r2r r %sr $<>> median_low([1, 3, 5]) 3 >>> median_low([1, 3, 5, 7]) 3 rrr}r4rrGr:s r2rr=s` $<>> median_high([1, 3, 5]) 3 >>> median_high([1, 3, 5, 7]) 5 rrr}rrs r2r r Ss@ $<>> demographics = Counter({ ... 25: 172, # 20 to 30 years old ... 35: 484, # 30 to 40 years old ... 45: 387, # 40 to 50 years old ... 55: 22, # 50 to 60 years old ... 65: 6, # 60 to 70 years old ... }) The 50th percentile (median) is the 536th person out of the 1071 member cohort. That person is in the 30 to 40 year old age group. The regular median() function would assume that everyone in the tricenarian age group was exactly 35 years old. A more tenable assumption is that the 484 members of that age group are evenly distributed between 30 and 40. For that, we use median_grouped(). >>> data = list(demographics.elements()) >>> median(data) 35 >>> round(median_grouped(data, interval=10), 1) 37.5 The caller is responsible for making sure the data points are separated by exact multiples of *interval*. This is essential for getting a correct result. The function does not check this precondition. Inputs may be any numeric type that can be coerced to a float during the interpolation step. rr})loz$Value cannot be converted to a floatr+)rrrrrrfrmrg) rGintervalr:rTrjLcffs r2r r fsV $<>> mode([1, 1, 2, 3, 3, 3, 3, 4]) 3 This also works with nominal (non-numeric) data: >>> mode(["red", "blue", "blue", "red", "green", "red", "red"]) 'red' If there are multiple modes with same frequency, return the first one encountered: >>> mode(['red', 'red', 'green', 'blue', 'blue']) 'red' If *data* is empty, ``mode``, raises StatisticsError. r4rzno mode for empty dataN)r(r most_common IndexErrorr)rGpairss r2rrsi. DJJ   + +A . .EBQx{ BBB677TABs ?Actt|}|sgSt|fd|DS)a.Return a list of the most frequently occurring values. Will return more than one result if there are multiple modes or an empty list if *data* is empty. >>> multimode('aabbbbbbbbcc') ['b'] >>> multimode('aabbbbccddddeeffffgg') ['b', 'd', 'f'] >>> multimode('') [] c&g|] \}}|k |Sr0r0)r8rqrHmaxcounts r2 zmultimode..s' J J JleU8I8IE8I8I8Ir1)r(rmaxrNrD)rGcountsrs @r2rrs\T$ZZ F  6==??##H J J J Jfllnn J J JJr1r exclusive)r:methodc|dkrtdt|}t|}|dkrtd|dkrg|dz }g}td|D]M}t ||z|\}}||||z z||dz|zz|z } || N|S|dkr||dz}g}td|D]b}||z|z}|dkrdn||dz kr|dz n|}||z||zz }||dz ||z z|||zz|z } || c|St d|)aDivide *data* into *n* continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. Set *n* to 100 for percentiles which gives the 99 cuts points that separate *data* in to 100 equal sized groups. The *data* can be any iterable containing sample. The cut points are linearly interpolated between data points. If *method* is set to *inclusive*, *data* is treated as population data. The minimum value is treated as the 0th percentile and the maximum value is treated as the 100th percentile. r4zn must be at least 1r}z"must have at least two data points inclusiverzUnknown method: )rrrrangedivmodappendrm) rGr:rldrwresultrrdelta interpolateds r2rrs  1uu4555 $<>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] >>> variance(data) 1.3720238095238095 If you have already calculated the mean of your data, you can pass it as the optional second argument ``xbar`` to avoid recalculating it: >>> m = mean(data) >>> variance(data, m) 1.3720238095238095 This function does not check that ``xbar`` is actually the mean of ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or impossible results. Decimals and Fractions are supported: >>> from decimal import Decimal as D >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) Decimal('31.01875') >>> from fractions import Fraction as F >>> variance([F(1, 6), F(1, 2), F(5, 3)]) Fraction(67, 108) r}z*variance requires at least two data pointsr4r]rrr)rGxbarrPssrUr:s r2rr6sJLdD//KAr1a1uuJKKK B!a%L! $ $$r1c|t||\}}}}|dkrtdt||z |S)a,Return the population variance of ``data``. data should be a sequence or iterable of Real-valued numbers, with at least one value. The optional argument mu, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the ``variance`` function is usually a better choice. Examples: >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25] >>> pvariance(data) 1.25 If you have already calculated the mean of the data, you can pass it as the optional second argument to avoid recalculating it: >>> mu = mean(data) >>> pvariance(data, mu) 1.25 Decimals and Fractions are supported: >>> from decimal import Decimal as D >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) Decimal('24.815') >>> from fractions import Fraction as F >>> pvariance([F(1, 4), F(5, 4), F(1, 2)]) Fraction(13, 72) r4z*pvariance requires at least one data pointr)rGmurPrrUr:s r2rrbsFFdB--KAr1a1uuJKKK BFA  r1ct||\}}}}|dkrtd||dz z }t|trt |j|jSt|j|jS)zReturn the square root of the sample variance. See ``variance`` for arguments and other details. >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]) 1.0810874155219827 r}'stdev requires at least two data pointsr4r]rrerrrnror)rGrrPrrUr:msss r2rrsydD//KAr1a1uuGHHH A,C!WE$S]CODDD s}co > >>r1ct||\}}}}|dkrtd||z }t|trt |j|jSt|j|jS)zReturn the square root of the population variance. See ``pvariance`` for arguments and other details. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]) 0.986893273527251 r4z'pstdev requires at least one data pointr)rGrrPrrUr:rs r2rrsudB--KAr1a1uuGHHH q&C!WE$S]CODDD s}co > >>r1c4t|\}}}}|dkrtd||dz z } t|t|j|jfS#t $r1t|t|t|z fcYSwxYw)zFIn one pass, compute the mean and sample standard deviation as floats.r}rr4)r]rrfrrnror`)rGrPrrr:rs r2 _mean_stdevrsYYNAr41uuGHHH A,C4T{{/ sOOOO 444T{{E$KK%))333334s(A8BBc>t|}t||krtd|dkrtdt||z t||z tfdt||D}||dz z S)apCovariance Return the sample covariance of two inputs *x* and *y*. Covariance is a measure of the joint variability of two inputs. >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> covariance(x, y) 0.75 >>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> covariance(x, z) -7.5 >>> covariance(z, x) -7.5 zDcovariance requires that both inputs have same number of data pointsr}z,covariance requires at least two data pointsc34K|]\}}|z |z zVdSr6r0r8xiyirybars r2r;zcovariance..4AAVRT b4i(AAAAAAr1r4)rrr%r)rTyr:sxyrrs @@r2rrs" AA 1vv{{deee1uuLMMM 77Q;D 77Q;D AAAAAs1ayyAAA A AC !a%=r1ct|}t||krtd|dkrtdt||z t||z tfdt||D}tfd|D}tfd|D} |t ||zz S#t $rtdwxYw)aPearson's correlation coefficient Return the Pearson's correlation coefficient for two inputs. Pearson's correlation coefficient *r* takes values between -1 and +1. It measures the strength and direction of the linear relationship, where +1 means very strong, positive linear relationship, -1 very strong, negative linear relationship, and 0 no linear relationship. >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> correlation(x, x) 1.0 >>> correlation(x, y) -1.0 zEcorrelation requires that both inputs have same number of data pointsr}z-correlation requires at least two data pointsc34K|]\}}|z |z zVdSr6r0rs r2r;zcorrelation..rr1c3,K|]}|z xzVdSr6r0r8rr9rs r2r;zcorrelation..000R$Y!#000000r1c3,K|]}|z xzVdSr6r0)r8rr9rs r2r;zcorrelation..rr1z&at least one of the inputs is constant)rrr%rrr) rTrr:rr\syyr9rrs @@@r2rrs&" AA 1vv{{efff1uuMNNN 77Q;D 77Q;D AAAAAs1ayyAAA A AC 00000a000 0 0C 00000a000 0 0CHT#)__$$ HHHFGGGHs C&&DLinearRegressionslope interceptF) proportionalcp t|}t||krtd|dkrtd|rAtdt||D}td|D}njt||z t||z t fdt||D}t fd|D} ||z }n#t$rtdwxYw|rd n | zz }t || S) aSlope and intercept for simple linear regression. Return the slope and intercept of simple linear regression parameters estimated using ordinary least squares. Simple linear regression describes relationship between an independent variable *x* and a dependent variable *y* in terms of a linear function: y = slope * x + intercept + noise where *slope* and *intercept* are the regression parameters that are estimated, and noise represents the variability of the data that was not explained by the linear regression (it is equal to the difference between predicted and actual values of the dependent variable). The parameters are returned as a named tuple. >>> x = [1, 2, 3, 4, 5] >>> noise = NormalDist().samples(5, seed=42) >>> y = [3 * x[i] + 2 + noise[i] for i in range(5)] >>> linear_regression(x, y) #doctest: +ELLIPSIS LinearRegression(slope=3.09078914170..., intercept=1.75684970486...) If *proportional* is true, the independent variable *x* and the dependent variable *y* are assumed to be directly proportional. The data is fit to a line passing through the origin. Since the *intercept* will always be 0.0, the underlying linear function simplifies to: y = slope * x + noise >>> y = [3 * x[i] + noise[i] for i in range(5)] >>> linear_regression(x, y, proportional=True) #doctest: +ELLIPSIS LinearRegression(slope=3.02447542484..., intercept=0.0) zKlinear regression requires that both inputs have same number of data pointsr}z3linear regression requires at least two data pointsc3&K|] \}}||zV dSr6r0)r8rrs r2r;z$linear_regression../s*33vr227333333r1c3 K|] }||zV dSr6r0)r8rs r2r;z$linear_regression..0s&''r27''''''r1c34K|]\}}|z |z zVdSr6r0rs r2r;z$linear_regression..4s4EERBI"t),EEEEEEr1c3,K|]}|z xzVdSr6r0rs r2r;z$linear_regression..5s044BdNAa'444444r1z x is constantr)rrr%rrr) rTrrr:rr\rrr9rrs @@@r2r r sfL AA 1vv{{klll1uuSTTT533Q33333''Q'''''Aww{Aww{EEEEE3q!99EEEEE44444!44444/c  ///o.../#< )>Dc|dz }t|dkrpd||zz }d|zdz|zdz|zdz|zdz|zd z|zd z|zd z|z}d |zd z|zdz|zdz|zdz|zdz|zdz|zdz}||z }|||zzS|dkr|nd|z }tt| }|dkr^|dz }d|zdz|zdz|zdz|zdz|zdz|zdz|zdz}d|zd z|zd!z|zd"z|zd#z|zd$z|zd%z|zdz}n]|dz }d&|zd'z|zd(z|zd)z|zd*z|zd+z|zd,z|zd-z}d.|zd/z|zd0z|zd1z|zd2z|zd3z|zd4z|zdz}||z }|dkr| }|||zzS)5N?g333333?gQ?g^}o)@gE.kR@g Ul@g*u>l@gN@g"]Ξ@gnC`@gu @giK~j@gv|E@gd|1@gfRr@gu.2@g~y@gn8(E@rrg@g?g鬷ZaI?ggElD?g7\?guSS?g=. @gj%b@gHw@gjRe?g9dh? >g('߿A?g~z ?g@3?gɅ3?g3fRx?gIFl@gt>g*Yn>gESB\T?gN;A+?gUR1?gEF?gPn@g&>@gigtcI,\>gŝI?g*F2v?gC4?gO1?)r rr$)prsigmarrrrrTs r2_normal_dist_inv_cdfrAs CA Aww% q1u 0140145601456115661 156 6 1 1 56 6 1 1 56 6115661140145601456115661 156 6 1 1 56 6 1 1 56 6 #IQY #XX37A c!ffW ACxx G1A51256712567226772 267 7 2 2 67 7 2 2 67 7222A51256712567226772 267 7 2 2 67 7 2 2 67 7 G1A51256712567226772 267 7 2 2 67 7 2 2 67 7223Q61256712567226772 267 7 2 2 67 7 2 2 67 7 c A3ww B U r1)rc*eZdZdZdddZd$dZedZd d d Zd Z d Z dZ d%dZ dZ dZedZedZedZedZedZdZdZdZdZdZdZeZdZeZdZd Zd!Z d"Z!d#Z"d S)&rz(Normal distribution of a random variablez(Arithmetic mean of a normal distributionz+Standard deviation of a normal distribution_mu_sigmarrc|dkrtdt||_t||_dS)zDNormalDist where mu is the mean and sigma is the standard deviation.rzsigma must be non-negativeN)rrfrr)selfrrs r2__init__zNormalDist.__init__s8 3;;!">?? ?99Ell r1c&|t|S)z5Make a normal distribution instance from sample data.)r)clsrGs r2 from_sampleszNormalDist.from_samplesssK%%&&r1N)seedc| tjntj|j|j|jcfdt |DS)z=Generate *n* samples for a given mean and standard deviation.Nc(g|]}Sr0r0)r8rgaussrrs r2rz&NormalDist.samples..s%333Qb%  333r1)randomr Randomrrr)rr:r r rrs @@@r2sampleszNormalDist.samplessV $  &-2E2E2KHdk E333333%((3333r1c|j|jz}|std||jz }t||zd|zz t t |zz S)z4Probability density function. P(x <= X < x+dx) / dxz$pdf() not defined when sigma is zerog)rrrr!rr#)rrTrdiffs r2pdfzNormalDist.pdfs_;, J!"HII I48|4$;$/233d3>6J6JJJr1c|jstdddt||jz |jtzz zzS)z,Cumulative distribution function. P(X <= x)z$cdf() not defined when sigma is zerorr)rrr"r_SQRT2rrTs r2cdfzNormalDist.cdfsF{ J!"HII IcCTX$+2F GHHHIIr1c|dks|dkrtd|jdkrtdt||j|jS)aSInverse cumulative distribution function. x : P(X <= x) = p Finds the value of the random variable such that the probability of the variable being less than or equal to that value equals the given probability. This function is also called the percent point function or quantile function. rrz$p must be in the range 0.0 < p < 1.0z-cdf() not defined when sigma at or below zero)rrrr)rrs r2inv_cdfzNormalDist.inv_cdfsV 88qCxx!"HII I ;#  !"QRR R#Atx===r1rc@fdtdDS)anDivide into *n* continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. Set *n* to 100 for percentiles which gives the 99 cuts points that separate the normal distribution in to 100 equal sized groups. c@g|]}|z Sr0)r)r8rr:rs r2rz(NormalDist.quantiles..s)999 QU##999r1r4)r)rr:s``r2rzNormalDist.quantiless+:9999U1a[[9999r1c  t|tstd||}}|j|jf|j|jfkr||}}|j|j}}|r|st d||z }t|j|jz }|s%dt|d|jztzz z S|j|z|j|zz }|j|jzt||z|t||z zzz} || z|z } || z |z } dt| | | | z t| | | | z zz S)aCompute the overlapping coefficient (OVL) between two normal distributions. Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area in the two underlying probability density functions. >>> N1 = NormalDist(2.4, 1.6) >>> N2 = NormalDist(3.2, 2.0) >>> N1.overlap(N2) 0.8035050657330205 z$Expected another NormalDist instancez(overlap() not defined when sigma is zerorr+) rrrgrrrrr r"rrr$r) rotherXYX_varY_vardvrr{bx1x2s r2overlapzNormalDist.overlaps %,, DBCC CU1 Hae !%0 0 0aqAz1:u NE N!"LMM M U] !%!%-  =R3>F#:;<<< < EEMAEEM ) Hqx $rBwc%%-6H6H1H'H"I"I I!er\!er\d15599quuRyy011DrQUU2YY9N4O4OOPPr1cR|jstd||jz |jz S)zCompute the Standard Score. (x - mean) / stdev Describes *x* in terms of the number of standard deviations above or below the mean of the normal distribution. z'zscore() not defined when sigma is zero)rrrrs r2zscorezNormalDist.zscores1{ M!"KLL LDH  ++r1c|jS)z+Arithmetic mean of the normal distribution.rrs r2r zNormalDist.mean xr1c|jS)z,Return the median of the normal distributionr)r*s r2r zNormalDist.median r+r1c|jS)zReturn the mode of the normal distribution The mode is the value x where which the probability density function (pdf) takes its maximum value. r)r*s r2rzNormalDist.modes xr1c|jS)z.Standard deviation of the normal distribution.rr*s r2rzNormalDist.stdevs {r1c |j|jzS)z!Square of the standard deviation.r/r*s r2rzNormalDist.variances{T[((r1ct|tr5t|j|jzt|j|jSt|j|z|jS)ajAdd a constant or another NormalDist instance. If *other* is a constant, translate mu by the constant, leaving sigma unchanged. If *other* is a NormalDist, add both the means and the variances. Mathematically, this works only if the two distributions are independent or if they are jointly normally distributed. rrrrrr#r$s r2__add__zNormalDist.__add__!U b* % % LbfrvouRY /J/JKK K"&2+ry111r1ct|tr5t|j|jz t|j|jSt|j|z |jS)asSubtract a constant or another NormalDist instance. If *other* is a constant, translate by the constant mu, leaving sigma unchanged. If *other* is a NormalDist, subtract the means and add the variances. Mathematically, this works only if the two distributions are independent or if they are jointly normally distributed. r2r3s r2__sub__zNormalDist.__sub__/r5r1c\t|j|z|jt|zS)zMultiply both mu and sigma by a constant. Used for rescaling, perhaps to change measurement units. Sigma is scaled with the absolute value of the constant. rrrr r3s r2__mul__zNormalDist.__mul__=' "&2+ry488';<<>> : : : : Q Q QD , , ,XXXX))X) 2 2 2 2 2 2======---...HH;;; ---PPP%%%&&&&&r1rr6)rs)r)KrT__all__rarr sys fractionsrdecimalr itertoolsrrbisectrrrrr r!r"r#r$r% functoolsr&operatorr' collectionsr(r)r*rrmrrQr]rBrErArrrvrFr| float_infomant_digr__annotations__rfrrr rrrr rr r rrrrrrrrrrrr r _statistics ImportErrorrr0r1r2rhshhhT   .  %%%%%%%%,,,,,,,,<<<<<<<<<<<<<<<<<<<<8888888888 c     j   333l&&&&R   444>+++\$3>22Q6666 #3 #3 #5 # # # #SSW<""",####LGGG&5,5,5,5,p+++0   ,&E+E+E+E+PBBB<KKKr;(4(4(4(4(4b)%)%)%)%X&&&&R????$????$ 4 4 4(8HHHB:02HII058>8>8>8>8>|GGGV 0000000   D \&\&\&\&\&\&\&\&\&\&sD!!D)(D)