[e@sdZddlmZddlmZmZddl m Z m Z mZmZmZddl mZmZmZmZddlmZddlm Z!m"Z#ddl$m%Z&d d d d d ddddddddddddddddddgZ'd e d! ed"Z(d"eZ)e d#Z*d$e d%Z+d&Z,d'e, Z-dd(l.Z.Gd)d d e.j/Z/Gd*dde/Z0d+d,Z1d-d.d/Z2e/Z3e3j4Z4e3j5Z5e3j6Z6e3j7Z7e3j8Z8e3j9Z9e3j:Z:e3j;Z;e3j<Z<e3j=Z=e3j>Z>e3j?Z?e3j@Z@e3jAZAe3jBZBe3jCZCe3jDZDe3jEZEe3jFZFe3jGZGe3jHZHeId0kr{e2nd(S)1aRandom variable generators. integers -------- uniform within range sequences --------- pick random element pick 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) MethodTypeBuiltinMethodType)logexppieceil)sqrtacoscossin)urandom)SetSequence)sha512Randomseedrandomuniformrandintchoicesample randrangeshuffle normalvariatelognormvariate expovariatevonmisesvariate gammavariate triangulargauss betavariate paretovariateweibullvariategetstatesetstate getrandbits SystemRandomg?g@g@g?g@5NcseZdZdZdZdddZddfddZfd d Zfd d Zd dZ ddZ ddZ dde ddZ ddZe de>eeeddZddZdddZddZd d!Zd"d#dd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Z d6d7Z!S)8raRandom 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|j|d|_dS)zeInitialize an instance. Optional argument x controls seeding, as for Random.seed(). N)r gauss_next)selfxr0/usr/lib/python3.4/random.py__init__Ts zRandom.__init__r+c s|dkrbytjtdd}Wqbtk r^ddl}t|jd}YqbXn|dkrt|tttfrt|tr|j }n|t |j 7}tj|d}qnt j |d|_dS)aInitialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1, the hash() of *a* is used instead. If *a* is an int, all bits are used. Ni bigrr+)int from_bytes_urandomNotImplementedErrortime isinstancestrbytes bytearrayencode_sha512Zdigestsuperrr-)r.aversionr9) __class__r0r1r]s    z Random.seedcs|jtj|jfS)z9Return internal state; can be passed to setstate() later.)VERSIONr@r%r-)r.)rCr0r1r%}szRandom.getstatecs|d}|dkr;|\}}|_tj|n|dkr|\}}|_ytdd|D}Wn.tk r}zt|WYdd}~XnXtj|ntd||jfdS)z:Restore internal state from object returned by getstate().rr,r+css|]}|dVqdS)r+ Nlr0).0r/r0r0r1 sz"Random.setstate..Nz?state with version %s passed to Random.setstate() of version %s)r-r@r&tuple ValueError TypeErrorrD)r.staterBZ internalstater)rCr0r1r&s   zRandom.setstatecCs |jS)N)r%)r.r0r0r1 __getstate__szRandom.__getstate__cCs|j|dS)N)r&)r.rKr0r0r1 __setstate__szRandom.__setstate__cCs|jf|jfS)N)rCr%)r.r0r0r1 __reduce__szRandom.__reduce__c Cs||}||kr'tdn|dkr[|dkrL|j|Stdn||}||krtdn||}|dkr|dkr||j|S|dkrtd|||fn||}||krtdn|dkr%||d|} n-|dkrF||d|} n td | dkrmtdn|||j| 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()rOz'empty range for randrange() (%d,%d, %d)z non-integer step for randrange()zzero step for randrange())rI _randbelow) r.startstopstep_intZistartZistopwidthZistepnr0r0r1rs4               zRandom.randrangecCs|j||dS)zJReturn random integer in range [a, b], including both end points. rO)r)r.rAbr0r0r1rszRandom.randintc Cs|j}|j}|||ks6|||krq|j} || } x| |krl|| } qQW| S||krtd|||S||} || |} |} x| | kr|} qW|| ||S)zCReturn a random int in the range [0,n). Raises ValueError if n==0.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.)rr' bit_length_warn) r.rVr5maxsizetypeZMethodZ BuiltinMethodrr'krZremlimitr0r0r1rPs"  $       zRandom._randbelowc CsBy|jt|}Wntk r9tdYnX||S)z2Choose a random element from a non-empty sequence.z$Cannot choose from an empty sequence)rPlenrI IndexError)r.seqir0r0r1rs  z Random.choicecCs|dkrk|j}xttdt|D]3}||d}||||||<||Population must be a sequence or set. For dicts, use list(d).rzSample larger than populationNr)r,rO)r:_SetrH _SequencerJrPr_rI_ceil_loglistrdsetadd) r.Z populationr\rerVresultZsetsizeZpoolrbrfZselectedZ selected_addr0r0r1rs6    $      z Random.samplecCs||||jS)zHGet a random number in the range [a, b) or [a, b] depending on rounding.)r)r.rArWr0r0r1rVszRandom.uniformgg?c Cs|j}y(|dkr!dn||||}Wntk rL|SYnX||kr}d|}d|}||}}n|||||dS)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 Ng?g?)rZeroDivisionError)r.ZlowZhighmodeucr0r0r1r \s (     zRandom.triangularcCsi|j}xQ|}d|}t|d|}||d}|t| kr Pq q W|||S)z\Normal distribution. mu is the mean, and sigma is the standard deviation. g?g?g@)r NV_MAGICCONSTrl)r.musigmaru1u2zZzzr0r0r1rrs   zRandom.normalvariatecCst|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.rvrwr0r0r1rszRandom.lognormvariatecCstd|j |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. g?)rlr)r.Zlambdr0r0r1rszRandom.expovariatecCs|j}|dkr t|Sd|}|td||}xf|}tt|}|||}|} | d||ks| d|t|krEPqEqEWd|} | |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ư>g?g?)rTWOPI_sqrt_cos_pir{_acos)r.rvZkapparsr]rxrzdryqfZu3Zthetar0r0r1rs&      .   zRandom.vonmisesvariatecCs |dks|dkr'tdn|j}|dkr td|d}|t}||}x|}d|kodknsqgnd|}t|d||} |t| } |||} ||| | } | td| dks| t| krg| |SqgWn|dkr`|} x| dkrP|} q8Wt|  |Sx|} t|t}|| }|dkr|d|} nt||| } |}|dkr|| |dkrPqqc|t| krcPqcqcW| |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 gz*gammavariate: alpha and beta must be > 0.0g?g@gHz>gP?g@N)rIrr}LOG4rlr{ SG_MAGICCONST_e)r.alphabetarZainvZbbbZcccrxryvr/rzr]rsrWpr0r0r1rsJ      *        zRandom.gammavariatecCs|j}|j}d|_|dkrw|t}tdtd|}t||}t|||_n|||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. Ng@g?g)rr-r|r}rlr~_sin)r.rvrwrrzZx2piZg2radr0r0r1r!"s     z Random.gausscCs>|j|d}|dkr"dS|||j|dSdS)zBeta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. g?rgN)r)r.rryr0r0r1r"Ws  zRandom.betavariatecCs d|j}d|d|S)z3Pareto distribution. alpha is the shape parameter.g?)r)r.rrsr0r0r1r#iszRandom.paretovariatecCs'd|j}|t| d|S)zfWeibull distribution. alpha is the scale parameter and beta is the shape parameter. g?)rrl)r.rrrsr0r0r1r$rszRandom.weibullvariate)"__name__ __module__ __qualname____doc__rDr2rr%r&rLrMrNr5rrBPFr[ _MethodType_BuiltinMethodTyperPrrrrr rrrrrr!r"r#r$r0r0)rCr1rDs6      ,    >    0 H 5  c@sPeZdZdZddZddZddZdd 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). cCstjtddd?tS)z3Get the next random number in the range [0.0, 1.0).r3r,)r5r6r7 RECIP_BPF)r.r0r0r1rszSystemRandom.randomcCsr|dkrtdn|t|kr<tdn|dd}tjt|d}||d|?S)z:getrandbits(k) -> x. Generates an int with k random bits.rz(number of bits must be greater than zeroz#number of bits should be an integerrr3)rIr5rJr6r7)r.r\Znumbytesr/r0r0r1r's zSystemRandom.getrandbitscOsdS)z%sd("         =!