\d}tdZddlmZddlmZmZm Z m Z m ZddlmZmZmZmZddlmZmZmZddlmZddl m!Z"m#Z$ddl%m&Z'dd l(m)Z*m+Z,dd l-m-Z.dd lZ/dd l0Z0 dd l1m2Z1n#e3$r dd l4m2Z1YnwxYwgd Z5dedzedz Z6edZ7dedzZ8dZ9de9 zZ:dZ;Gdde0j<Z<Gdde<Z=e<Z>e>j?Z?e>j@Z@e>jAZAe>jBZBe>jCZCe>jDZDe>jEZEe>jFZFe>jGZGe>jHZHe>jIZIe>jJZJe>jKZKe>jLZLe>jMZMe>jNZNe>jOZOe>jPZPe>jQZQe>jRZRe>jSZSe>jTZTe>jUZUdZVd!dZWeXe/dre/jYe>j?eZd kr eWd Sd S)"aRandom variable generators. bytes ----- uniform bytes (values between 0 and 255) integers -------- uniform within range sequences --------- pick random element pick random sample pick weighted random sample generate random permutation distributions on the real line: ------------------------------ uniform triangular normal (Gaussian) lognormal negative exponential gamma beta pareto Weibull distributions on the circle (angles 0 to 2pi) --------------------------------------------- circular uniform von Mises General notes on the underlying Mersenne Twister core generator: * The period is 2**19937-1. * It is one of the most extensively tested generators in existence. * The random() method is implemented in C, executes in a single Python step, and is, therefore, threadsafe. )warn)logexppieceil)sqrtacoscossin)taufloorisfinite)urandom)SetSequence)index) accumulaterepeat)bisectN)sha512)Random SystemRandom betavariatechoicechoices expovariate gammavariategauss getrandbitsgetstatelognormvariate normalvariate paretovariate randbytesrandintrandom randrangesampleseedsetstateshuffle triangularuniformvonmisesvariateweibullvariateg@@?@5ceZdZdZdZd&dZd'fd ZfdZfdZd Z d Z d Z d Z d Z dezfdZe ZdZdefdZdZdZdZdddZd&ddddZdZd(dZd)dZd)dZdZd Zd!Zd"Z d#Z!d$Z"d%Z#xZ$S)*raRandom number generator base class used by bound module functions. Used to instantiate instances of Random to get generators that don't share state. Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the following methods: random(), seed(), getstate(), and setstate(). Optionally, implement a getrandbits() method so that randrange() can cover arbitrarily large ranges. Nc>||d|_dS)zeInitialize an instance. Optional argument x controls seeding, as for Random.seed(). N)r* gauss_next)selfxs ..\python\lib\random.py__init__zRandom.__init__ws ! r7c ^|dkrt|ttfrt|tr|dn|}|rt |ddznd}t t|D] }d|z|z dz}|t |z}|dkrdn|}n|d krt|tttfrft|tr|}t |t| z}nKt|td tttttfstd t!|d |_d S) a\Initialize internal state from a seed. The only supported seed types are None, int, float, str, bytes, and bytearray. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds. r8zlatin-1riCBlr7NzOThe only supported seed types are: None, int, float, str, bytes, and bytearray.) isinstancestrbytesdecodeordmaplen bytearrayencodeint from_bytes_sha512digesttypefloat TypeErrorsuperr*r<)r=aversionr>c __class__s r?r*z Random.seedsx$ a<s r? z"Random.setstate..s&%K%Ka7m%K%K%K%K%K%KrANzstate with version z( passed to Random.setstate() of version )r<rVr+tuple ValueErrorrUr\)r=staterX internalstaterrZs r?r+zRandom.setstates( a<<6; 3G]DO GG  ] + + + + + \\6; 3G]DO  ' %%K%K]%K%K%K K K  ' ' 'Q& ' GG  ] + + + + +*%ggt||566 6sA** B4A<<Bc*|SN)r!r=s r? __getstate__zRandom.__getstate__s}}rAc0||dSrg)r+)r=rds r? __setstate__zRandom.__setstate__s erAc:|jd|fS)Nr_)rZr!rhs r? __reduce__zRandom.__reduce__s~r4==??22rAc |jD]>}d|jvrdSd|jvr|j|_dSd|jvr|j|_dS?dS)aControl how subclasses generate random integers. The algorithm a subclass can use depends on the random() and/or getrandbits() implementation available to it and determines whether it can generate random integers from arbitrarily large ranges. _randbelowr r'N)__mro____dict___randbelow_with_getrandbitsro_randbelow_without_getrandbits)clskwargsrYs r?__init_subclass__zRandom.__init_subclass__st  Aqz)) **!$!@1:%%!$!C&  rAc|j}|}||}||kr||}||k|S)z;Return a random int in the range [0,n). Defined for n > 0.)r bit_length)r=nr krs r?rrz"Random._randbelow_with_getrandbitssL& LLNN KNN1ff AA1ffrAr8c|j}||kr)tdt||zS||z}||z |z }|}||kr|}||kt||z|zS)zReturn a random int in the range [0,n). Defined for n > 0. The implementation does not use getrandbits, but only random. zUnderlying random() generator does not supply enough bits to choose from a population range this large. To remove the range limitation, add a getrandbits() method.)r'_warn_floor)r=rymaxsizer'remlimitr{s r?rsz%Random._randbelow_without_getrandbitss  << N O O O&&((Q,'' 'k3') FHH5jjA5jja'k""Q&&rAcZ||dz|dS)Generate n random bytes.little)r to_bytesr=rys r?r%zRandom.randbytess*A&&//8<< randbelowijs r?r,zRandom.shufflexslO %3q66**++ $ $A !a%  A1qtJAaD!A$$ $ $rA)countscttstdt}|t t |t|krt d}t|tstd|dkrt d| t||}tfd|DS|j }d|cxkr|ksnt d dg|z}d } |d kr&| d tt|d zd zz } || krLt } t|D],} ||| z } | | || <| || z dz | | <-n[t} | j}t|D]6} ||} | | vr||} | | v|| | || <7|S)afChooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. Repeated elements can be specified one at a time or with the optional counts parameter. For example: sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to: sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5) To choose a sample from a range of integers, use range() for the population argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) zAPopulation must be a sequence. For dicts or sets, use sorted(d).Nz2The number of counts does not match the populationzCounts must be integersrz)Total of counts must be greater than zero)rzc4g|]}|Sr_r_)r`sr cum_counts populations r? z!Random.sample..s*JJJ!Jvvj!445JJJrAz,Sample larger than population or is negativer1r:r8)rF _SequencerUrLlist _accumulatercpoprOr)r_bisectro_ceil_logsetadd)r=rrzrrytotal selectionsrresultsetsizepoolrrselected selected_addrrs ` @@r?r)z Random.samplesLj*i00 A@AA A  OO  k&1122J:!## !UVVVNN$$EeS)) ; 9:::zz !LMMMU5\\Q77JFJJJJJJzJJJ JO A{{{{{{{{KLL L! q55 qE$q1ua..111 1G << ##D1XX * *Ia!e$$ Gq q1uqy/Q * uuH#.s2RRRA 55A#6#67RRRrAz4The number of choices must be a keyword argument: k=z2Cannot specify both weights and cumulative weightsz3The number of weights does not match the populationrDz*Total of weights must be greater than zerozTotal of weights must be finiter8c Ng|]!}zd"S)rr_)r`rrrhirr'rs r?rz"Random.choices..sI+++66+vvxx%/?BGGH+++rA) r'rLr~_repeatrrrUrFrOrc _isfiniter) r=rweightsrrzrrrryr'rs ` ` @@@@@@r?rzRandom.choicess  OO  SRRRRRRRqAQAQRRRR ";w#7#788    !'3//MMM   PQQ Q {  q RSS SB#% C<<IJJ J @>?? ? U+++++++++ q))+++ +s A,,6B"c<|||z |zzS)zHGet a random number in the range [a, b) or [a, b] depending on rounding.r'rs r?r.zRandom.uniformsAET[[]]***rArr4c|} |dn ||z ||z z }n#t$r|cYSwxYw||krd|z }d|z }||}}|||z t||zzzS)zTriangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution N?r4)r'ZeroDivisionError_sqrt)r=lowhighmodeurYs r?r-zRandom.triangular s KKMM |$*)DAA    JJJ  q55aAaAcCdSjE!a%LL000s & 55c|j} |}d|z }t|dz z|z }||zdz }|t| krnE|||zzS)z\Normal distribution. mu is the mean, and sigma is the standard deviation. Tr4rr3)r' NV_MAGICCONSTr)r=musigmar'u1u2zzzs r?r#zRandom.normalvariate ss BvvxxBc*R/AQBd2hhY  AI~rAc |j}|j}d|_|e|tz}tdt d|z z}t ||z}t ||z|_|||zzS)zGaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. Ngr4)r'r<TWOPIrr_cos_sin)r=rrr'rx2pig2rads r?rz Random.gauss5s6 O 9688e#D$cFFHHn!5!5566ET U"A"4jj50DOAI~rAcHt|||S)zLog normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero. )_expr#)r=rrs r?r"zRandom.lognormvariate[s"D&&r511222rAcRtd|z  |z S)a^Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative. r4)rr')r=lambds r?rzRandom.expovariatees'S4;;==()))E11rAc|j}|dkrt|zSd|z }|td||zzz} |}tt|z}|||zz }|} | d||zz ks| d|z t |zkrnZd|z } | |zd| |zzz } |} | dkr|t | ztz} n|t | z tz} | S)aFCircular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. gư>rr4)r'rrr_pir_acos)r=rkappar'rr{rrdrqfu3thetas r?r/zRandom.vonmisesvariatevs  D==6688# # %K cAEk"" " BS2XAQU ABC!a%K2#'T!WW)<#<#<  !G UsQU{ # VXX 88%((]e+EE%((]e+E rAc|dks|dkrtd|j}|dkrtd|zdz }|tz }||z} |}d|cxkrdksnd|z }t |d|z z |z } |t | z} ||z|z} ||| zz| z } | t zd| zz dks| t | kr| |zS|dkrt d|z  |zS |} t|ztz }|| z}|dkr |d|z z} nt ||z |z  } |}|dkr|| |dz zkrnn|t | krnz| |zS) aZGamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is: x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha rz*gammavariate: alpha and beta must be > 0.0r4r2TgHz>gP?r5)rcr'rLOG4rr SG_MAGICCONST_e)r=alphabetar'ainvbbbcccrrvr>rr{rrps r?rzRandom.gammavariates C<<43;;IJJ J 3;; us*++D$,C$,C $VXXb,,,,9,,,,6688^sRx))D0DGGOGbL#'MA%}$sQw.#55d1ggt8O $c\\vvxx(((4/ / FHH%Z2%E88cEk*AAq1uo...AVXXs77Q53;///0488^^ t8OrAcn||d}|r||||dzz SdS)zBeta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. r4r)r)r=rrys r?rzRandom.betavariatesF,   eS ) )  :D--dC8889 9srAc@d|z }|d|z zS)z3Pareto distribution. alpha is the shape parameter.r4gr)r=rrs r?r$zRandom.paretovariates% $++-- TE\""rAcbd|z }|t| d|z zzS)zfWeibull distribution. alpha is the scale parameter and beta is the shape parameter. r4)r'r)r=rrrs r?r0zRandom.weibullvariates2 $++-- acDj111rArg)Nr7)rr4Nrr4)%__name__ __module__ __qualname____doc__r\r@r*r!r+rirkrmrvrrBPFrsror%rr(r&rr,r)rr.r-r#rr"rr/rrr$r0 __classcell__)rZs@r?rrgsd  G$$$$$$LAAAAA66666B333 (9:3''''&-J===%)tH3H3H3H3T&&&...$$$/3]]]]]~#+tq#+#+#+#+#+P+++1111(*$$$$L333222"(((T???B6### 2 2 2 2 2 2 2rArc8eZdZdZdZdZdZdZdZexZ Z dS)rzAlternate random number generator using sources provided by the operating system (such as /dev/urandom on Unix or CryptGenRandom on Windows). Not available on all systems (see os.urandom() for details). cfttddz tzS)z7Get the next random number in the range 0.0 <= X < 1.0.rCr:)rOrP_urandom RECIP_BPFrhs r?r'zSystemRandom.randoms$x{{++q0I==rAc|dkrtd|dzdz}tt|}||dz|z z S)z:getrandbits(k) -> x. Generates an int with k random bits.rz#number of bits must be non-negativerCr)rcrOrPr)r=rznumbytesr>s r?r zSystemRandom.getrandbits sT q55BCC CEa< NN8H-- . .X\A%&&rAc t|S)r)rrs r?r%zSystemRandom.randbytes(s{{rAcdS)z>>''' PPP*)HxxxrArc^ddlm}m}ddlm}|}fdt d|D}|}||} ||| } t |} t|} t||z dd|dj td| | | | fzdS) Nr)stdevfmean) perf_countercg|]}Sr_r_)r`rrfuncs r?rz#_test_generator..as 2 2 2ADD$K 2 2 2rAz.3fz sec, z times z"avg %g, stddev %g, min %g, max %g ) statisticsr r timer rminmaxprintr) ryrrr meanr t0datat1xbarrrrs `` r?_test_generatorr\s////////!!!!!! B 2 2 2 2 2q!1!1 2 2 2D B 4::D E$  E d))C t99D R"W 9 9 9 9 9$- 9 9::: /4T2J JKKKKKrAct|tdt|tdt|tdt|tdt|t dt|t dt|t dt|t dt|t dt|t dt|t d t|t d t|t d t|t dt|td t|td dS)Nr_r)g{Gz?r4)皙?r4)rr2)rr4)g?r4)r4r4)r2r4)g4@r4)gi@r4)@r)rr4gUUUUUU?) rr'r#r"r/rrrr-)Ns r?_testr ms)Avr"""A}j111A~z222A 333A|[111A|Z000A|Z000A|Z000A|Z000A|Z000A|Z000A|[111A|\222Auj)))A{J///Az#899999rAfork)after_in_child__main__)r)[rwarningsrr}mathrrrrrrrrrrr rr rr rr rr rrr~rrosrr_collections_abcr_Setrroperatorrr itertoolsrrrrrr_os_randomrQr ImportErrorhashlib__all__rrrrrrrr_instr*r'r.r-r&rr(r)r,rr#r"rr/rrrr$r0r!r+r r%rr hasattrregister_at_forkrr_rAr?r3sL))^#"""""LLLLLLLLLLLLLLGGGGGGGGGGGGEEEEEEEEEE""""""????????$$$$$$BBBBBBBB$$$$$$*)))))))***))))))))*   8DDJJs+  tCyydd3ii  #I e 2e 2e 2e 2e 2W^e 2e 2e 2X"*"*"*"*"*6"*"*"*X  z  -   -  O  - -# % '!   # % > > O LLL"::::, 734C 3333 z EGGGGGsA A-,A-