U e5dp@sdZddlmZddlmZmZm Z m Z m ZddlmZmZmZmZddlmZddlmZmZddlm Z!m"Z#ddl$m$Z%dd lZ&zdd l'm(Z'Wn e)k rdd l*m(Z'YnXd d d ddddddddddddddddddd d!d"gZ+d#ed$ed%Z,d%e Z-ed&Z.d'ed(Z/d)Z0d*e0 Z1dd l2Z2Gd+d d e2j3Z3Gd,d"d"e3Z4d-d.Z5d5d0d1Z6e3Z7e7j8Z8e7j9Z9e7j:Z:e7j;Z;e7jZ>e7j?Z?e7j@Z@e7jAZAe7jBZBe7jCZCe7jDZDe7jEZEe7jFZFe7jGZGe7jHZHe7jIZIe7jJZJe7jKZKe7jLZLe7jMZMeNe&d2re&jOe7j8d3ePd4kre6d S)6aRandom variable generators. 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)urandom)SetSequence) accumulaterepeat)bisectN)sha512Randomseedrandomuniformrandintchoicesample randrangeshuffle normalvariatelognormvariate expovariatevonmisesvariate gammavariate triangulargauss betavariate paretovariateweibullvariategetstatesetstate getrandbitschoices SystemRandomg@@?@5cs$eZdZdZdZd?ddZddZd@fd d Zfd d Zfd dZ ddZ ddZ ddZ dde fddZddZddZe de>fddZeZddZdAd d!Zd"d#ZdBddd$d%d&Zd'd(ZdCd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Zd9d:Z d;d<Z!d=d>Z"Z#S)DraRandom 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. NcCs||d|_dS)zeInitialize an instance. Optional argument x controls seeding, as for Random.seed(). N)r gauss_next)selfxr6/usr/lib64/python3.8/random.py__init__^s zRandom.__init__cKsJ|jD]>}d|jkrqFd|jkr.|j|_qFd|jkr|j|_qFqdS)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(rN)__mro____dict___randbelow_with_getrandbitsr9_randbelow_without_getrandbits)clskwargscr6r6r7__init_subclass__gs    zRandom.__init_subclass__r1cs|dkrt|ttfrt|tr*|dn|}|rBt|dd>nd}tt|D]}d||Ad@}qP|t|N}|dkr~dn|}|d krt|tttfrt|tr|}|t | 7}t |d }t |d |_d S) aInitialize internal state from hashable object. 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. zlatin-1riCBlr1bigN) isinstancestrbytesdecodeordmaplen bytearrayencode_sha512Zdigestint from_bytessuperrr3)r4aversionr5r@ __class__r6r7r{s    z Random.seedcs|jt|jfS)z9Return internal state; can be passed to setstate() later.)VERSIONrSr&r3r4rVr6r7r&szRandom.getstatec s|d}|dkr*|\}}|_t|nt|dkr|\}}|_ztdd|D}Wn(tk r|}z t|W5d}~XYnXt|ntd||jfdS)z:Restore internal state from object returned by getstate().rr2r1css|]}|dVqdS)lNr6).0r5r6r6r7 sz"Random.setstate..Nz?state with version %s passed to Random.setstate() of version %s)r3rSr'tuple ValueError TypeErrorrX)r4staterUZ internalstaterrVr6r7r's  zRandom.setstatecCs|SN)r&rYr6r6r7 __getstate__szRandom.__getstate__cCs||dSr`)r')r4r_r6r6r7 __setstate__szRandom.__setstate__cCs|jd|fS)Nr6)rWr&rYr6r6r7 __reduce__szRandom.__reduce__rBc Cs||}||krtd|dkr:|dkr2||Std||}||krRtd||}|dkrx|dkrx|||S|dkrtd|||f||}||krtd|dkr||d|} n"|dkr||d|} ntd | dkrtd|||| S) zChoose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. z!non-integer arg 1 for randrange()Nrzempty range for randrange()z non-integer stop for randrange()rBz(empty range for randrange() (%d, %d, %d)z non-integer step for randrange()zzero step for randrange())r]r9) r4startstopstep_intZistartZistopwidthZistepnr6r6r7rs4  zRandom.randrangecCs|||dS)zJReturn random integer in range [a, b], including both end points. rB)rr4rTbr6r6r7rszRandom.randintcCs,|j}|}||}||kr(||}q|S)zCReturn a random int in the range [0,n). Raises ValueError if n==0.)r( bit_length)r4rir(krr6r6r7r<s  z"Random._randbelow_with_getrandbitscCsn|j}||kr$td|||S|dkr4td||}|||}|}||kr^|}qN||||S)zReturn a random int in the range [0,n). Raises ValueError if 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.rzBoundary cannot be zero)r_warnr])r4rirQmaxsizerZremlimitrnr6r6r7r=s z%Random._randbelow_without_getrandbitscCs:z|t|}Wntk r0tddYnX||S)z2Choose a random element from a non-empty sequence.z$Cannot choose from an empty sequenceN)r9rMr] IndexError)r4seqir6r6r7rs z Random.choicecCs|dkrN|j}ttdt|D]*}||d}||||||<||<q nHt}ttdt|D]0}|||d}||||||<||<qddS)zShuffle list x in place, and return None. Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used. NrB)r9reversedrangerMrQ)r4r5r randbelowrtjrgr6r6r7r%s  zRandom.shufflec Cst|trt|}t|ts$td|j}t|}d|krF|ksPntddg|}d}|dkr|dtt |dd7}||krt |}t |D]0}|||} || ||<|||d || <qnHt } | j } t |D]2}||} | | kr||} q| | || ||<q|S) a=Chooses k unique random elements from a population sequence or set. 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. To choose a sample in a range of integers, use range as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) z>Population must be a sequence or set. For dicts, use list(d).rz,Sample larger than population or is negativeNr+r2rB)rG_Setr\ _Sequencer^r9rMr]_ceil_loglistrvsetadd) r4 populationrmrwriresultZsetsizeZpoolrtrxZselectedZ selected_addr6r6r7r;s6)        z Random.sample) cum_weightsrmcs|jtdkrV|dkrHtd7fddtd|DStt|n|dk rftdtkrztdtdddfd dtd|DS) zReturn a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. Ncsg|]}qSr6r6rZrt)rgrirrr6r7 sz"Random.choices..z2Cannot specify both weights and cumulative weightsz3The number of weights does not match the populationrDrBcs$g|]}dqS)rr6r)rrhirrtotalr6r7rs) rrMrQ_repeatr _accumulater^r]_bisect)r4rZweightsrrmr6)rgrrrrirrrr7r)s$  zRandom.choicescCs||||S)zHGet a random number in the range [a, b) or [a, b] depending on rounding.rrjr6r6r7rszRandom.uniformrr.cCs||}z |dkrdn||||}Wntk r@|YSX||krdd|}d|}||}}|||t||S)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?r.)rZeroDivisionError_sqrt)r4ZlowZhighmodeur@r6r6r7r!s    zRandom.triangularcCsP|j}|}d|}t|d|}||d}|t| krqDq|||S)z\Normal distribution. mu is the mean, and sigma is the standard deviation. r.rr-)r NV_MAGICCONSTr~)r4musigmaru1u2zZzzr6r6r7rs   zRandom.normalvariatecCst|||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)r4rrr6r6r7rszRandom.lognormvariatecCstd| |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. r.)r~r)r4Zlambdr6r6r7rszRandom.expovariatecCs|j}|dkrt|Sd|}|td||}|}tt|}|||}|} | d||ks| d|t|kr4qq4d|} | |d| |} |} | dkr|t| t} n|t| t} | 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ư>rr.)rTWOPIr_cos_pir_acos)r4rZkapparsrnrrdrqfZu3Zthetar6r6r7rs$   $zRandom.vonmisesvariatecCs~|dks|dkrtd|j}|dkrtd|d}|t}||}|}d|kr`dksdqFqFd|}t|d||} |t| } |||} ||| | } | td| dks| t| krF| |SqFn|dkrtd| |S|} t|t}|| }|dkr$|d|} nt||| } |}|dkr^|| |dkrpqrq|t| krqrq| |SdS) 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.0r.r,gHz>gP?r/N)r]rrLOG4r~r SG_MAGICCONST_e)r4alphabetarZainvZbbbZcccrrvr5rrnrrkpr6r6r7r #s@        zRandom.gammavariatecCs`|j}|j}d|_|dkrT|t}tdtd|}t||}t|||_|||S)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. Ngr.)rr3rrr~r_sin)r4rrrrZx2piZg2radr6r6r7r"hs  z Random.gausscCs0||d}|dkrdS||||dSdS)zBeta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. r.rrN)r )r4rryr6r6r7r#s zRandom.betavariatecCsd|}d|d|S)z3Pareto distribution. alpha is the shape parameter.r.r)r4rrr6r6r7r$s zRandom.paretovariatecCs"d|}|t| d|S)zfWeibull distribution. alpha is the scale parameter and beta is the shape parameter. r.)rr~)r4rrrr6r6r7r%s zRandom.weibullvariate)N)Nr1)N)N)rr.N)$__name__ __module__ __qualname____doc__rXr8rArr&r'rarbrcrQrrr<BPFr=r9rrrr)rr!rrrrr r"r#r$r% __classcell__r6r6rVr7rNs<    ,  G  0E5 c@s8eZdZdZddZddZddZdd ZeZZ d S) r*zAlternate 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). cCsttddd?tS)z3Get the next random number in the range [0.0, 1.0).rCrFr2)rQrR_urandom RECIP_BPFrYr6r6r7rszSystemRandom.randomcCs<|dkrtd|dd}tt|d}||d|?S)z:getrandbits(k) -> x. Generates an int with k random bits.rz(number of bits must be greater than zerorCrF)r]rQrRr)r4rmZnumbytesr5r6r6r7r(s  zSystemRandom.getrandbitscOsdS)zs'     {