home *** CD-ROM | disk | FTP | other *** search
/ Freelog 33 / Freelog033.iso / Progr / Python-2.2.1.exe / RANDOM.PY < prev    next >
Encoding:
Python Source  |  2001-11-25  |  22.0 KB  |  664 lines

  1. """Random variable generators.
  2.  
  3.     integers
  4.     --------
  5.            uniform within range
  6.  
  7.     sequences
  8.     ---------
  9.            pick random element
  10.            generate random permutation
  11.  
  12.     distributions on the real line:
  13.     ------------------------------
  14.            uniform
  15.            normal (Gaussian)
  16.            lognormal
  17.            negative exponential
  18.            gamma
  19.            beta
  20.  
  21.     distributions on the circle (angles 0 to 2pi)
  22.     ---------------------------------------------
  23.            circular uniform
  24.            von Mises
  25.  
  26. Translated from anonymously contributed C/C++ source.
  27.  
  28. Multi-threading note:  the random number generator used here is not thread-
  29. safe; it is possible that two calls return the same random value.  However,
  30. you can instantiate a different instance of Random() in each thread to get
  31. generators that don't share state, then use .setstate() and .jumpahead() to
  32. move the generators to disjoint segments of the full period.  For example,
  33.  
  34. def create_generators(num, delta, firstseed=None):
  35.     ""\"Return list of num distinct generators.
  36.     Each generator has its own unique segment of delta elements from
  37.     Random.random()'s full period.
  38.     Seed the first generator with optional arg firstseed (default is
  39.     None, to seed from current time).
  40.     ""\"
  41.  
  42.     from random import Random
  43.     g = Random(firstseed)
  44.     result = [g]
  45.     for i in range(num - 1):
  46.         laststate = g.getstate()
  47.         g = Random()
  48.         g.setstate(laststate)
  49.         g.jumpahead(delta)
  50.         result.append(g)
  51.     return result
  52.  
  53. gens = create_generators(10, 1000000)
  54.  
  55. That creates 10 distinct generators, which can be passed out to 10 distinct
  56. threads.  The generators don't share state so can be called safely in
  57. parallel.  So long as no thread calls its g.random() more than a million
  58. times (the second argument to create_generators), the sequences seen by
  59. each thread will not overlap.
  60.  
  61. The period of the underlying Wichmann-Hill generator is 6,953,607,871,644,
  62. and that limits how far this technique can be pushed.
  63.  
  64. Just for fun, note that since we know the period, .jumpahead() can also be
  65. used to "move backward in time":
  66.  
  67. >>> g = Random(42)  # arbitrary
  68. >>> g.random()
  69. 0.25420336316883324
  70. >>> g.jumpahead(6953607871644L - 1) # move *back* one
  71. >>> g.random()
  72. 0.25420336316883324
  73. """
  74. # XXX The docstring sucks.
  75.  
  76. from math import log as _log, exp as _exp, pi as _pi, e as _e
  77. from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
  78.  
  79. __all__ = ["Random","seed","random","uniform","randint","choice",
  80.            "randrange","shuffle","normalvariate","lognormvariate",
  81.            "cunifvariate","expovariate","vonmisesvariate","gammavariate",
  82.            "stdgamma","gauss","betavariate","paretovariate","weibullvariate",
  83.            "getstate","setstate","jumpahead","whseed"]
  84.  
  85. def _verify(name, computed, expected):
  86.     if abs(computed - expected) > 1e-7:
  87.         raise ValueError(
  88.             "computed value for %s deviates too much "
  89.             "(computed %g, expected %g)" % (name, computed, expected))
  90.  
  91. NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
  92. _verify('NV_MAGICCONST', NV_MAGICCONST, 1.71552776992141)
  93.  
  94. TWOPI = 2.0*_pi
  95. _verify('TWOPI', TWOPI, 6.28318530718)
  96.  
  97. LOG4 = _log(4.0)
  98. _verify('LOG4', LOG4, 1.38629436111989)
  99.  
  100. SG_MAGICCONST = 1.0 + _log(4.5)
  101. _verify('SG_MAGICCONST', SG_MAGICCONST, 2.50407739677627)
  102.  
  103. del _verify
  104.  
  105. # Translated by Guido van Rossum from C source provided by
  106. # Adrian Baddeley.
  107.  
  108. class Random:
  109.  
  110.     VERSION = 1     # used by getstate/setstate
  111.  
  112.     def __init__(self, x=None):
  113.         """Initialize an instance.
  114.  
  115.         Optional argument x controls seeding, as for Random.seed().
  116.         """
  117.  
  118.         self.seed(x)
  119.         self.gauss_next = None
  120.  
  121. ## -------------------- core generator -------------------
  122.  
  123.     # Specific to Wichmann-Hill generator.  Subclasses wishing to use a
  124.     # different core generator should override the seed(), random(),
  125.     # getstate(), setstate() and jumpahead() methods.
  126.  
  127.     def seed(self, a=None):
  128.         """Initialize internal state from hashable object.
  129.  
  130.         None or no argument seeds from current time.
  131.  
  132.         If a is not None or an int or long, hash(a) is used instead.
  133.  
  134.         If a is an int or long, a is used directly.  Distinct values between
  135.         0 and 27814431486575L inclusive are guaranteed to yield distinct
  136.         internal states (this guarantee is specific to the default
  137.         Wichmann-Hill generator).
  138.         """
  139.  
  140.         if a is None:
  141.             # Initialize from current time
  142.             import time
  143.             a = long(time.time() * 256)
  144.  
  145.         if type(a) not in (type(3), type(3L)):
  146.             a = hash(a)
  147.  
  148.         a, x = divmod(a, 30268)
  149.         a, y = divmod(a, 30306)
  150.         a, z = divmod(a, 30322)
  151.         self._seed = int(x)+1, int(y)+1, int(z)+1
  152.  
  153.     def random(self):
  154.         """Get the next random number in the range [0.0, 1.0)."""
  155.  
  156.         # Wichman-Hill random number generator.
  157.         #
  158.         # Wichmann, B. A. & Hill, I. D. (1982)
  159.         # Algorithm AS 183:
  160.         # An efficient and portable pseudo-random number generator
  161.         # Applied Statistics 31 (1982) 188-190
  162.         #
  163.         # see also:
  164.         #        Correction to Algorithm AS 183
  165.         #        Applied Statistics 33 (1984) 123
  166.         #
  167.         #        McLeod, A. I. (1985)
  168.         #        A remark on Algorithm AS 183
  169.         #        Applied Statistics 34 (1985),198-200
  170.  
  171.         # This part is thread-unsafe:
  172.         # BEGIN CRITICAL SECTION
  173.         x, y, z = self._seed
  174.         x = (171 * x) % 30269
  175.         y = (172 * y) % 30307
  176.         z = (170 * z) % 30323
  177.         self._seed = x, y, z
  178.         # END CRITICAL SECTION
  179.  
  180.         # Note:  on a platform using IEEE-754 double arithmetic, this can
  181.         # never return 0.0 (asserted by Tim; proof too long for a comment).
  182.         return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
  183.  
  184.     def getstate(self):
  185.         """Return internal state; can be passed to setstate() later."""
  186.         return self.VERSION, self._seed, self.gauss_next
  187.  
  188.     def setstate(self, state):
  189.         """Restore internal state from object returned by getstate()."""
  190.         version = state[0]
  191.         if version == 1:
  192.             version, self._seed, self.gauss_next = state
  193.         else:
  194.             raise ValueError("state with version %s passed to "
  195.                              "Random.setstate() of version %s" %
  196.                              (version, self.VERSION))
  197.  
  198.     def jumpahead(self, n):
  199.         """Act as if n calls to random() were made, but quickly.
  200.  
  201.         n is an int, greater than or equal to 0.
  202.  
  203.         Example use:  If you have 2 threads and know that each will
  204.         consume no more than a million random numbers, create two Random
  205.         objects r1 and r2, then do
  206.             r2.setstate(r1.getstate())
  207.             r2.jumpahead(1000000)
  208.         Then r1 and r2 will use guaranteed-disjoint segments of the full
  209.         period.
  210.         """
  211.  
  212.         if not n >= 0:
  213.             raise ValueError("n must be >= 0")
  214.         x, y, z = self._seed
  215.         x = int(x * pow(171, n, 30269)) % 30269
  216.         y = int(y * pow(172, n, 30307)) % 30307
  217.         z = int(z * pow(170, n, 30323)) % 30323
  218.         self._seed = x, y, z
  219.  
  220.     def __whseed(self, x=0, y=0, z=0):
  221.         """Set the Wichmann-Hill seed from (x, y, z).
  222.  
  223.         These must be integers in the range [0, 256).
  224.         """
  225.  
  226.         if not type(x) == type(y) == type(z) == type(0):
  227.             raise TypeError('seeds must be integers')
  228.         if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256):
  229.             raise ValueError('seeds must be in range(0, 256)')
  230.         if 0 == x == y == z:
  231.             # Initialize from current time
  232.             import time
  233.             t = long(time.time() * 256)
  234.             t = int((t&0xffffff) ^ (t>>24))
  235.             t, x = divmod(t, 256)
  236.             t, y = divmod(t, 256)
  237.             t, z = divmod(t, 256)
  238.         # Zero is a poor seed, so substitute 1
  239.         self._seed = (x or 1, y or 1, z or 1)
  240.  
  241.     def whseed(self, a=None):
  242.         """Seed from hashable object's hash code.
  243.  
  244.         None or no argument seeds from current time.  It is not guaranteed
  245.         that objects with distinct hash codes lead to distinct internal
  246.         states.
  247.  
  248.         This is obsolete, provided for compatibility with the seed routine
  249.         used prior to Python 2.1.  Use the .seed() method instead.
  250.         """
  251.  
  252.         if a is None:
  253.             self.__whseed()
  254.             return
  255.         a = hash(a)
  256.         a, x = divmod(a, 256)
  257.         a, y = divmod(a, 256)
  258.         a, z = divmod(a, 256)
  259.         x = (x + a) % 256 or 1
  260.         y = (y + a) % 256 or 1
  261.         z = (z + a) % 256 or 1
  262.         self.__whseed(x, y, z)
  263.  
  264. ## ---- Methods below this point do not need to be overridden when
  265. ## ---- subclassing for the purpose of using a different core generator.
  266.  
  267. ## -------------------- pickle support  -------------------
  268.  
  269.     def __getstate__(self): # for pickle
  270.         return self.getstate()
  271.  
  272.     def __setstate__(self, state):  # for pickle
  273.         self.setstate(state)
  274.  
  275. ## -------------------- integer methods  -------------------
  276.  
  277.     def randrange(self, start, stop=None, step=1, int=int, default=None):
  278.         """Choose a random item from range(start, stop[, step]).
  279.  
  280.         This fixes the problem with randint() which includes the
  281.         endpoint; in Python this is usually not what you want.
  282.         Do not supply the 'int' and 'default' arguments.
  283.         """
  284.  
  285.         # This code is a bit messy to make it fast for the
  286.         # common case while still doing adequate error checking
  287.         istart = int(start)
  288.         if istart != start:
  289.             raise ValueError, "non-integer arg 1 for randrange()"
  290.         if stop is default:
  291.             if istart > 0:
  292.                 return int(self.random() * istart)
  293.             raise ValueError, "empty range for randrange()"
  294.         istop = int(stop)
  295.         if istop != stop:
  296.             raise ValueError, "non-integer stop for randrange()"
  297.         if step == 1:
  298.             if istart < istop:
  299.                 return istart + int(self.random() *
  300.                                    (istop - istart))
  301.             raise ValueError, "empty range for randrange()"
  302.         istep = int(step)
  303.         if istep != step:
  304.             raise ValueError, "non-integer step for randrange()"
  305.         if istep > 0:
  306.             n = (istop - istart + istep - 1) / istep
  307.         elif istep < 0:
  308.             n = (istop - istart + istep + 1) / istep
  309.         else:
  310.             raise ValueError, "zero step for randrange()"
  311.  
  312.         if n <= 0:
  313.             raise ValueError, "empty range for randrange()"
  314.         return istart + istep*int(self.random() * n)
  315.  
  316.     def randint(self, a, b):
  317.         """Return random integer in range [a, b], including both end points.
  318.  
  319.         (Deprecated; use randrange(a, b+1).)
  320.         """
  321.  
  322.         return self.randrange(a, b+1)
  323.  
  324. ## -------------------- sequence methods  -------------------
  325.  
  326.     def choice(self, seq):
  327.         """Choose a random element from a non-empty sequence."""
  328.         return seq[int(self.random() * len(seq))]
  329.  
  330.     def shuffle(self, x, random=None, int=int):
  331.         """x, random=random.random -> shuffle list x in place; return None.
  332.  
  333.         Optional arg random is a 0-argument function returning a random
  334.         float in [0.0, 1.0); by default, the standard random.random.
  335.  
  336.         Note that for even rather small len(x), the total number of
  337.         permutations of x is larger than the period of most random number
  338.         generators; this implies that "most" permutations of a long
  339.         sequence can never be generated.
  340.         """
  341.  
  342.         if random is None:
  343.             random = self.random
  344.         for i in xrange(len(x)-1, 0, -1):
  345.             # pick an element in x[:i+1] with which to exchange x[i]
  346.             j = int(random() * (i+1))
  347.             x[i], x[j] = x[j], x[i]
  348.  
  349. ## -------------------- real-valued distributions  -------------------
  350.  
  351. ## -------------------- uniform distribution -------------------
  352.  
  353.     def uniform(self, a, b):
  354.         """Get a random number in the range [a, b)."""
  355.         return a + (b-a) * self.random()
  356.  
  357. ## -------------------- normal distribution --------------------
  358.  
  359.     def normalvariate(self, mu, sigma):
  360.         # mu = mean, sigma = standard deviation
  361.  
  362.         # Uses Kinderman and Monahan method. Reference: Kinderman,
  363.         # A.J. and Monahan, J.F., "Computer generation of random
  364.         # variables using the ratio of uniform deviates", ACM Trans
  365.         # Math Software, 3, (1977), pp257-260.
  366.  
  367.         random = self.random
  368.         while 1:
  369.             u1 = random()
  370.             u2 = random()
  371.             z = NV_MAGICCONST*(u1-0.5)/u2
  372.             zz = z*z/4.0
  373.             if zz <= -_log(u2):
  374.                 break
  375.         return mu + z*sigma
  376.  
  377. ## -------------------- lognormal distribution --------------------
  378.  
  379.     def lognormvariate(self, mu, sigma):
  380.         return _exp(self.normalvariate(mu, sigma))
  381.  
  382. ## -------------------- circular uniform --------------------
  383.  
  384.     def cunifvariate(self, mean, arc):
  385.         # mean: mean angle (in radians between 0 and pi)
  386.         # arc:  range of distribution (in radians between 0 and pi)
  387.  
  388.         return (mean + arc * (self.random() - 0.5)) % _pi
  389.  
  390. ## -------------------- exponential distribution --------------------
  391.  
  392.     def expovariate(self, lambd):
  393.         # lambd: rate lambd = 1/mean
  394.         # ('lambda' is a Python reserved word)
  395.  
  396.         random = self.random
  397.         u = random()
  398.         while u <= 1e-7:
  399.             u = random()
  400.         return -_log(u)/lambd
  401.  
  402. ## -------------------- von Mises distribution --------------------
  403.  
  404.     def vonmisesvariate(self, mu, kappa):
  405.         # mu:    mean angle (in radians between 0 and 2*pi)
  406.         # kappa: concentration parameter kappa (>= 0)
  407.         # if kappa = 0 generate uniform random angle
  408.  
  409.         # Based upon an algorithm published in: Fisher, N.I.,
  410.         # "Statistical Analysis of Circular Data", Cambridge
  411.         # University Press, 1993.
  412.  
  413.         # Thanks to Magnus Kessler for a correction to the
  414.         # implementation of step 4.
  415.  
  416.         random = self.random
  417.         if kappa <= 1e-6:
  418.             return TWOPI * random()
  419.  
  420.         a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)
  421.         b = (a - _sqrt(2.0 * a))/(2.0 * kappa)
  422.         r = (1.0 + b * b)/(2.0 * b)
  423.  
  424.         while 1:
  425.             u1 = random()
  426.  
  427.             z = _cos(_pi * u1)
  428.             f = (1.0 + r * z)/(r + z)
  429.             c = kappa * (r - f)
  430.  
  431.             u2 = random()
  432.  
  433.             if not (u2 >= c * (2.0 - c) and u2 > c * _exp(1.0 - c)):
  434.                 break
  435.  
  436.         u3 = random()
  437.         if u3 > 0.5:
  438.             theta = (mu % TWOPI) + _acos(f)
  439.         else:
  440.             theta = (mu % TWOPI) - _acos(f)
  441.  
  442.         return theta
  443.  
  444. ## -------------------- gamma distribution --------------------
  445.  
  446.     def gammavariate(self, alpha, beta):
  447.         # beta times standard gamma
  448.         ainv = _sqrt(2.0 * alpha - 1.0)
  449.         return beta * self.stdgamma(alpha, ainv, alpha - LOG4, alpha + ainv)
  450.  
  451.     def stdgamma(self, alpha, ainv, bbb, ccc):
  452.         # ainv = sqrt(2 * alpha - 1)
  453.         # bbb = alpha - log(4)
  454.         # ccc = alpha + ainv
  455.  
  456.         random = self.random
  457.         if alpha <= 0.0:
  458.             raise ValueError, 'stdgamma: alpha must be > 0.0'
  459.  
  460.         if alpha > 1.0:
  461.  
  462.             # Uses R.C.H. Cheng, "The generation of Gamma
  463.             # variables with non-integral shape parameters",
  464.             # Applied Statistics, (1977), 26, No. 1, p71-74
  465.  
  466.             while 1:
  467.                 u1 = random()
  468.                 u2 = random()
  469.                 v = _log(u1/(1.0-u1))/ainv
  470.                 x = alpha*_exp(v)
  471.                 z = u1*u1*u2
  472.                 r = bbb+ccc*v-x
  473.                 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
  474.                     return x
  475.  
  476.         elif alpha == 1.0:
  477.             # expovariate(1)
  478.             u = random()
  479.             while u <= 1e-7:
  480.                 u = random()
  481.             return -_log(u)
  482.  
  483.         else:   # alpha is between 0 and 1 (exclusive)
  484.  
  485.             # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
  486.  
  487.             while 1:
  488.                 u = random()
  489.                 b = (_e + alpha)/_e
  490.                 p = b*u
  491.                 if p <= 1.0:
  492.                     x = pow(p, 1.0/alpha)
  493.                 else:
  494.                     # p > 1
  495.                     x = -_log((b-p)/alpha)
  496.                 u1 = random()
  497.                 if not (((p <= 1.0) and (u1 > _exp(-x))) or
  498.                           ((p > 1)  and  (u1 > pow(x, alpha - 1.0)))):
  499.                     break
  500.             return x
  501.  
  502.  
  503. ## -------------------- Gauss (faster alternative) --------------------
  504.  
  505.     def gauss(self, mu, sigma):
  506.  
  507.         # When x and y are two variables from [0, 1), uniformly
  508.         # distributed, then
  509.         #
  510.         #    cos(2*pi*x)*sqrt(-2*log(1-y))
  511.         #    sin(2*pi*x)*sqrt(-2*log(1-y))
  512.         #
  513.         # are two *independent* variables with normal distribution
  514.         # (mu = 0, sigma = 1).
  515.         # (Lambert Meertens)
  516.         # (corrected version; bug discovered by Mike Miller, fixed by LM)
  517.  
  518.         # Multithreading note: When two threads call this function
  519.         # simultaneously, it is possible that they will receive the
  520.         # same return value.  The window is very small though.  To
  521.         # avoid this, you have to use a lock around all calls.  (I
  522.         # didn't want to slow this down in the serial case by using a
  523.         # lock here.)
  524.  
  525.         random = self.random
  526.         z = self.gauss_next
  527.         self.gauss_next = None
  528.         if z is None:
  529.             x2pi = random() * TWOPI
  530.             g2rad = _sqrt(-2.0 * _log(1.0 - random()))
  531.             z = _cos(x2pi) * g2rad
  532.             self.gauss_next = _sin(x2pi) * g2rad
  533.  
  534.         return mu + z*sigma
  535.  
  536. ## -------------------- beta --------------------
  537. ## See
  538. ## http://sourceforge.net/bugs/?func=detailbug&bug_id=130030&group_id=5470
  539. ## for Ivan Frohne's insightful analysis of why the original implementation:
  540. ##
  541. ##    def betavariate(self, alpha, beta):
  542. ##        # Discrete Event Simulation in C, pp 87-88.
  543. ##
  544. ##        y = self.expovariate(alpha)
  545. ##        z = self.expovariate(1.0/beta)
  546. ##        return z/(y+z)
  547. ##
  548. ## was dead wrong, and how it probably got that way.
  549.  
  550.     def betavariate(self, alpha, beta):
  551.         # This version due to Janne Sinkkonen, and matches all the std
  552.         # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
  553.         y = self.gammavariate(alpha, 1.)
  554.         if y == 0:
  555.             return 0.0
  556.         else:
  557.             return y / (y + self.gammavariate(beta, 1.))
  558.  
  559. ## -------------------- Pareto --------------------
  560.  
  561.     def paretovariate(self, alpha):
  562.         # Jain, pg. 495
  563.  
  564.         u = self.random()
  565.         return 1.0 / pow(u, 1.0/alpha)
  566.  
  567. ## -------------------- Weibull --------------------
  568.  
  569.     def weibullvariate(self, alpha, beta):
  570.         # Jain, pg. 499; bug fix courtesy Bill Arms
  571.  
  572.         u = self.random()
  573.         return alpha * pow(-_log(u), 1.0/beta)
  574.  
  575. ## -------------------- test program --------------------
  576.  
  577. def _test_generator(n, funccall):
  578.     import time
  579.     print n, 'times', funccall
  580.     code = compile(funccall, funccall, 'eval')
  581.     sum = 0.0
  582.     sqsum = 0.0
  583.     smallest = 1e10
  584.     largest = -1e10
  585.     t0 = time.time()
  586.     for i in range(n):
  587.         x = eval(code)
  588.         sum = sum + x
  589.         sqsum = sqsum + x*x
  590.         smallest = min(x, smallest)
  591.         largest = max(x, largest)
  592.     t1 = time.time()
  593.     print round(t1-t0, 3), 'sec,',
  594.     avg = sum/n
  595.     stddev = _sqrt(sqsum/n - avg*avg)
  596.     print 'avg %g, stddev %g, min %g, max %g' % \
  597.               (avg, stddev, smallest, largest)
  598.  
  599. def _test(N=200):
  600.     print 'TWOPI         =', TWOPI
  601.     print 'LOG4          =', LOG4
  602.     print 'NV_MAGICCONST =', NV_MAGICCONST
  603.     print 'SG_MAGICCONST =', SG_MAGICCONST
  604.     _test_generator(N, 'random()')
  605.     _test_generator(N, 'normalvariate(0.0, 1.0)')
  606.     _test_generator(N, 'lognormvariate(0.0, 1.0)')
  607.     _test_generator(N, 'cunifvariate(0.0, 1.0)')
  608.     _test_generator(N, 'expovariate(1.0)')
  609.     _test_generator(N, 'vonmisesvariate(0.0, 1.0)')
  610.     _test_generator(N, 'gammavariate(0.5, 1.0)')
  611.     _test_generator(N, 'gammavariate(0.9, 1.0)')
  612.     _test_generator(N, 'gammavariate(1.0, 1.0)')
  613.     _test_generator(N, 'gammavariate(2.0, 1.0)')
  614.     _test_generator(N, 'gammavariate(20.0, 1.0)')
  615.     _test_generator(N, 'gammavariate(200.0, 1.0)')
  616.     _test_generator(N, 'gauss(0.0, 1.0)')
  617.     _test_generator(N, 'betavariate(3.0, 3.0)')
  618.     _test_generator(N, 'paretovariate(1.0)')
  619.     _test_generator(N, 'weibullvariate(1.0, 1.0)')
  620.  
  621.     # Test jumpahead.
  622.     s = getstate()
  623.     jumpahead(N)
  624.     r1 = random()
  625.     # now do it the slow way
  626.     setstate(s)
  627.     for i in range(N):
  628.         random()
  629.     r2 = random()
  630.     if r1 != r2:
  631.         raise ValueError("jumpahead test failed " + `(N, r1, r2)`)
  632.  
  633. # Create one instance, seeded from current time, and export its methods
  634. # as module-level functions.  The functions are not threadsafe, and state
  635. # is shared across all uses (both in the user's code and in the Python
  636. # libraries), but that's fine for most programs and is easier for the
  637. # casual user than making them instantiate their own Random() instance.
  638. _inst = Random()
  639. seed = _inst.seed
  640. random = _inst.random
  641. uniform = _inst.uniform
  642. randint = _inst.randint
  643. choice = _inst.choice
  644. randrange = _inst.randrange
  645. shuffle = _inst.shuffle
  646. normalvariate = _inst.normalvariate
  647. lognormvariate = _inst.lognormvariate
  648. cunifvariate = _inst.cunifvariate
  649. expovariate = _inst.expovariate
  650. vonmisesvariate = _inst.vonmisesvariate
  651. gammavariate = _inst.gammavariate
  652. stdgamma = _inst.stdgamma
  653. gauss = _inst.gauss
  654. betavariate = _inst.betavariate
  655. paretovariate = _inst.paretovariate
  656. weibullvariate = _inst.weibullvariate
  657. getstate = _inst.getstate
  658. setstate = _inst.setstate
  659. jumpahead = _inst.jumpahead
  660. whseed = _inst.whseed
  661.  
  662. if __name__ == '__main__':
  663.     _test()
  664.