Qf{^dZddlmZddlmZmZm Z m Z m ZddlmZmZmZmZddlmZmZmZddlmZmZ m!Z"ddl#m$Z%ddl&m'Z(dd l)m*Z+dd l,m-Z.m/Z0dd l1m1Z2dd l#Z3dd l4Z4 dd l5m6Z7gdZ:dedzedz Z;edZde> zZ?dZ@Gdde4jZAGddeAZBeAZCeCjZDeCjZEeCjZFeCjZGeCjZHeCjZIeCjZJeCjZKeCjZLeCjZMeCjZNeCjZOeCjZPeCjZQeCjZReCjZSeCjZTeCjZUeCjZVeCjZWeCjZXeCjZYeCjZZeCjZ[dZ\d!dZ]e^e3dre3jeCje`d k(re]y y #e8$r dd l9m6Z7YwxYw)"aERandom 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 discrete distributions ---------------------- binomial 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)lgammafabslog2)urandom)Sequence)index) accumulaterepeat)bisectN)sha512)Random SystemRandom betavariatebinomialvariatechoicechoices expovariate gammavariategauss getrandbitsgetstatelognormvariate normalvariate paretovariate randbytesrandintrandom randrangesampleseedsetstateshuffle triangularuniformvonmisesvariateweibullvariateg@@?@5ceZdZdZdZd$dZd%fd ZfdZfdZdZ d Z d Z d Z d Z d ezfdZe ZdZdefdZdZdZdZdddZd$dd ddZdZd&dZd'dZd'dZdZd(dZdZdZ d Z!d!Z"d"Z#d)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. Nc4|j|d|_y)zeInitialize an instance. Optional argument x controls seeding, as for Random.seed(). N)r- gauss_next)selfxs -/opt/alt/python312/lib64/python3.12/random.py__init__zRandom.__init__~s ! c |dk(rt|ttfrpt|tr|jdn|}|rt |ddznd}t t|D] }d|z|z dz}|t |z}|dk(rdn|}n|d k(rkt|tttfrPt|tr|j}tj|t|jz}n:t|td tttttfs td t |E|d |_y ) 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. r;zlatin-1riCBlr:NzOThe only supported seed types are: None, int, float, str, bytes, and bytearray.) isinstancestrbytesdecodeordmaplen bytearrayencodeint from_bytes_sha512digesttypefloat TypeErrorsuperr-r?)r@aversionrAc __class__s rBr-z Random.seeds$ az"Random.setstate..s%K]a7m]sNzstate with version z( passed to Random.setstate() of version )r?rYr.tuple ValueErrorrXr_)r@stater[ internalstaterr]s rBr.zRandom.setstates( a<6; 3G]DO G ] + \6; 3G]DO  ' %%K]%K K  G ] +%t||56 6  'Q& 'sA55 B >BB c"|jSN)r$r@s rB __getstate__zRandom.__getstate__s}}rDc&|j|yrj)r.)r@rgs rB __setstate__zRandom.__setstate__s erDc<|jd|jfS)Nrb)r]r$rks rB __reduce__zRandom.__reduce__s~~r4==?22rDc |jD]T}d|jvryd|jvr|j|_yd|jvsC|j|_yy)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_getrandbitsrr_randbelow_without_getrandbits)clskwargsr\s rB__init_subclass__zRandom.__init_subclass__sYAqzz) *!$!@!@1::%!$!C!CrDct|j}|j}||}||k\r||}||k\r|S)z;Return a random int in the range [0,n). Defined for n > 0.)r# bit_length)r@nr#krs rBruz"Random._randbelow_with_getrandbitssA&& LLN N1fAA1frDr;c|j}||k\rtdt||zS||z}||z |z }|}||k\r |}||k\r t||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@r|maxsizer*remlimitr~s rBrvz%Random._randbelow_without_getrandbitss  < N O&(Q,' 'k3') H5jA5ja'k"Q&&rDcJ|j|dzj|dS)Generate n random bytes.little)r#to_bytesr@r|s rBr(zRandom.randbytess$A&//8<t |} t|D]#}| ||z }| || |<| ||z d z | |<%| St}|j }t|D]+}| |}||vr | |}||vr ||||| |<-| Scc} w)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)r}z,Sample larger than population or is negativer4r=r;)rI _SequencerXrOlist _accumulaterfpoprRr,r_bisectrr_ceil_logsetadd)r@ populationr}rr| cum_countstotal selectionsrsrresultsetsizepoolrrselected selected_adds rBr,z Random.samplegsj*i0@A A  O  k&12J:!# !UVVNN$EeS) 9::z !LMMU5\Q7JF?IJz!Jvj!45zJ JOO A{{KL LKL L! q5 qE$q1ua.11 1G < #D1Xa!e$ Gq q1uqy/Q uH#<? ? U q)+)A6+vx%/?BGH)+ ++S !'3/KM  $+sC5C:D):,D&c4|||z |jzzS)zGet a random number in the range [a, b) or [a, b] depending on rounding. The mean (expected value) and variance of the random variable are: E[X] = (a + b) / 2 Var[X] = (b - a) ** 2 / 12 r*rs rBr1zRandom.uniformsAET[[]***rDc|j} |dn ||z ||z z }||kDrd|z }d|z }||}}|||z t||zzzS#t$r|cYSwxYw)aTriangular 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 The mean (expected value) and variance of the random variable are: E[X] = (low + high + mode) / 3 Var[X] = (low**2 + high**2 + mode**2 - low*high - low*mode - high*mode) / 18 ?r7)r*ZeroDivisionError_sqrt)r@lowhighmodeur\s rBr0zRandom.triangulars KKM |$*)DA q5aAaAcCdSjE!a%L000 ! J sA AAc|j} |}d|z }t|dz z|z }||zdz }|t| krn9|||zzS)z\Normal distribution. mu is the mean, and sigma is the standard deviation. r7rr6)r* NV_MAGICCONSTr)r@musigmar*u1u2zzzs rBr&zRandom.normalvariatesgBvxBc*R/AQBd2hY AI~rDc|j}|j}d|_|N|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. Ngr7)r*r?TWOPIrr_cos_sin)r@rrr*rx2pig2rads rBr"z Random.gauss'st6 OO 98e#D$cFHn!556ET U"A"4j50DOAI~rDc8t|j||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 rBr%zRandom.lognormvariateMsD&&r5122rDcBtd|jz  |z S)aExponential 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. The mean (expected value) and variance of the random variable are: E[X] = 1 / lambd Var[X] = 1 / lambd ** 2 r7)rr*)r@lambds rBr zRandom.expovariateWs"$S4;;=())E11rDc|j}|dkrt|zSd|z }|td||zzz} |}tt|z}|||zz }|} | d||zz ks| d|z t |zkrnId|z } | |zd| |zzz } |} | dkDr|t | ztz} | S|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ư>rr7)r*rrr_pir_acos)r@rkappar*rr~rrdrqfu3thetas rBr2zRandom.vonmisesvariateks  D=68# # %K cAEk" "BS2XAQU ABC!a%K2#'T!W)<#< !G UsQU{ # X 8%(]e+E %(]e+E rDc|dks|dkr td|j}|dkDrtd|zdz }|tz }||z} |}d|cxkrdksnd|z }t |d|z z |z } |t | z} ||z|z} ||| zz| z } | t zd| zz dk\s| t | k\r| |zSz|dk(rt d|z  |zS |} t|ztz }|| z}|dkr |d|z z} nt ||z |z  } |}|dkDr|| |dz zkr | |zS|t | kr | |zSo)aGamma 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 The mean (expected value) and variance of the random variable are: E[X] = alpha * beta Var[X] = alpha * beta ** 2 rz*gammavariate: alpha and beta must be > 0.0r7r5gHz>gP?r8)rfr*rLOG4rr SG_MAGICCONST_e)r@alphabetar*ainvbbbcccrrvrArr~rrps rBr!zRandom.gammavariates( C<43;IJ J 3; us*+D$,C$,CXb,9,68^sRx)D0DGOGbL#'MA%}$sQw.#5d1gt8Oc\vx((4/ / H%Z2%E8cEk*Aq1uo..AXs7Q53;//t8O48^t8OrDc\|j|d}|r|||j|dzz Sy)aQBeta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. The mean (expected value) and variance of the random variable are: E[X] = alpha / (alpha + beta) Var[X] = alpha * beta / ((alpha + beta)**2 * (alpha + beta + 1)) r7r)r!)r@rrys rBrzRandom.betavariates96   eS ) D--dC889 9rDc8d|jz }|d|z zS)z3Pareto distribution. alpha is the shape parameter.r7gr)r@rrs rBr'zRandom.paretovariates# $++- TE\""rDcRd|jz }|t| d|z zzS)zfWeibull distribution. alpha is the scale parameter and beta is the shape parameter. r7)r*r)r@rrrs rBr3zRandom.weibullvariates. $++- acDj111rDc|dkr td|dks|dk\r|dk(ry|dk(r|Std|j}|dk(rt||kS|dkDr||j|d|z z S||zdkrFdx}}t d|z }|s|S |t t ||z dzz }||kDr|S|dz }/d }t ||zd|z z}d d |zz} d d| zzd|zz} ||zdz}dd| z z } |} | dz} dt| z } t d| z| z | z| z|z}|dks||kDr@|}| dk\r|| kr|S|sOdd| z z|z}t|d|z z }t |dz|z}t|dzt||z dzz}d }|| | | zz | zz z}t|t|dzz t||z dzz |z zzkr|S)aBinomial random variable. Gives the number of successes for *n* independent trials with the probability of success in each trial being *p*: sum(random() < p for i in range(n)) Returns an integer in the range: 0 <= X <= n The mean (expected value) and variance of the random variable are: E[X] = n * p Var[x] = n * p * (1 - p) rzn must be non-negativerr7z&p must be in the range 0.0 <= p <= 1.0r;rg$@TFgffffff?g= ףp=@gEJYga+e?{Gz?gq= ףp?g@r5gQ?gp= ף@gffffff@) rfr*rr_log2rr_fabsr_lgamma)r@r|rr*rArr\setup_completespqrrZvrrusr}rrlpqmhs rBrzRandom.binomialvariates{" q556 6 8qCxCxCxEF F 6&(Q,' ' s7t++AsQw77 7 q54<IAcAgAVE&(Oa/0144q5HQ AES1W%& 4#:  fqj 4!8 + ECK C!G^A HAuQxBa" q(A-12A1uAATza2g "a3.1a=)AEQ;'AENWQUQY%77!% !rBw-!+, ,AAw!ga!en,wq1uqy/AAQUcMQQ5rDrj)Nr:)rr7Nrr7)r7)r;r)&__name__ __module__ __qualname____doc__r_rCr-r$r.rlrnrpryruBPFrvrrr(rr+r)rr/r,rr1r0r&r"r%r r2r!rr'r3r __classcell__)r]s@rBrrns G$LA6B3 (9:3'&-J=%)t'3R&.$/3]~#+tq#+P +12*$L32((TCJ@# 2VrDrc6eZdZdZdZdZdZdZdZexZ Z y)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). cRtjtddz tzS)z7Get the next random number in the range 0.0 <= X < 1.0.rFr=)rRrS_urandom RECIP_BPFrks rBr*zSystemRandom.randomusx{+q0I==rDc|dkr td|dzdz}tjt|}||dz|z z S)z:getrandbits(k) -> x. Generates an int with k random bits.rz#number of bits must be non-negativerFr)rfrRrSr )r@r}numbytesrAs rBr#zSystemRandom.getrandbitsysI q5BC CEa< NN8H- .X\A%&&rDct|S)r)r rs rBr(zSystemRandom.randbytess{rDcy)z' P*)HxrDrc6ddlm}m}ddlm}|}t d|Dcgc]}|| }}|} ||} ||| } t |} t|} t| |z dd|d|j|td| | | | fzycc}w)Nr)stdevfmean) perf_counterz.3fz sec, z times z"avg %g, stddev %g, min %g, max %g ) statisticsrrtimerrminmaxprintr)r|funcrrmeanrt0rdatat1xbarrrrs rB_test_generatorr$s/! B!(q!1 2!1AD$K!1D 2 B :D $ E d)C t9D R"WSMs'$-- AB /4T2J JK 3s Bcht|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 d t|t d t|tdt|tdt|tdy)Nrbr)g333333?)dg?)rr7)皙?r7)r(r5)rr7)g?r7)r7r7)r5r7)g4@r7)gi@r7)@r))rr7gUUUUUU?) r$r*r&r%r2rr!r"rr0)Ns rB_testr+sAvr"A}j1A~z2A 3A 3A 4A|[1A|Z0A|Z0A|Z0A|Z0A|Z0A|Z0A|[1A|\2Auj)A{J/Az#89rDfork)after_in_child__main__)i')arwarningsrrmathrrrrrrrrrrr rr rr rr rr rrrrrrrrrrrosrr _collections_abcrroperatorrr itertoolsrrrrrr_os_random_sha2rrT ImportErrorhashlib__all__rrrrr rrr_instr-r*r1r0r)rr+r,r/rr&r%r r2r!r"rrr'r3r$r.r#r(r$r+hasattrregister_at_forkrrbrDrBr>s.h#LLGGEE@@"2$B$*'  :DJs+  Cyd3i  #I w W^^w |"*6"*X  zz  --    --  OO  -- --## %% ''!!   ''## %% >> >> OO L":0 3C 3 z G}*))*s H H,+H,