zfc@ sdZddlmZddlmZddlmZm Z ddl m Z mZmZmZmZddl mZmZmZmZddlmZ ddl!m"Z#dd l$Z%d d d d ddddddddddddddddddd d!d"gZ&d#ed$ed%Z'd%eZ(e d&Z)d'e d(Z*d)Z+d*e+ Z,dd l-Z-d e-j.fd+YZ.d e.fd,YZ/d"e.fd-YZ0d.Z1d/d0Z2e.Z3e3j4Z4e3j5Z5e3j6Z6e3j7Z7e3j8Z8e3j9Z9e3j:Z:e3j;Z;e3j<Z<e3j=Z=e3j>Z>e3j?Z?e3j@Z@e3jAZAe3jBZBe3jCZCe3jDZDe3jEZEe3jFZFe3jGZGe3jHZHe3jIZIeJd1kre2nd S(2sPRandom 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. * Without a direct way to compute N steps forward, the semantics of jumpahead(n) are weakened to simply jump to another distant state and rely on the large period to avoid overlapping sequences. * The random() method is implemented in C, executes in a single Python step, and is, therefore, threadsafe. i(tdivision(twarn(t MethodTypetBuiltinMethodType(tlogtexptpitetceil(tsqrttacostcostsin(turandom(thexlifyNtRandomtseedtrandomtuniformtrandinttchoicetsamplet randrangetshufflet normalvariatetlognormvariatet expovariatetvonmisesvariatet gammavariatet triangulartgausst betavariatet paretovariatetweibullvariatetgetstatetsetstatet jumpaheadt WichmannHillt getrandbitst SystemRandomigg@g@g?g@i5icB s*eZdZdZddZddZdZdZdZ dZ dZ d Z dd e d e>d Zd Zee d e>eedZdZddZdZdZddddZdZdZdZdZdZdZdZ dZ!dZ"RS( sRandom number generator base class used by bound module functions. Used to instantiate instances of Random to get generators that don't share state. Especially useful for multi-threaded programs, creating a different instance of Random for each thread, and using the jumpahead() method to ensure that the generated sequences seen by each thread don't overlap. 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(), setstate() and jumpahead(). Optionally, implement a getrandbits() method so that randrange() can cover arbitrarily large ranges. icC s|j|d|_dS(seInitialize an instance. Optional argument x controls seeding, as for Random.seed(). N(RtNonet gauss_next(tselftx((s/usr/lib64/python2.7/random.pyt__init__[s cC s|dkrdytttdd}Wqdtk r`ddl}t|jd}qdXntt|j|d|_ dS(sInitialize internal state of the random number generator. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or is an int or long, hash(a) is used instead. Hash values for some types are nondeterministic when the PYTHONHASHSEED environment variable is enabled. i iiNi( R(tlongt_hexlifyt_urandomtNotImplementedErrorttimetsuperRRR)(R*taR1((s/usr/lib64/python2.7/random.pyRds   cC s"|jtt|j|jfS(s9Return internal state; can be passed to setstate() later.(tVERSIONR2RR"R)(R*((s/usr/lib64/python2.7/random.pyR"{scC s|d}|dkrA|\}}|_tt|j|n|dkr|\}}|_ytd|D}Wntk r}t|nXtt|j|ntd||jfdS(s:Restore internal state from object returned by getstate().iiics s|]}t|dVqdS(ii NI(R-(t.0R+((s/usr/lib64/python2.7/random.pys ss?state with version %s passed to Random.setstate() of version %sN(R)R2RR#ttuplet ValueErrort TypeErrorR4(R*tstatetversiont internalstateR((s/usr/lib64/python2.7/random.pyR#s    cC sWt|t|j}ttjd|jd}tt|j|dS(sChange the internal state to one that is likely far away from the current state. This method will not be in Py3.x, so it is better to simply reseed. tsha512iN( treprR"tintt_hashlibtnewt hexdigestR2RR$(R*tnts((s/usr/lib64/python2.7/random.pyR$s!cC s |jS(N(R"(R*((s/usr/lib64/python2.7/random.pyt __getstate__scC s|j|dS(N(R#(R*R9((s/usr/lib64/python2.7/random.pyt __setstate__scC s|jd|jfS(N((t __class__R"(R*((s/usr/lib64/python2.7/random.pyt __reduce__silc C s||}||kr$tdn|d kru|dkri||krU|j|S||j|Stdn||}||krtdn||}|dkr|dkr||kr|||j|S||||j|S|dkr!td|||fn||} | |krEtdn| dkrf|| d| } n*| dkr|| d| } n td| dkrtdn| |kr|| |j| S|| ||j| S( sChoose 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. s!non-integer arg 1 for randrange()isempty range for randrange()s non-integer stop for randrange()is'empty range for randrange() (%d,%d, %d)s non-integer step for randrange()szero step for randrange()N(R7R(t _randbelowR( R*tstarttstoptstept_intt _maxwidthtistarttistoptwidthtistepRB((s/usr/lib64/python2.7/random.pyRs@                       cC s|j||dS(sJReturn random integer in range [a, b], including both end points. i(R(R*R3tb((s/usr/lib64/python2.7/random.pyRsc C sy |j}Wntk r ntXt|j|ksHt||kr|d||dd}||} x| |kr||} qtW| S||krtdn||j|S(sReturn a random int in the range [0,n) Handles the case where n has more bits than returned by a single call to the underlying generator. grZ| ?ig@sgUnderlying random() generator does not supply enough bits to choose from a population range this large(R&tAttributeErrorttypeRt_warn( R*RBt_logRLRMt_Methodt_BuiltinMethodR&tktr((s/usr/lib64/python2.7/random.pyRHs  '   cC s|t|jt|S(s2Choose a random element from a non-empty sequence.(R>Rtlen(R*tseq((s/usr/lib64/python2.7/random.pyRscC s||dkr|j}nt}xWttdt|D]:}|||d}||||||<|| shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random. iN(R(RR>treversedtxrangeR[(R*R+RRLtitj((s/usr/lib64/python2.7/random.pyRs   "c C st|}d|ko#|kns7tdn|j}t}d g|}d}|dkr|dtt|dd7}n||kst|drt|}xt |D]A} |||| } || || <||| d|| R(t_ceilRVthasattrtlistR^tsettaddR8tKeyErrort isinstanceRR6( R*t populationRYRBRRLtresulttsetsizetpoolR_R`tselectedt selected_add((s/usr/lib64/python2.7/random.pyR's:    $    cC s||||jS(sHGet a random number in the range [a, b) or [a, b] depending on rounding.(R(R*R3RR((s/usr/lib64/python2.7/random.pyRhsgg?cC s|j}y(|dkr!dn||||}Wntk rH|SX||kryd|}d|}||}}n|||||dS(sTriangular 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 g?g?N(RR(tZeroDivisionError(R*tlowthightmodetutc((s/usr/lib64/python2.7/random.pyRns (    cC si|j}xQ|}d|}t|d|}||d}|t| kr Pq q W|||S(s\Normal distribution. mu is the mean, and sigma is the standard deviation. g?g?g@(Rt NV_MAGICCONSTRV(R*tmutsigmaRtu1tu2tztzz((s/usr/lib64/python2.7/random.pyRs   cC st|j||S(sLog 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. (t_expR(R*RvRw((s/usr/lib64/python2.7/random.pyRscC std|j |S(s^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?(RVR(R*tlambd((s/usr/lib64/python2.7/random.pyRscC s|j}|dkr t|Sd|}|td||}xf|}tt|}|||}|} | d||ks| d|t|krEPqEqEWd|} | |d| |} |} | dkr|t| t} n|t| t} | S(sFCircular 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?(RtTWOPIt_sqrtt_cost_piR|t_acos(R*RvtkappaRRCRZRxRztdRytqtftu3ttheta((s/usr/lib64/python2.7/random.pyRs&      .   cC s |dks|dkr$tdn|j}|dkrtd|d}|t}||}x|}d|kodknsqdnd|}t|d||} |t| } |||} ||| | } | td| dks| t| krd| |SqdWn|dkr]|} x| dkrM|} q5Wt|  |Sx|} t|t}|| }|dkr|d|} nt||| } |}|dkr|| |dkrPqq`|t| kr`Pq`q`W| |SdS( sZGamma 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 gs*gammavariate: alpha and beta must be > 0.0g?g@gHz>gP?g@N(R7RRtLOG4RVR|t SG_MAGICCONSTt_e(R*talphatbetaRtainvtbbbtcccRxRytvR+RzRZRsRRtp((s/usr/lib64/python2.7/random.pyRsJ       *        cC s|j}|j}d|_|dkrw|t}tdtd|}t||}t|||_n|||S(sGaussian 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. gg?N(RR)R(R~RRVRt_sin(R*RvRwRRztx2pitg2rad((s/usr/lib64/python2.7/random.pyR4s     cC s>|j|d}|dkr"dS|||j|dSdS(sBeta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. g?igN(R(R*RRty((s/usr/lib64/python2.7/random.pyRis  cC s%d|j}dt|d|S(s3Pareto distribution. alpha is the shape parameter.g?(Rtpow(R*RRs((s/usr/lib64/python2.7/random.pyR {scC s,d|j}|tt| d|S(sfWeibull distribution. alpha is the scale parameter and beta is the shape parameter. g?(RRRV(R*RRRs((s/usr/lib64/python2.7/random.pyR!sN(#t__name__t __module__t__doc__R4R(R,RR"R#R$RDRERGR>tBPFRRRVt _MethodTypet_BuiltinMethodTypeRHRRRRRRRRRRRRR R!(((s/usr/lib64/python2.7/random.pyRHs8       ?     A    0 H 5  cB s\eZdZd dZdZdZdZdZddddZ d dZ RS( icC s|dkrdytttdd}Wqdtk r`ddl}t|jd}qdXnt|ttfst|}nt |d\}}t |d\}}t |d\}}t|dt|dt|df|_ d|_ dS( sInitialize 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 not None or an int or long, hash(a) is used instead. If a is an int or long, a is used directly. Distinct values between 0 and 27814431486575L inclusive are guaranteed to yield distinct internal states (this guarantee is specific to the default Wichmann-Hill generator). iiNiithashtdivmodt_seedR)(R*R3R1R+RRz((s/usr/lib64/python2.7/random.pyRs   0cC sj|j\}}}d|d}d|d}d|d}|||f|_|d|d|d d S( s3Get the next random number in the range [0.0, 1.0).ii=viicviisvg@@g@g@g?(R(R*R+RRz((s/usr/lib64/python2.7/random.pyRs cC s|j|j|jfS(s9Return internal state; can be passed to setstate() later.(R4RR)(R*((s/usr/lib64/python2.7/random.pyR"scC sK|d}|dkr.|\}|_|_ntd||jfdS(s:Restore internal state from object returned by getstate().iis?state with version %s passed to Random.setstate() of version %sN(RR)R7R4(R*R9R:((s/usr/lib64/python2.7/random.pyR#s   cC s|dkstdn|j\}}}t|td|dd}t|td|dd}t|td|dd}|||f|_d S( sAct as if n calls to random() were made, but quickly. n is an int, greater than or equal to 0. Example use: If you have 2 threads and know that each will consume no more than a million random numbers, create two Random objects r1 and r2, then do r2.setstate(r1.getstate()) r2.jumpahead(1000000) Then r1 and r2 will use guaranteed-disjoint segments of the full period. isn must be >= 0ii=viicviisvN(R7RR>R(R*RBR+RRz((s/usr/lib64/python2.7/random.pyR$s    icC st|t|ko4t|ko4tknsHtdnd|ko_dknod|ko{dknod|kodknstdnd|ko|ko|knrNddl}t|jd}t|d@|d?A}t|d\}}t|d\}}t|d\}}n|pWd |p`d |pid f|_d|_ dS( sjSet the Wichmann-Hill seed from (x, y, z). These must be integers in the range [0, 256). sseeds must be integersiisseeds must be in range(0, 256)iNiii( RTR>R8R7R1R-RRR(R)(R*R+RRzR1tt((s/usr/lib64/python2.7/random.pyt__whseeds9T' $cC s|dkr|jdSt|}t|d\}}t|d\}}t|d\}}||dpvd}||dpd}||dpd}|j|||dS(sbSeed from hashable object's hash code. None or no argument seeds from current time. It is not guaranteed that objects with distinct hash codes lead to distinct internal states. This is obsolete, provided for compatibility with the seed routine used prior to Python 2.1. Use the .seed() method instead. Nii(R(t_WichmannHill__whseedRR(R*R3R+RRz((s/usr/lib64/python2.7/random.pytwhseeds   N( RRR4R(RRR"R#R$RR(((s/usr/lib64/python2.7/random.pyR%s    cB sFeZdZdZdZdZeZZdZeZ Z RS(sAlternate 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). cC s!tttddd?tS(s3Get the next random number in the range [0.0, 1.0).iii(R-R.R/t RECIP_BPF(R*((s/usr/lib64/python2.7/random.pyR/scC su|dkrtdn|t|kr<tdn|dd}ttt|d}||d|?S(s>getrandbits(k) -> x. Generates a long int with k random bits.is(number of bits must be greater than zeros#number of bits should be an integeriii(R7R>R8R-R.R/(R*RYtbytesR+((s/usr/lib64/python2.7/random.pyR&3s cO sdS(s<Stub method. Not used for a system random number generator.N(R((R*targstkwds((s/usr/lib64/python2.7/random.pyt_stub=scO stddS(sAMethod should not be called for a system random number generator.s*System entropy source does not have state.N(R0(R*RR((s/usr/lib64/python2.7/random.pyt_notimplementedBs( RRRRR&RRR$RR"R#(((s/usr/lib64/python2.7/random.pyR''s    cC sddl}|GdG|jGHd}d}d}d}|j}xVt|D]H} ||} || 7}|| | }t| |}t| |}qMW|j} t| |dGdG||} t||| | } d| | ||fGHdS( Nittimesgg _Bg _issec,s!avg %g, stddev %g, min %g, max %g(R1RtrangetmintmaxtroundR(RBtfuncRR1ttotaltsqsumtsmallesttlargesttt0R_R+tt1tavgtstddev((s/usr/lib64/python2.7/random.pyt_test_generatorIs&      icC s t|td t|td t|td t|tdt|tdt|tdt|tdt|tdt|tdt|tdt|tdt|tdt|tdt|tdt|tdt|tdddfdS(Ngg?g{Gz?g?g@g?g?g4@gi@g@((gg?(gg?(gg?(g{Gz?g?(g?g?(g?g@(g?g?(g?g?(g?g?(g@g?(g4@g?(gi@g?(gg?(g@g@gUUUUUU?( RRRRRRRRR(tN((s/usr/lib64/python2.7/random.pyt_test_s t__main__(KRt __future__RtwarningsRRUttypesRRRRtmathRRVRR|RRRRRRbR RR RR RR RtosR R/tbinasciiRR.thashlibR?t__all__RuR~RRRRt_randomRR%R'RRt_instRRRRRRRRRRRRRRRRR R!R"R#R$R&R(((s/usr/lib64/python2.7/random.pyt(sj("         K"