home *** CD-ROM | disk | FTP | other *** search
/ One Click 11 / OneClick11.iso / Bancos de Dados / Conversao / Mysql2Excel / Setup.exe / Mysql2Excel.exe / random.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-06-23  |  20.3 KB  |  573 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''Random variable generators.
  5.  
  6.     integers
  7.     --------
  8.            uniform within range
  9.  
  10.     sequences
  11.     ---------
  12.            pick random element
  13.            generate random permutation
  14.  
  15.     distributions on the real line:
  16.     ------------------------------
  17.            uniform
  18.            normal (Gaussian)
  19.            lognormal
  20.            negative exponential
  21.            gamma
  22.            beta
  23.  
  24.     distributions on the circle (angles 0 to 2pi)
  25.     ---------------------------------------------
  26.            circular uniform
  27.            von Mises
  28.  
  29. Translated from anonymously contributed C/C++ source.
  30.  
  31. Multi-threading note:  the random number generator used here is not thread-
  32. safe; it is possible that two calls return the same random value.  However,
  33. you can instantiate a different instance of Random() in each thread to get
  34. generators that don\'t share state, then use .setstate() and .jumpahead() to
  35. move the generators to disjoint segments of the full period.  For example,
  36.  
  37. def create_generators(num, delta, firstseed=None):
  38.     """Return list of num distinct generators.
  39.     Each generator has its own unique segment of delta elements from
  40.     Random.random()\'s full period.
  41.     Seed the first generator with optional arg firstseed (default is
  42.     None, to seed from current time).
  43.     """
  44.  
  45.     from random import Random
  46.     g = Random(firstseed)
  47.     result = [g]
  48.     for i in range(num - 1):
  49.         laststate = g.getstate()
  50.         g = Random()
  51.         g.setstate(laststate)
  52.         g.jumpahead(delta)
  53.         result.append(g)
  54.     return result
  55.  
  56. gens = create_generators(10, 1000000)
  57.  
  58. That creates 10 distinct generators, which can be passed out to 10 distinct
  59. threads.  The generators don\'t share state so can be called safely in
  60. parallel.  So long as no thread calls its g.random() more than a million
  61. times (the second argument to create_generators), the sequences seen by
  62. each thread will not overlap.
  63.  
  64. The period of the underlying Wichmann-Hill generator is 6,953,607,871,644,
  65. and that limits how far this technique can be pushed.
  66.  
  67. Just for fun, note that since we know the period, .jumpahead() can also be
  68. used to "move backward in time":
  69.  
  70. >>> g = Random(42)  # arbitrary
  71. >>> g.random()
  72. 0.25420336316883324
  73. >>> g.jumpahead(6953607871644L - 1) # move *back* one
  74. >>> g.random()
  75. 0.25420336316883324
  76. '''
  77. from math import log as _log, exp as _exp, pi as _pi, e as _e
  78. from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
  79. __all__ = [
  80.     'Random',
  81.     'seed',
  82.     'random',
  83.     'uniform',
  84.     'randint',
  85.     'choice',
  86.     'randrange',
  87.     'shuffle',
  88.     'normalvariate',
  89.     'lognormvariate',
  90.     'cunifvariate',
  91.     'expovariate',
  92.     'vonmisesvariate',
  93.     'gammavariate',
  94.     'stdgamma',
  95.     'gauss',
  96.     'betavariate',
  97.     'paretovariate',
  98.     'weibullvariate',
  99.     'getstate',
  100.     'setstate',
  101.     'jumpahead',
  102.     'whseed']
  103.  
  104. def _verify(name, computed, expected):
  105.     if abs(computed - expected) > 9.9999999999999995e-008:
  106.         raise ValueError('computed value for %s deviates too much (computed %g, expected %g)' % (name, computed, expected))
  107.     
  108.  
  109. NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0)
  110. _verify('NV_MAGICCONST', NV_MAGICCONST, 1.71552776992141)
  111. TWOPI = 2.0 * _pi
  112. _verify('TWOPI', TWOPI, 6.2831853071800001)
  113. LOG4 = _log(4.0)
  114. _verify('LOG4', LOG4, 1.3862943611198899)
  115. SG_MAGICCONST = 1.0 + _log(4.5)
  116. _verify('SG_MAGICCONST', SG_MAGICCONST, 2.5040773967762702)
  117. del _verify
  118.  
  119. class Random:
  120.     VERSION = 1
  121.     
  122.     def __init__(self, x = None):
  123.         '''Initialize an instance.
  124.  
  125.         Optional argument x controls seeding, as for Random.seed().
  126.         '''
  127.         self.seed(x)
  128.         self.gauss_next = None
  129.  
  130.     
  131.     def seed(self, a = None):
  132.         '''Initialize internal state from hashable object.
  133.  
  134.         None or no argument seeds from current time.
  135.  
  136.         If a is not None or an int or long, hash(a) is used instead.
  137.  
  138.         If a is an int or long, a is used directly.  Distinct values between
  139.         0 and 27814431486575L inclusive are guaranteed to yield distinct
  140.         internal states (this guarantee is specific to the default
  141.         Wichmann-Hill generator).
  142.         '''
  143.         if a is None:
  144.             import time
  145.             a = long(time.time() * 256)
  146.         
  147.         if type(a) not in (type(3), type(0x3L)):
  148.             a = hash(a)
  149.         
  150.         (a, x) = divmod(a, 30268)
  151.         (a, y) = divmod(a, 30306)
  152.         (a, z) = divmod(a, 30322)
  153.         self._seed = (int(x) + 1, int(y) + 1, int(z) + 1)
  154.  
  155.     
  156.     def random(self):
  157.         '''Get the next random number in the range [0.0, 1.0).'''
  158.         (x, y, z) = self._seed
  159.         x = 171 * x % 30269
  160.         y = 172 * y % 30307
  161.         z = 170 * z % 30323
  162.         self._seed = (x, y, z)
  163.         return (x / 30269.0 + y / 30307.0 + z / 30323.0) % 1.0
  164.  
  165.     
  166.     def getstate(self):
  167.         '''Return internal state; can be passed to setstate() later.'''
  168.         return (self.VERSION, self._seed, self.gauss_next)
  169.  
  170.     
  171.     def setstate(self, state):
  172.         '''Restore internal state from object returned by getstate().'''
  173.         version = state[0]
  174.         if version == 1:
  175.             (version, self._seed, self.gauss_next) = state
  176.         else:
  177.             raise ValueError('state with version %s passed to Random.setstate() of version %s' % (version, self.VERSION))
  178.  
  179.     
  180.     def jumpahead(self, n):
  181.         '''Act as if n calls to random() were made, but quickly.
  182.  
  183.         n is an int, greater than or equal to 0.
  184.  
  185.         Example use:  If you have 2 threads and know that each will
  186.         consume no more than a million random numbers, create two Random
  187.         objects r1 and r2, then do
  188.             r2.setstate(r1.getstate())
  189.             r2.jumpahead(1000000)
  190.         Then r1 and r2 will use guaranteed-disjoint segments of the full
  191.         period.
  192.         '''
  193.         if not (n >= 0):
  194.             raise ValueError('n must be >= 0')
  195.         
  196.         (x, y, z) = self._seed
  197.         x = int(x * pow(171, n, 30269)) % 30269
  198.         y = int(y * pow(172, n, 30307)) % 30307
  199.         z = int(z * pow(170, n, 30323)) % 30323
  200.         self._seed = (x, y, z)
  201.  
  202.     
  203.     def __whseed(self, x = 0, y = 0, z = 0):
  204.         '''Set the Wichmann-Hill seed from (x, y, z).
  205.  
  206.         These must be integers in the range [0, 256).
  207.         '''
  208.         if not None if type(y) == type(y) and type(z) == type(z) else type(z) == type(0):
  209.             raise TypeError('seeds must be integers')
  210.         
  211.         if x <= x:
  212.             pass
  213.         elif x < 256:
  214.             if y <= y:
  215.                 pass
  216.             elif y < 256:
  217.                 pass
  218.         if not None if z <= z else z < 256:
  219.             raise ValueError('seeds must be in range(0, 256)')
  220.         
  221.         if x == x and y == y:
  222.             pass
  223.         elif y == z:
  224.             import time
  225.             t = long(time.time() * 256)
  226.             t = int(t & 16777215 ^ t >> 24)
  227.             (t, x) = divmod(t, 256)
  228.             (t, y) = divmod(t, 256)
  229.             (t, z) = divmod(t, 256)
  230.         
  231.         if not x:
  232.             pass
  233.         if not y:
  234.             pass
  235.         if not z:
  236.             pass
  237.         self._seed = (1, 1, 1)
  238.  
  239.     
  240.     def whseed(self, a = None):
  241.         """Seed from hashable object's hash code.
  242.  
  243.         None or no argument seeds from current time.  It is not guaranteed
  244.         that objects with distinct hash codes lead to distinct internal
  245.         states.
  246.  
  247.         This is obsolete, provided for compatibility with the seed routine
  248.         used prior to Python 2.1.  Use the .seed() method instead.
  249.         """
  250.         if a is None:
  251.             self._Random__whseed()
  252.             return None
  253.         
  254.         a = hash(a)
  255.         (a, x) = divmod(a, 256)
  256.         (a, y) = divmod(a, 256)
  257.         (a, z) = divmod(a, 256)
  258.         if not (x + a) % 256:
  259.             pass
  260.         x = 1
  261.         if not (y + a) % 256:
  262.             pass
  263.         y = 1
  264.         if not (z + a) % 256:
  265.             pass
  266.         z = 1
  267.         self._Random__whseed(x, y, z)
  268.  
  269.     
  270.     def __getstate__(self):
  271.         return self.getstate()
  272.  
  273.     
  274.     def __setstate__(self, state):
  275.         self.setstate(state)
  276.  
  277.     
  278.     def randrange(self, start, stop = None, step = 1, int = int, default = None):
  279.         """Choose a random item from range(start, stop[, step]).
  280.  
  281.         This fixes the problem with randint() which includes the
  282.         endpoint; in Python this is usually not what you want.
  283.         Do not supply the 'int' and 'default' arguments.
  284.         """
  285.         istart = int(start)
  286.         if istart != start:
  287.             raise ValueError, 'non-integer arg 1 for randrange()'
  288.         
  289.         if stop is default:
  290.             if istart > 0:
  291.                 return int(self.random() * istart)
  292.             
  293.             raise ValueError, 'empty range for randrange()'
  294.         
  295.         istop = int(stop)
  296.         if istop != stop:
  297.             raise ValueError, 'non-integer stop for randrange()'
  298.         
  299.         if step == 1:
  300.             if istart < istop:
  301.                 return istart + int(self.random() * (istop - istart))
  302.             
  303.             raise ValueError, 'empty range for randrange()'
  304.         
  305.         istep = int(step)
  306.         if istep != step:
  307.             raise ValueError, 'non-integer step for randrange()'
  308.         
  309.         if istep > 0:
  310.             n = ((istop - istart) + istep - 1) / istep
  311.         elif istep < 0:
  312.             n = ((istop - istart) + istep + 1) / istep
  313.         else:
  314.             raise ValueError, 'zero step for randrange()'
  315.         if n <= 0:
  316.             raise ValueError, 'empty range for randrange()'
  317.         
  318.         return istart + istep * int(self.random() * n)
  319.  
  320.     
  321.     def randint(self, a, b):
  322.         '''Return random integer in range [a, b], including both end points.
  323.  
  324.         (Deprecated; use randrange(a, b+1).)
  325.         '''
  326.         return self.randrange(a, b + 1)
  327.  
  328.     
  329.     def choice(self, seq):
  330.         '''Choose a random element from a non-empty sequence.'''
  331.         return seq[int(self.random() * len(seq))]
  332.  
  333.     
  334.     def shuffle(self, x, random = None, int = int):
  335.         '''x, random=random.random -> shuffle list x in place; return None.
  336.  
  337.         Optional arg random is a 0-argument function returning a random
  338.         float in [0.0, 1.0); by default, the standard random.random.
  339.  
  340.         Note that for even rather small len(x), the total number of
  341.         permutations of x is larger than the period of most random number
  342.         generators; this implies that "most" permutations of a long
  343.         sequence can never be generated.
  344.         '''
  345.         if random is None:
  346.             random = self.random
  347.         
  348.         for i in xrange(len(x) - 1, 0, -1):
  349.             j = int(random() * (i + 1))
  350.             (x[i], x[j]) = (x[j], x[i])
  351.         
  352.  
  353.     
  354.     def uniform(self, a, b):
  355.         '''Get a random number in the range [a, b).'''
  356.         return a + (b - a) * self.random()
  357.  
  358.     
  359.     def normalvariate(self, mu, sigma):
  360.         random = self.random
  361.         while 1:
  362.             u1 = random()
  363.             u2 = random()
  364.             z = NV_MAGICCONST * (u1 - 0.5) / u2
  365.             zz = z * z / 4.0
  366.             if zz <= -_log(u2):
  367.                 break
  368.             
  369.         return mu + z * sigma
  370.  
  371.     
  372.     def lognormvariate(self, mu, sigma):
  373.         return _exp(self.normalvariate(mu, sigma))
  374.  
  375.     
  376.     def cunifvariate(self, mean, arc):
  377.         return (mean + arc * (self.random() - 0.5)) % _pi
  378.  
  379.     
  380.     def expovariate(self, lambd):
  381.         random = self.random
  382.         u = random()
  383.         while u <= 9.9999999999999995e-008:
  384.             u = random()
  385.         return -_log(u) / lambd
  386.  
  387.     
  388.     def vonmisesvariate(self, mu, kappa):
  389.         random = self.random
  390.         if kappa <= 9.9999999999999995e-007:
  391.             return TWOPI * random()
  392.         
  393.         a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)
  394.         b = (a - _sqrt(2.0 * a)) / (2.0 * kappa)
  395.         r = (1.0 + b * b) / (2.0 * b)
  396.         while 1:
  397.             u1 = random()
  398.             z = _cos(_pi * u1)
  399.             f = (1.0 + r * z) / (r + z)
  400.             c = kappa * (r - f)
  401.             u2 = random()
  402.             if u2 >= c * (2.0 - c):
  403.                 pass
  404.             if not (u2 > c * _exp(1.0 - c)):
  405.                 break
  406.             
  407.         u3 = random()
  408.         if u3 > 0.5:
  409.             theta = mu % TWOPI + _acos(f)
  410.         else:
  411.             theta = mu % TWOPI - _acos(f)
  412.         return theta
  413.  
  414.     
  415.     def gammavariate(self, alpha, beta):
  416.         ainv = _sqrt(2.0 * alpha - 1.0)
  417.         return beta * self.stdgamma(alpha, ainv, alpha - LOG4, alpha + ainv)
  418.  
  419.     
  420.     def stdgamma(self, alpha, ainv, bbb, ccc):
  421.         random = self.random
  422.         if alpha <= 0.0:
  423.             raise ValueError, 'stdgamma: alpha must be > 0.0'
  424.         
  425.         if alpha > 1.0:
  426.             while 1:
  427.                 u1 = random()
  428.                 u2 = random()
  429.                 v = _log(u1 / (1.0 - u1)) / ainv
  430.                 x = alpha * _exp(v)
  431.                 z = u1 * u1 * u2
  432.                 r = bbb + ccc * v - x
  433.                 if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= _log(z):
  434.                     return x
  435.                 
  436.         elif alpha == 1.0:
  437.             u = random()
  438.             while u <= 9.9999999999999995e-008:
  439.                 u = random()
  440.             return -_log(u)
  441.         else:
  442.             while 1:
  443.                 u = random()
  444.                 b = (_e + alpha) / _e
  445.                 p = b * u
  446.                 if p <= 1.0:
  447.                     x = pow(p, 1.0 / alpha)
  448.                 else:
  449.                     x = -_log((b - p) / alpha)
  450.                 u1 = random()
  451.                 if p <= 1.0 and u1 > _exp(-x) and p > 1:
  452.                     pass
  453.                 if not (u1 > pow(x, alpha - 1.0)):
  454.                     break
  455.                 
  456.             return x
  457.  
  458.     
  459.     def gauss(self, mu, sigma):
  460.         random = self.random
  461.         z = self.gauss_next
  462.         self.gauss_next = None
  463.         if z is None:
  464.             x2pi = random() * TWOPI
  465.             g2rad = _sqrt(-2.0 * _log(1.0 - random()))
  466.             z = _cos(x2pi) * g2rad
  467.             self.gauss_next = _sin(x2pi) * g2rad
  468.         
  469.         return mu + z * sigma
  470.  
  471.     
  472.     def betavariate(self, alpha, beta):
  473.         y = self.gammavariate(alpha, 1.0)
  474.         if y == 0:
  475.             return 0.0
  476.         else:
  477.             return y / (y + self.gammavariate(beta, 1.0))
  478.  
  479.     
  480.     def paretovariate(self, alpha):
  481.         u = self.random()
  482.         return 1.0 / pow(u, 1.0 / alpha)
  483.  
  484.     
  485.     def weibullvariate(self, alpha, beta):
  486.         u = self.random()
  487.         return alpha * pow(-_log(u), 1.0 / beta)
  488.  
  489.  
  490.  
  491. def _test_generator(n, funccall):
  492.     import time
  493.     print n, 'times', funccall
  494.     code = compile(funccall, funccall, 'eval')
  495.     sum = 0.0
  496.     sqsum = 0.0
  497.     smallest = 10000000000.0
  498.     largest = -10000000000.0
  499.     t0 = time.time()
  500.     for i in range(n):
  501.         x = eval(code)
  502.         sum = sum + x
  503.         sqsum = sqsum + x * x
  504.         smallest = min(x, smallest)
  505.         largest = max(x, largest)
  506.     
  507.     t1 = time.time()
  508.     print round(t1 - t0, 3), 'sec,',
  509.     avg = sum / n
  510.     stddev = _sqrt(sqsum / n - avg * avg)
  511.     print 'avg %g, stddev %g, min %g, max %g' % (avg, stddev, smallest, largest)
  512.  
  513.  
  514. def _test(N = 200):
  515.     print 'TWOPI         =', TWOPI
  516.     print 'LOG4          =', LOG4
  517.     print 'NV_MAGICCONST =', NV_MAGICCONST
  518.     print 'SG_MAGICCONST =', SG_MAGICCONST
  519.     _test_generator(N, 'random()')
  520.     _test_generator(N, 'normalvariate(0.0, 1.0)')
  521.     _test_generator(N, 'lognormvariate(0.0, 1.0)')
  522.     _test_generator(N, 'cunifvariate(0.0, 1.0)')
  523.     _test_generator(N, 'expovariate(1.0)')
  524.     _test_generator(N, 'vonmisesvariate(0.0, 1.0)')
  525.     _test_generator(N, 'gammavariate(0.5, 1.0)')
  526.     _test_generator(N, 'gammavariate(0.9, 1.0)')
  527.     _test_generator(N, 'gammavariate(1.0, 1.0)')
  528.     _test_generator(N, 'gammavariate(2.0, 1.0)')
  529.     _test_generator(N, 'gammavariate(20.0, 1.0)')
  530.     _test_generator(N, 'gammavariate(200.0, 1.0)')
  531.     _test_generator(N, 'gauss(0.0, 1.0)')
  532.     _test_generator(N, 'betavariate(3.0, 3.0)')
  533.     _test_generator(N, 'paretovariate(1.0)')
  534.     _test_generator(N, 'weibullvariate(1.0, 1.0)')
  535.     s = getstate()
  536.     jumpahead(N)
  537.     r1 = random()
  538.     setstate(s)
  539.     for i in range(N):
  540.         random()
  541.     
  542.     r2 = random()
  543.     if r1 != r2:
  544.         raise ValueError('jumpahead test failed ' + `(N, r1, r2)`)
  545.     
  546.  
  547. _inst = Random()
  548. seed = _inst.seed
  549. random = _inst.random
  550. uniform = _inst.uniform
  551. randint = _inst.randint
  552. choice = _inst.choice
  553. randrange = _inst.randrange
  554. shuffle = _inst.shuffle
  555. normalvariate = _inst.normalvariate
  556. lognormvariate = _inst.lognormvariate
  557. cunifvariate = _inst.cunifvariate
  558. expovariate = _inst.expovariate
  559. vonmisesvariate = _inst.vonmisesvariate
  560. gammavariate = _inst.gammavariate
  561. stdgamma = _inst.stdgamma
  562. gauss = _inst.gauss
  563. betavariate = _inst.betavariate
  564. paretovariate = _inst.paretovariate
  565. weibullvariate = _inst.weibullvariate
  566. getstate = _inst.getstate
  567. setstate = _inst.setstate
  568. jumpahead = _inst.jumpahead
  569. whseed = _inst.whseed
  570. if __name__ == '__main__':
  571.     _test()
  572.  
  573.