Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1 | """Random variable generators. |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 2 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 3 | integers |
| 4 | -------- |
| 5 | uniform within range |
| 6 | |
| 7 | sequences |
| 8 | --------- |
| 9 | pick random element |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 10 | pick random sample |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 11 | generate random permutation |
| 12 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 13 | distributions on the real line: |
| 14 | ------------------------------ |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 15 | uniform |
Raymond Hettinger | bbc50ea | 2008-03-23 13:32:32 +0000 | [diff] [blame] | 16 | triangular |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 17 | normal (Gaussian) |
| 18 | lognormal |
| 19 | negative exponential |
| 20 | gamma |
| 21 | beta |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 22 | pareto |
| 23 | Weibull |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 24 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 25 | distributions on the circle (angles 0 to 2pi) |
| 26 | --------------------------------------------- |
| 27 | circular uniform |
| 28 | von Mises |
| 29 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 30 | General notes on the underlying Mersenne Twister core generator: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 31 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 32 | * The period is 2**19937-1. |
Tim Peters | 0e11595 | 2006-06-10 22:51:45 +0000 | [diff] [blame] | 33 | * It is one of the most extensively tested generators in existence. |
| 34 | * Without a direct way to compute N steps forward, the semantics of |
| 35 | jumpahead(n) are weakened to simply jump to another distant state and rely |
| 36 | on the large period to avoid overlapping sequences. |
| 37 | * The random() method is implemented in C, executes in a single Python step, |
| 38 | and is, therefore, threadsafe. |
Tim Peters | e360d95 | 2001-01-26 10:00:39 +0000 | [diff] [blame] | 39 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 40 | """ |
Guido van Rossum | d03e119 | 1998-05-29 17:51:31 +0000 | [diff] [blame] | 41 | |
Raymond Hettinger | c4f7bab | 2008-03-23 19:37:53 +0000 | [diff] [blame] | 42 | from __future__ import division |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 43 | from warnings import warn as _warn |
| 44 | from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType |
Raymond Hettinger | 91e27c2 | 2005-08-19 01:36:35 +0000 | [diff] [blame] | 45 | from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 46 | from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin |
Raymond Hettinger | c1c43ca | 2004-09-05 00:00:42 +0000 | [diff] [blame] | 47 | from os import urandom as _urandom |
| 48 | from binascii import hexlify as _hexlify |
Raymond Hettinger | ffd2a42 | 2010-09-10 10:47:22 +0000 | [diff] [blame] | 49 | import hashlib as _hashlib |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 50 | |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 51 | __all__ = ["Random","seed","random","uniform","randint","choice","sample", |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 52 | "randrange","shuffle","normalvariate","lognormvariate", |
Raymond Hettinger | bbc50ea | 2008-03-23 13:32:32 +0000 | [diff] [blame] | 53 | "expovariate","vonmisesvariate","gammavariate","triangular", |
Raymond Hettinger | f8a52d3 | 2003-08-05 12:23:19 +0000 | [diff] [blame] | 54 | "gauss","betavariate","paretovariate","weibullvariate", |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 55 | "getstate","setstate","jumpahead", "WichmannHill", "getrandbits", |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 56 | "SystemRandom"] |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 57 | |
| 58 | NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 59 | TWOPI = 2.0*_pi |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 60 | LOG4 = _log(4.0) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 61 | SG_MAGICCONST = 1.0 + _log(4.5) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 62 | BPF = 53 # Number of bits in a float |
Tim Peters | 7c2a85b | 2004-08-31 02:19:55 +0000 | [diff] [blame] | 63 | RECIP_BPF = 2**-BPF |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 64 | |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 65 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 66 | # Translated by Guido van Rossum from C source provided by |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 67 | # Adrian Baddeley. Adapted by Raymond Hettinger for use with |
Raymond Hettinger | 3fa19d7 | 2004-08-31 01:05:15 +0000 | [diff] [blame] | 68 | # the Mersenne Twister and os.urandom() core generators. |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 69 | |
Raymond Hettinger | 145a4a0 | 2003-01-07 10:25:55 +0000 | [diff] [blame] | 70 | import _random |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 71 | |
Raymond Hettinger | 145a4a0 | 2003-01-07 10:25:55 +0000 | [diff] [blame] | 72 | class Random(_random.Random): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 73 | """Random number generator base class used by bound module functions. |
| 74 | |
| 75 | Used to instantiate instances of Random to get generators that don't |
| 76 | share state. Especially useful for multi-threaded programs, creating |
| 77 | a different instance of Random for each thread, and using the jumpahead() |
| 78 | method to ensure that the generated sequences seen by each thread don't |
| 79 | overlap. |
| 80 | |
| 81 | Class Random can also be subclassed if you want to use a different basic |
| 82 | generator of your own devising: in that case, override the following |
Benjamin Peterson | f2eb2b4 | 2008-07-30 13:46:53 +0000 | [diff] [blame] | 83 | methods: random(), seed(), getstate(), setstate() and jumpahead(). |
| 84 | Optionally, implement a getrandbits() method so that randrange() can cover |
| 85 | arbitrarily large ranges. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 86 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 87 | """ |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 88 | |
Martin v. Löwis | 6b449f4 | 2007-12-03 19:20:02 +0000 | [diff] [blame] | 89 | VERSION = 3 # used by getstate/setstate |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 90 | |
| 91 | def __init__(self, x=None): |
| 92 | """Initialize an instance. |
| 93 | |
| 94 | Optional argument x controls seeding, as for Random.seed(). |
| 95 | """ |
| 96 | |
| 97 | self.seed(x) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 98 | self.gauss_next = None |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 99 | |
Tim Peters | 0de88fc | 2001-02-01 04:59:18 +0000 | [diff] [blame] | 100 | def seed(self, a=None): |
| 101 | """Initialize internal state from hashable object. |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 102 | |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 103 | None or no argument seeds from current time or from an operating |
| 104 | system specific randomness source if available. |
Tim Peters | 0de88fc | 2001-02-01 04:59:18 +0000 | [diff] [blame] | 105 | |
Tim Peters | bcd725f | 2001-02-01 10:06:53 +0000 | [diff] [blame] | 106 | If a is not None or an int or long, hash(a) is used instead. |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 107 | """ |
| 108 | |
Raymond Hettinger | 3081d59 | 2003-08-09 18:30:57 +0000 | [diff] [blame] | 109 | if a is None: |
Raymond Hettinger | c1c43ca | 2004-09-05 00:00:42 +0000 | [diff] [blame] | 110 | try: |
Raymond Hettinger | ddb39e7 | 2014-05-13 22:09:23 -0700 | [diff] [blame] | 111 | # Seed with enough bytes to span the 19937 bit |
| 112 | # state space for the Mersenne Twister |
| 113 | a = long(_hexlify(_urandom(2500)), 16) |
Raymond Hettinger | c1c43ca | 2004-09-05 00:00:42 +0000 | [diff] [blame] | 114 | except NotImplementedError: |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 115 | import time |
| 116 | a = long(time.time() * 256) # use fractional seconds |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 117 | |
Raymond Hettinger | 145a4a0 | 2003-01-07 10:25:55 +0000 | [diff] [blame] | 118 | super(Random, self).seed(a) |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 119 | self.gauss_next = None |
| 120 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 121 | def getstate(self): |
| 122 | """Return internal state; can be passed to setstate() later.""" |
Raymond Hettinger | 145a4a0 | 2003-01-07 10:25:55 +0000 | [diff] [blame] | 123 | return self.VERSION, super(Random, self).getstate(), self.gauss_next |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 124 | |
| 125 | def setstate(self, state): |
| 126 | """Restore internal state from object returned by getstate().""" |
| 127 | version = state[0] |
Martin v. Löwis | 6b449f4 | 2007-12-03 19:20:02 +0000 | [diff] [blame] | 128 | if version == 3: |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 129 | version, internalstate, self.gauss_next = state |
Raymond Hettinger | 145a4a0 | 2003-01-07 10:25:55 +0000 | [diff] [blame] | 130 | super(Random, self).setstate(internalstate) |
Martin v. Löwis | 6b449f4 | 2007-12-03 19:20:02 +0000 | [diff] [blame] | 131 | elif version == 2: |
| 132 | version, internalstate, self.gauss_next = state |
| 133 | # In version 2, the state was saved as signed ints, which causes |
| 134 | # inconsistencies between 32/64-bit systems. The state is |
| 135 | # really unsigned 32-bit ints, so we convert negative ints from |
| 136 | # version 2 to positive longs for version 3. |
| 137 | try: |
| 138 | internalstate = tuple( long(x) % (2**32) for x in internalstate ) |
| 139 | except ValueError, e: |
| 140 | raise TypeError, e |
| 141 | super(Random, self).setstate(internalstate) |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 142 | else: |
| 143 | raise ValueError("state with version %s passed to " |
| 144 | "Random.setstate() of version %s" % |
| 145 | (version, self.VERSION)) |
| 146 | |
Raymond Hettinger | ffd2a42 | 2010-09-10 10:47:22 +0000 | [diff] [blame] | 147 | def jumpahead(self, n): |
| 148 | """Change the internal state to one that is likely far away |
| 149 | from the current state. This method will not be in Py3.x, |
| 150 | so it is better to simply reseed. |
| 151 | """ |
| 152 | # The super.jumpahead() method uses shuffling to change state, |
| 153 | # so it needs a large and "interesting" n to work with. Here, |
| 154 | # we use hashing to create a large n for the shuffle. |
| 155 | s = repr(n) + repr(self.getstate()) |
| 156 | n = int(_hashlib.new('sha512', s).hexdigest(), 16) |
| 157 | super(Random, self).jumpahead(n) |
| 158 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 159 | ## ---- Methods below this point do not need to be overridden when |
| 160 | ## ---- subclassing for the purpose of using a different core generator. |
| 161 | |
| 162 | ## -------------------- pickle support ------------------- |
| 163 | |
| 164 | def __getstate__(self): # for pickle |
| 165 | return self.getstate() |
| 166 | |
| 167 | def __setstate__(self, state): # for pickle |
| 168 | self.setstate(state) |
| 169 | |
Raymond Hettinger | 5f078ff | 2003-06-24 20:29:04 +0000 | [diff] [blame] | 170 | def __reduce__(self): |
| 171 | return self.__class__, (), self.getstate() |
| 172 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 173 | ## -------------------- integer methods ------------------- |
| 174 | |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 175 | def randrange(self, start, stop=None, step=1, _int=int, _maxwidth=1L<<BPF): |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 176 | """Choose a random item from range(start, stop[, step]). |
| 177 | |
| 178 | This fixes the problem with randint() which includes the |
| 179 | endpoint; in Python this is usually not what you want. |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 180 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 181 | """ |
| 182 | |
| 183 | # This code is a bit messy to make it fast for the |
Tim Peters | 9146f27 | 2002-08-16 03:41:39 +0000 | [diff] [blame] | 184 | # common case while still doing adequate error checking. |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 185 | istart = _int(start) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 186 | if istart != start: |
| 187 | raise ValueError, "non-integer arg 1 for randrange()" |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 188 | if stop is None: |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 189 | if istart > 0: |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 190 | if istart >= _maxwidth: |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 191 | return self._randbelow(istart) |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 192 | return _int(self.random() * istart) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 193 | raise ValueError, "empty range for randrange()" |
Tim Peters | 9146f27 | 2002-08-16 03:41:39 +0000 | [diff] [blame] | 194 | |
| 195 | # stop argument supplied. |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 196 | istop = _int(stop) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 197 | if istop != stop: |
| 198 | raise ValueError, "non-integer stop for randrange()" |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 199 | width = istop - istart |
| 200 | if step == 1 and width > 0: |
Tim Peters | 76ca1d4 | 2003-06-19 03:46:46 +0000 | [diff] [blame] | 201 | # Note that |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 202 | # int(istart + self.random()*width) |
Tim Peters | 76ca1d4 | 2003-06-19 03:46:46 +0000 | [diff] [blame] | 203 | # instead would be incorrect. For example, consider istart |
| 204 | # = -2 and istop = 0. Then the guts would be in |
| 205 | # -2.0 to 0.0 exclusive on both ends (ignoring that random() |
| 206 | # might return 0.0), and because int() truncates toward 0, the |
| 207 | # final result would be -1 or 0 (instead of -2 or -1). |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 208 | # istart + int(self.random()*width) |
Tim Peters | 76ca1d4 | 2003-06-19 03:46:46 +0000 | [diff] [blame] | 209 | # would also be incorrect, for a subtler reason: the RHS |
| 210 | # can return a long, and then randrange() would also return |
| 211 | # a long, but we're supposed to return an int (for backward |
| 212 | # compatibility). |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 213 | |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 214 | if width >= _maxwidth: |
| 215 | return _int(istart + self._randbelow(width)) |
| 216 | return _int(istart + _int(self.random()*width)) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 217 | if step == 1: |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 218 | raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width) |
Tim Peters | 9146f27 | 2002-08-16 03:41:39 +0000 | [diff] [blame] | 219 | |
| 220 | # Non-unit step argument supplied. |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 221 | istep = _int(step) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 222 | if istep != step: |
| 223 | raise ValueError, "non-integer step for randrange()" |
| 224 | if istep > 0: |
Raymond Hettinger | ffdb8bb | 2004-09-27 15:29:05 +0000 | [diff] [blame] | 225 | n = (width + istep - 1) // istep |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 226 | elif istep < 0: |
Raymond Hettinger | ffdb8bb | 2004-09-27 15:29:05 +0000 | [diff] [blame] | 227 | n = (width + istep + 1) // istep |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 228 | else: |
| 229 | raise ValueError, "zero step for randrange()" |
| 230 | |
| 231 | if n <= 0: |
| 232 | raise ValueError, "empty range for randrange()" |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 233 | |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 234 | if n >= _maxwidth: |
Raymond Hettinger | 94547f7 | 2006-12-20 06:42:06 +0000 | [diff] [blame] | 235 | return istart + istep*self._randbelow(n) |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 236 | return istart + istep*_int(self.random() * n) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 237 | |
| 238 | def randint(self, a, b): |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 239 | """Return random integer in range [a, b], including both end points. |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 240 | """ |
| 241 | |
| 242 | return self.randrange(a, b+1) |
| 243 | |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 244 | def _randbelow(self, n, _log=_log, _int=int, _maxwidth=1L<<BPF, |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 245 | _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType): |
| 246 | """Return a random int in the range [0,n) |
| 247 | |
| 248 | Handles the case where n has more bits than returned |
| 249 | by a single call to the underlying generator. |
| 250 | """ |
| 251 | |
| 252 | try: |
| 253 | getrandbits = self.getrandbits |
| 254 | except AttributeError: |
| 255 | pass |
| 256 | else: |
| 257 | # Only call self.getrandbits if the original random() builtin method |
| 258 | # has not been overridden or if a new getrandbits() was supplied. |
| 259 | # This assures that the two methods correspond. |
| 260 | if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method: |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 261 | k = _int(1.00001 + _log(n-1, 2.0)) # 2**k > n-1 > 2**(k-2) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 262 | r = getrandbits(k) |
| 263 | while r >= n: |
| 264 | r = getrandbits(k) |
| 265 | return r |
| 266 | if n >= _maxwidth: |
| 267 | _warn("Underlying random() generator does not supply \n" |
| 268 | "enough bits to choose from a population range this large") |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 269 | return _int(self.random() * n) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 270 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 271 | ## -------------------- sequence methods ------------------- |
| 272 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 273 | def choice(self, seq): |
| 274 | """Choose a random element from a non-empty sequence.""" |
Raymond Hettinger | 5dae505 | 2004-06-07 02:07:15 +0000 | [diff] [blame] | 275 | return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 276 | |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 277 | def shuffle(self, x, random=None): |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 278 | """x, random=random.random -> shuffle list x in place; return None. |
| 279 | |
| 280 | Optional arg random is a 0-argument function returning a random |
| 281 | float in [0.0, 1.0); by default, the standard random.random. |
Senthil Kumaran | 37851d0 | 2013-09-11 22:52:58 -0700 | [diff] [blame] | 282 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 283 | """ |
| 284 | |
| 285 | if random is None: |
| 286 | random = self.random |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 287 | _int = int |
Raymond Hettinger | 85c20a4 | 2003-11-06 14:06:48 +0000 | [diff] [blame] | 288 | for i in reversed(xrange(1, len(x))): |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 289 | # pick an element in x[:i+1] with which to exchange x[i] |
Raymond Hettinger | 8dc1692 | 2013-10-05 21:34:48 -0700 | [diff] [blame] | 290 | j = _int(random() * (i+1)) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 291 | x[i], x[j] = x[j], x[i] |
| 292 | |
Raymond Hettinger | fdbe522 | 2003-06-13 07:01:51 +0000 | [diff] [blame] | 293 | def sample(self, population, k): |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 294 | """Chooses k unique random elements from a population sequence. |
| 295 | |
Raymond Hettinger | c0b4034 | 2002-11-13 15:26:37 +0000 | [diff] [blame] | 296 | Returns a new list containing elements from the population while |
| 297 | leaving the original population unchanged. The resulting list is |
| 298 | in selection order so that all sub-slices will also be valid random |
| 299 | samples. This allows raffle winners (the sample) to be partitioned |
| 300 | into grand prize and second place winners (the subslices). |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 301 | |
Raymond Hettinger | c0b4034 | 2002-11-13 15:26:37 +0000 | [diff] [blame] | 302 | Members of the population need not be hashable or unique. If the |
| 303 | population contains repeats, then each occurrence is a possible |
| 304 | selection in the sample. |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 305 | |
Raymond Hettinger | c0b4034 | 2002-11-13 15:26:37 +0000 | [diff] [blame] | 306 | To choose a sample in a range of integers, use xrange as an argument. |
| 307 | This is especially fast and space efficient for sampling from a |
| 308 | large population: sample(xrange(10000000), 60) |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 309 | """ |
| 310 | |
Raymond Hettinger | c0b4034 | 2002-11-13 15:26:37 +0000 | [diff] [blame] | 311 | # Sampling without replacement entails tracking either potential |
Raymond Hettinger | 91e27c2 | 2005-08-19 01:36:35 +0000 | [diff] [blame] | 312 | # selections (the pool) in a list or previous selections in a set. |
Raymond Hettinger | c0b4034 | 2002-11-13 15:26:37 +0000 | [diff] [blame] | 313 | |
Jeremy Hylton | 2b55d35 | 2004-02-23 17:27:57 +0000 | [diff] [blame] | 314 | # When the number of selections is small compared to the |
| 315 | # population, then tracking selections is efficient, requiring |
Raymond Hettinger | 91e27c2 | 2005-08-19 01:36:35 +0000 | [diff] [blame] | 316 | # only a small set and an occasional reselection. For |
Jeremy Hylton | 2b55d35 | 2004-02-23 17:27:57 +0000 | [diff] [blame] | 317 | # a larger number of selections, the pool tracking method is |
| 318 | # preferred since the list takes less space than the |
Raymond Hettinger | 91e27c2 | 2005-08-19 01:36:35 +0000 | [diff] [blame] | 319 | # set and it doesn't suffer from frequent reselections. |
Raymond Hettinger | c0b4034 | 2002-11-13 15:26:37 +0000 | [diff] [blame] | 320 | |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 321 | n = len(population) |
| 322 | if not 0 <= k <= n: |
Raymond Hettinger | 22d8f7b | 2011-05-18 17:28:50 -0500 | [diff] [blame] | 323 | raise ValueError("sample larger than population") |
Raymond Hettinger | 8b9aa8d | 2003-01-04 05:20:33 +0000 | [diff] [blame] | 324 | random = self.random |
Raymond Hettinger | fdbe522 | 2003-06-13 07:01:51 +0000 | [diff] [blame] | 325 | _int = int |
Raymond Hettinger | c0b4034 | 2002-11-13 15:26:37 +0000 | [diff] [blame] | 326 | result = [None] * k |
Raymond Hettinger | 91e27c2 | 2005-08-19 01:36:35 +0000 | [diff] [blame] | 327 | setsize = 21 # size of a small set minus size of an empty list |
| 328 | if k > 5: |
Tim Peters | 9e34c04 | 2005-08-26 15:20:46 +0000 | [diff] [blame] | 329 | setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets |
Tim Peters | c17976e | 2006-04-01 00:26:53 +0000 | [diff] [blame] | 330 | if n <= setsize or hasattr(population, "keys"): |
| 331 | # An n-length list is smaller than a k-length set, or this is a |
| 332 | # mapping type so the other algorithm wouldn't work. |
Raymond Hettinger | 311f419 | 2002-11-18 09:01:24 +0000 | [diff] [blame] | 333 | pool = list(population) |
| 334 | for i in xrange(k): # invariant: non-selected at [0,n-i) |
Raymond Hettinger | fdbe522 | 2003-06-13 07:01:51 +0000 | [diff] [blame] | 335 | j = _int(random() * (n-i)) |
Raymond Hettinger | 311f419 | 2002-11-18 09:01:24 +0000 | [diff] [blame] | 336 | result[i] = pool[j] |
Raymond Hettinger | 8b9aa8d | 2003-01-04 05:20:33 +0000 | [diff] [blame] | 337 | pool[j] = pool[n-i-1] # move non-selected item into vacancy |
Raymond Hettinger | c0b4034 | 2002-11-13 15:26:37 +0000 | [diff] [blame] | 338 | else: |
Raymond Hettinger | 66d09f1 | 2003-09-06 04:25:54 +0000 | [diff] [blame] | 339 | try: |
Raymond Hettinger | 3c3346d | 2006-03-29 09:13:13 +0000 | [diff] [blame] | 340 | selected = set() |
| 341 | selected_add = selected.add |
| 342 | for i in xrange(k): |
Raymond Hettinger | fdbe522 | 2003-06-13 07:01:51 +0000 | [diff] [blame] | 343 | j = _int(random() * n) |
Raymond Hettinger | 3c3346d | 2006-03-29 09:13:13 +0000 | [diff] [blame] | 344 | while j in selected: |
| 345 | j = _int(random() * n) |
| 346 | selected_add(j) |
| 347 | result[i] = population[j] |
Tim Peters | c17976e | 2006-04-01 00:26:53 +0000 | [diff] [blame] | 348 | except (TypeError, KeyError): # handle (at least) sets |
Raymond Hettinger | 3c3346d | 2006-03-29 09:13:13 +0000 | [diff] [blame] | 349 | if isinstance(population, list): |
| 350 | raise |
Tim Peters | c17976e | 2006-04-01 00:26:53 +0000 | [diff] [blame] | 351 | return self.sample(tuple(population), k) |
Raymond Hettinger | 311f419 | 2002-11-18 09:01:24 +0000 | [diff] [blame] | 352 | return result |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 353 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 354 | ## -------------------- real-valued distributions ------------------- |
| 355 | |
| 356 | ## -------------------- uniform distribution ------------------- |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 357 | |
| 358 | def uniform(self, a, b): |
Raymond Hettinger | 2c0cdca | 2009-06-11 23:14:53 +0000 | [diff] [blame] | 359 | "Get a random number in the range [a, b) or [a, b] depending on rounding." |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 360 | return a + (b-a) * self.random() |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 361 | |
Raymond Hettinger | bbc50ea | 2008-03-23 13:32:32 +0000 | [diff] [blame] | 362 | ## -------------------- triangular -------------------- |
| 363 | |
Raymond Hettinger | c4f7bab | 2008-03-23 19:37:53 +0000 | [diff] [blame] | 364 | def triangular(self, low=0.0, high=1.0, mode=None): |
Raymond Hettinger | bbc50ea | 2008-03-23 13:32:32 +0000 | [diff] [blame] | 365 | """Triangular distribution. |
| 366 | |
| 367 | Continuous distribution bounded by given lower and upper limits, |
| 368 | and having a given mode value in-between. |
| 369 | |
| 370 | http://en.wikipedia.org/wiki/Triangular_distribution |
| 371 | |
| 372 | """ |
| 373 | u = self.random() |
Raymond Hettinger | 92df752 | 2014-05-25 17:40:25 -0700 | [diff] [blame^] | 374 | try: |
| 375 | c = 0.5 if mode is None else (mode - low) / (high - low) |
| 376 | except ZeroDivisionError: |
| 377 | return low |
Raymond Hettinger | bbc50ea | 2008-03-23 13:32:32 +0000 | [diff] [blame] | 378 | if u > c: |
Raymond Hettinger | c4f7bab | 2008-03-23 19:37:53 +0000 | [diff] [blame] | 379 | u = 1.0 - u |
| 380 | c = 1.0 - c |
Raymond Hettinger | bbc50ea | 2008-03-23 13:32:32 +0000 | [diff] [blame] | 381 | low, high = high, low |
| 382 | return low + (high - low) * (u * c) ** 0.5 |
| 383 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 384 | ## -------------------- normal distribution -------------------- |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 385 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 386 | def normalvariate(self, mu, sigma): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 387 | """Normal distribution. |
| 388 | |
| 389 | mu is the mean, and sigma is the standard deviation. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 390 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 391 | """ |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 392 | # mu = mean, sigma = standard deviation |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 393 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 394 | # Uses Kinderman and Monahan method. Reference: Kinderman, |
| 395 | # A.J. and Monahan, J.F., "Computer generation of random |
| 396 | # variables using the ratio of uniform deviates", ACM Trans |
| 397 | # Math Software, 3, (1977), pp257-260. |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 398 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 399 | random = self.random |
Raymond Hettinger | 42406e6 | 2005-04-30 09:02:51 +0000 | [diff] [blame] | 400 | while 1: |
Tim Peters | 0c9886d | 2001-01-15 01:18:21 +0000 | [diff] [blame] | 401 | u1 = random() |
Raymond Hettinger | 73ced7e | 2003-01-04 09:26:32 +0000 | [diff] [blame] | 402 | u2 = 1.0 - random() |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 403 | z = NV_MAGICCONST*(u1-0.5)/u2 |
| 404 | zz = z*z/4.0 |
| 405 | if zz <= -_log(u2): |
| 406 | break |
| 407 | return mu + z*sigma |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 408 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 409 | ## -------------------- lognormal distribution -------------------- |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 410 | |
| 411 | def lognormvariate(self, mu, sigma): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 412 | """Log normal distribution. |
| 413 | |
| 414 | If you take the natural logarithm of this distribution, you'll get a |
| 415 | normal distribution with mean mu and standard deviation sigma. |
| 416 | mu can have any value, and sigma must be greater than zero. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 417 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 418 | """ |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 419 | return _exp(self.normalvariate(mu, sigma)) |
| 420 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 421 | ## -------------------- exponential distribution -------------------- |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 422 | |
| 423 | def expovariate(self, lambd): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 424 | """Exponential distribution. |
| 425 | |
Mark Dickinson | e6dc531 | 2009-01-07 17:48:33 +0000 | [diff] [blame] | 426 | lambd is 1.0 divided by the desired mean. It should be |
| 427 | nonzero. (The parameter would be called "lambda", but that is |
| 428 | a reserved word in Python.) Returned values range from 0 to |
| 429 | positive infinity if lambd is positive, and from negative |
| 430 | infinity to 0 if lambd is negative. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 431 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 432 | """ |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 433 | # lambd: rate lambd = 1/mean |
| 434 | # ('lambda' is a Python reserved word) |
| 435 | |
Raymond Hettinger | cba8731 | 2011-06-25 11:24:35 +0200 | [diff] [blame] | 436 | # we use 1-random() instead of random() to preclude the |
| 437 | # possibility of taking the log of zero. |
| 438 | return -_log(1.0 - self.random())/lambd |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 439 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 440 | ## -------------------- von Mises distribution -------------------- |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 441 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 442 | def vonmisesvariate(self, mu, kappa): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 443 | """Circular data distribution. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 444 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 445 | mu is the mean angle, expressed in radians between 0 and 2*pi, and |
| 446 | kappa is the concentration parameter, which must be greater than or |
| 447 | equal to zero. If kappa is equal to zero, this distribution reduces |
| 448 | to a uniform random angle over the range 0 to 2*pi. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 449 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 450 | """ |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 451 | # mu: mean angle (in radians between 0 and 2*pi) |
| 452 | # kappa: concentration parameter kappa (>= 0) |
| 453 | # if kappa = 0 generate uniform random angle |
| 454 | |
| 455 | # Based upon an algorithm published in: Fisher, N.I., |
| 456 | # "Statistical Analysis of Circular Data", Cambridge |
| 457 | # University Press, 1993. |
| 458 | |
| 459 | # Thanks to Magnus Kessler for a correction to the |
| 460 | # implementation of step 4. |
| 461 | |
| 462 | random = self.random |
| 463 | if kappa <= 1e-6: |
| 464 | return TWOPI * random() |
| 465 | |
Serhiy Storchaka | 65d5639 | 2013-02-10 19:27:37 +0200 | [diff] [blame] | 466 | s = 0.5 / kappa |
| 467 | r = s + _sqrt(1.0 + s * s) |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 468 | |
Raymond Hettinger | 42406e6 | 2005-04-30 09:02:51 +0000 | [diff] [blame] | 469 | while 1: |
Tim Peters | 0c9886d | 2001-01-15 01:18:21 +0000 | [diff] [blame] | 470 | u1 = random() |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 471 | z = _cos(_pi * u1) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 472 | |
Serhiy Storchaka | 65d5639 | 2013-02-10 19:27:37 +0200 | [diff] [blame] | 473 | d = z / (r + z) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 474 | u2 = random() |
Serhiy Storchaka | 65d5639 | 2013-02-10 19:27:37 +0200 | [diff] [blame] | 475 | if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d): |
Tim Peters | 0c9886d | 2001-01-15 01:18:21 +0000 | [diff] [blame] | 476 | break |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 477 | |
Serhiy Storchaka | 65d5639 | 2013-02-10 19:27:37 +0200 | [diff] [blame] | 478 | q = 1.0 / r |
| 479 | f = (q + z) / (1.0 + q * z) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 480 | u3 = random() |
| 481 | if u3 > 0.5: |
Mark Dickinson | 9aaeb5e | 2013-02-10 14:13:40 +0000 | [diff] [blame] | 482 | theta = (mu + _acos(f)) % TWOPI |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 483 | else: |
Mark Dickinson | 9aaeb5e | 2013-02-10 14:13:40 +0000 | [diff] [blame] | 484 | theta = (mu - _acos(f)) % TWOPI |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 485 | |
| 486 | return theta |
| 487 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 488 | ## -------------------- gamma distribution -------------------- |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 489 | |
| 490 | def gammavariate(self, alpha, beta): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 491 | """Gamma distribution. Not the gamma function! |
| 492 | |
| 493 | Conditions on the parameters are alpha > 0 and beta > 0. |
| 494 | |
Raymond Hettinger | 405a471 | 2011-03-22 15:52:46 -0700 | [diff] [blame] | 495 | The probability distribution function is: |
| 496 | |
| 497 | x ** (alpha - 1) * math.exp(-x / beta) |
| 498 | pdf(x) = -------------------------------------- |
| 499 | math.gamma(alpha) * beta ** alpha |
| 500 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 501 | """ |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 502 | |
Raymond Hettinger | b760efb | 2002-05-14 06:40:34 +0000 | [diff] [blame] | 503 | # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2 |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 504 | |
Guido van Rossum | 570764d | 2002-05-14 14:08:12 +0000 | [diff] [blame] | 505 | # Warning: a few older sources define the gamma distribution in terms |
| 506 | # of alpha > -1.0 |
| 507 | if alpha <= 0.0 or beta <= 0.0: |
| 508 | raise ValueError, 'gammavariate: alpha and beta must be > 0.0' |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 509 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 510 | random = self.random |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 511 | if alpha > 1.0: |
| 512 | |
| 513 | # Uses R.C.H. Cheng, "The generation of Gamma |
| 514 | # variables with non-integral shape parameters", |
| 515 | # Applied Statistics, (1977), 26, No. 1, p71-74 |
| 516 | |
Raymond Hettinger | ca6cdc2 | 2002-05-13 23:40:14 +0000 | [diff] [blame] | 517 | ainv = _sqrt(2.0 * alpha - 1.0) |
| 518 | bbb = alpha - LOG4 |
| 519 | ccc = alpha + ainv |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 520 | |
Raymond Hettinger | 42406e6 | 2005-04-30 09:02:51 +0000 | [diff] [blame] | 521 | while 1: |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 522 | u1 = random() |
Raymond Hettinger | 73ced7e | 2003-01-04 09:26:32 +0000 | [diff] [blame] | 523 | if not 1e-7 < u1 < .9999999: |
| 524 | continue |
| 525 | u2 = 1.0 - random() |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 526 | v = _log(u1/(1.0-u1))/ainv |
| 527 | x = alpha*_exp(v) |
| 528 | z = u1*u1*u2 |
| 529 | r = bbb+ccc*v-x |
| 530 | if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z): |
Raymond Hettinger | b760efb | 2002-05-14 06:40:34 +0000 | [diff] [blame] | 531 | return x * beta |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 532 | |
| 533 | elif alpha == 1.0: |
| 534 | # expovariate(1) |
| 535 | u = random() |
| 536 | while u <= 1e-7: |
| 537 | u = random() |
Raymond Hettinger | b760efb | 2002-05-14 06:40:34 +0000 | [diff] [blame] | 538 | return -_log(u) * beta |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 539 | |
| 540 | else: # alpha is between 0 and 1 (exclusive) |
| 541 | |
| 542 | # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle |
| 543 | |
Raymond Hettinger | 42406e6 | 2005-04-30 09:02:51 +0000 | [diff] [blame] | 544 | while 1: |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 545 | u = random() |
| 546 | b = (_e + alpha)/_e |
| 547 | p = b*u |
| 548 | if p <= 1.0: |
Raymond Hettinger | 42406e6 | 2005-04-30 09:02:51 +0000 | [diff] [blame] | 549 | x = p ** (1.0/alpha) |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 550 | else: |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 551 | x = -_log((b-p)/alpha) |
| 552 | u1 = random() |
Raymond Hettinger | 42406e6 | 2005-04-30 09:02:51 +0000 | [diff] [blame] | 553 | if p > 1.0: |
| 554 | if u1 <= x ** (alpha - 1.0): |
| 555 | break |
| 556 | elif u1 <= _exp(-x): |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 557 | break |
Raymond Hettinger | b760efb | 2002-05-14 06:40:34 +0000 | [diff] [blame] | 558 | return x * beta |
| 559 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 560 | ## -------------------- Gauss (faster alternative) -------------------- |
Guido van Rossum | 95bfcda | 1994-03-09 14:21:05 +0000 | [diff] [blame] | 561 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 562 | def gauss(self, mu, sigma): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 563 | """Gaussian distribution. |
| 564 | |
| 565 | mu is the mean, and sigma is the standard deviation. This is |
| 566 | slightly faster than the normalvariate() function. |
| 567 | |
| 568 | Not thread-safe without a lock around calls. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 569 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 570 | """ |
Guido van Rossum | cc32ac9 | 1994-03-15 16:10:24 +0000 | [diff] [blame] | 571 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 572 | # When x and y are two variables from [0, 1), uniformly |
| 573 | # distributed, then |
| 574 | # |
| 575 | # cos(2*pi*x)*sqrt(-2*log(1-y)) |
| 576 | # sin(2*pi*x)*sqrt(-2*log(1-y)) |
| 577 | # |
| 578 | # are two *independent* variables with normal distribution |
| 579 | # (mu = 0, sigma = 1). |
| 580 | # (Lambert Meertens) |
| 581 | # (corrected version; bug discovered by Mike Miller, fixed by LM) |
Guido van Rossum | cc32ac9 | 1994-03-15 16:10:24 +0000 | [diff] [blame] | 582 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 583 | # Multithreading note: When two threads call this function |
| 584 | # simultaneously, it is possible that they will receive the |
| 585 | # same return value. The window is very small though. To |
| 586 | # avoid this, you have to use a lock around all calls. (I |
| 587 | # didn't want to slow this down in the serial case by using a |
| 588 | # lock here.) |
Guido van Rossum | d03e119 | 1998-05-29 17:51:31 +0000 | [diff] [blame] | 589 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 590 | random = self.random |
| 591 | z = self.gauss_next |
| 592 | self.gauss_next = None |
| 593 | if z is None: |
| 594 | x2pi = random() * TWOPI |
| 595 | g2rad = _sqrt(-2.0 * _log(1.0 - random())) |
| 596 | z = _cos(x2pi) * g2rad |
| 597 | self.gauss_next = _sin(x2pi) * g2rad |
Guido van Rossum | cc32ac9 | 1994-03-15 16:10:24 +0000 | [diff] [blame] | 598 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 599 | return mu + z*sigma |
Guido van Rossum | 95bfcda | 1994-03-09 14:21:05 +0000 | [diff] [blame] | 600 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 601 | ## -------------------- beta -------------------- |
Tim Peters | 85e2e47 | 2001-01-26 06:49:56 +0000 | [diff] [blame] | 602 | ## See |
Ezio Melotti | 1bb18cc | 2011-04-15 08:25:16 +0300 | [diff] [blame] | 603 | ## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html |
Tim Peters | 85e2e47 | 2001-01-26 06:49:56 +0000 | [diff] [blame] | 604 | ## for Ivan Frohne's insightful analysis of why the original implementation: |
| 605 | ## |
| 606 | ## def betavariate(self, alpha, beta): |
| 607 | ## # Discrete Event Simulation in C, pp 87-88. |
| 608 | ## |
| 609 | ## y = self.expovariate(alpha) |
| 610 | ## z = self.expovariate(1.0/beta) |
| 611 | ## return z/(y+z) |
| 612 | ## |
| 613 | ## was dead wrong, and how it probably got that way. |
Guido van Rossum | 95bfcda | 1994-03-09 14:21:05 +0000 | [diff] [blame] | 614 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 615 | def betavariate(self, alpha, beta): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 616 | """Beta distribution. |
| 617 | |
Raymond Hettinger | 1b0ce85 | 2007-01-19 18:07:18 +0000 | [diff] [blame] | 618 | Conditions on the parameters are alpha > 0 and beta > 0. |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 619 | Returned values range between 0 and 1. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 620 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 621 | """ |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 622 | |
Tim Peters | 85e2e47 | 2001-01-26 06:49:56 +0000 | [diff] [blame] | 623 | # This version due to Janne Sinkkonen, and matches all the std |
| 624 | # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). |
| 625 | y = self.gammavariate(alpha, 1.) |
| 626 | if y == 0: |
| 627 | return 0.0 |
| 628 | else: |
| 629 | return y / (y + self.gammavariate(beta, 1.)) |
Guido van Rossum | 95bfcda | 1994-03-09 14:21:05 +0000 | [diff] [blame] | 630 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 631 | ## -------------------- Pareto -------------------- |
Guido van Rossum | cf4559a | 1997-12-02 02:47:39 +0000 | [diff] [blame] | 632 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 633 | def paretovariate(self, alpha): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 634 | """Pareto distribution. alpha is the shape parameter.""" |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 635 | # Jain, pg. 495 |
Guido van Rossum | cf4559a | 1997-12-02 02:47:39 +0000 | [diff] [blame] | 636 | |
Raymond Hettinger | 73ced7e | 2003-01-04 09:26:32 +0000 | [diff] [blame] | 637 | u = 1.0 - self.random() |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 638 | return 1.0 / pow(u, 1.0/alpha) |
Guido van Rossum | cf4559a | 1997-12-02 02:47:39 +0000 | [diff] [blame] | 639 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 640 | ## -------------------- Weibull -------------------- |
Guido van Rossum | cf4559a | 1997-12-02 02:47:39 +0000 | [diff] [blame] | 641 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 642 | def weibullvariate(self, alpha, beta): |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 643 | """Weibull distribution. |
| 644 | |
| 645 | alpha is the scale parameter and beta is the shape parameter. |
Raymond Hettinger | ef4d4bd | 2002-05-23 23:58:17 +0000 | [diff] [blame] | 646 | |
Raymond Hettinger | c32f033 | 2002-05-23 19:44:49 +0000 | [diff] [blame] | 647 | """ |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 648 | # Jain, pg. 499; bug fix courtesy Bill Arms |
Guido van Rossum | cf4559a | 1997-12-02 02:47:39 +0000 | [diff] [blame] | 649 | |
Raymond Hettinger | 73ced7e | 2003-01-04 09:26:32 +0000 | [diff] [blame] | 650 | u = 1.0 - self.random() |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 651 | return alpha * pow(-_log(u), 1.0/beta) |
Guido van Rossum | 6c395ba | 1999-08-18 13:53:28 +0000 | [diff] [blame] | 652 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 653 | ## -------------------- Wichmann-Hill ------------------- |
| 654 | |
| 655 | class WichmannHill(Random): |
| 656 | |
| 657 | VERSION = 1 # used by getstate/setstate |
| 658 | |
| 659 | def seed(self, a=None): |
| 660 | """Initialize internal state from hashable object. |
| 661 | |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 662 | None or no argument seeds from current time or from an operating |
| 663 | system specific randomness source if available. |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 664 | |
| 665 | If a is not None or an int or long, hash(a) is used instead. |
| 666 | |
| 667 | If a is an int or long, a is used directly. Distinct values between |
| 668 | 0 and 27814431486575L inclusive are guaranteed to yield distinct |
| 669 | internal states (this guarantee is specific to the default |
| 670 | Wichmann-Hill generator). |
| 671 | """ |
| 672 | |
| 673 | if a is None: |
Raymond Hettinger | c1c43ca | 2004-09-05 00:00:42 +0000 | [diff] [blame] | 674 | try: |
| 675 | a = long(_hexlify(_urandom(16)), 16) |
| 676 | except NotImplementedError: |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 677 | import time |
| 678 | a = long(time.time() * 256) # use fractional seconds |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 679 | |
| 680 | if not isinstance(a, (int, long)): |
| 681 | a = hash(a) |
| 682 | |
| 683 | a, x = divmod(a, 30268) |
| 684 | a, y = divmod(a, 30306) |
| 685 | a, z = divmod(a, 30322) |
| 686 | self._seed = int(x)+1, int(y)+1, int(z)+1 |
| 687 | |
| 688 | self.gauss_next = None |
| 689 | |
| 690 | def random(self): |
| 691 | """Get the next random number in the range [0.0, 1.0).""" |
| 692 | |
| 693 | # Wichman-Hill random number generator. |
| 694 | # |
| 695 | # Wichmann, B. A. & Hill, I. D. (1982) |
| 696 | # Algorithm AS 183: |
| 697 | # An efficient and portable pseudo-random number generator |
| 698 | # Applied Statistics 31 (1982) 188-190 |
| 699 | # |
| 700 | # see also: |
| 701 | # Correction to Algorithm AS 183 |
| 702 | # Applied Statistics 33 (1984) 123 |
| 703 | # |
| 704 | # McLeod, A. I. (1985) |
| 705 | # A remark on Algorithm AS 183 |
| 706 | # Applied Statistics 34 (1985),198-200 |
| 707 | |
| 708 | # This part is thread-unsafe: |
| 709 | # BEGIN CRITICAL SECTION |
| 710 | x, y, z = self._seed |
| 711 | x = (171 * x) % 30269 |
| 712 | y = (172 * y) % 30307 |
| 713 | z = (170 * z) % 30323 |
| 714 | self._seed = x, y, z |
| 715 | # END CRITICAL SECTION |
| 716 | |
| 717 | # Note: on a platform using IEEE-754 double arithmetic, this can |
| 718 | # never return 0.0 (asserted by Tim; proof too long for a comment). |
| 719 | return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0 |
| 720 | |
| 721 | def getstate(self): |
| 722 | """Return internal state; can be passed to setstate() later.""" |
| 723 | return self.VERSION, self._seed, self.gauss_next |
| 724 | |
| 725 | def setstate(self, state): |
| 726 | """Restore internal state from object returned by getstate().""" |
| 727 | version = state[0] |
| 728 | if version == 1: |
| 729 | version, self._seed, self.gauss_next = state |
| 730 | else: |
| 731 | raise ValueError("state with version %s passed to " |
| 732 | "Random.setstate() of version %s" % |
| 733 | (version, self.VERSION)) |
| 734 | |
| 735 | def jumpahead(self, n): |
| 736 | """Act as if n calls to random() were made, but quickly. |
| 737 | |
| 738 | n is an int, greater than or equal to 0. |
| 739 | |
| 740 | Example use: If you have 2 threads and know that each will |
| 741 | consume no more than a million random numbers, create two Random |
| 742 | objects r1 and r2, then do |
| 743 | r2.setstate(r1.getstate()) |
| 744 | r2.jumpahead(1000000) |
| 745 | Then r1 and r2 will use guaranteed-disjoint segments of the full |
| 746 | period. |
| 747 | """ |
| 748 | |
| 749 | if not n >= 0: |
| 750 | raise ValueError("n must be >= 0") |
| 751 | x, y, z = self._seed |
| 752 | x = int(x * pow(171, n, 30269)) % 30269 |
| 753 | y = int(y * pow(172, n, 30307)) % 30307 |
| 754 | z = int(z * pow(170, n, 30323)) % 30323 |
| 755 | self._seed = x, y, z |
| 756 | |
| 757 | def __whseed(self, x=0, y=0, z=0): |
| 758 | """Set the Wichmann-Hill seed from (x, y, z). |
| 759 | |
| 760 | These must be integers in the range [0, 256). |
| 761 | """ |
| 762 | |
| 763 | if not type(x) == type(y) == type(z) == int: |
| 764 | raise TypeError('seeds must be integers') |
| 765 | if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256): |
| 766 | raise ValueError('seeds must be in range(0, 256)') |
| 767 | if 0 == x == y == z: |
| 768 | # Initialize from current time |
| 769 | import time |
| 770 | t = long(time.time() * 256) |
| 771 | t = int((t&0xffffff) ^ (t>>24)) |
| 772 | t, x = divmod(t, 256) |
| 773 | t, y = divmod(t, 256) |
| 774 | t, z = divmod(t, 256) |
| 775 | # Zero is a poor seed, so substitute 1 |
| 776 | self._seed = (x or 1, y or 1, z or 1) |
| 777 | |
| 778 | self.gauss_next = None |
| 779 | |
| 780 | def whseed(self, a=None): |
| 781 | """Seed from hashable object's hash code. |
| 782 | |
| 783 | None or no argument seeds from current time. It is not guaranteed |
| 784 | that objects with distinct hash codes lead to distinct internal |
| 785 | states. |
| 786 | |
| 787 | This is obsolete, provided for compatibility with the seed routine |
| 788 | used prior to Python 2.1. Use the .seed() method instead. |
| 789 | """ |
| 790 | |
| 791 | if a is None: |
| 792 | self.__whseed() |
| 793 | return |
| 794 | a = hash(a) |
| 795 | a, x = divmod(a, 256) |
| 796 | a, y = divmod(a, 256) |
| 797 | a, z = divmod(a, 256) |
| 798 | x = (x + a) % 256 or 1 |
| 799 | y = (y + a) % 256 or 1 |
| 800 | z = (z + a) % 256 or 1 |
| 801 | self.__whseed(x, y, z) |
| 802 | |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 803 | ## --------------- Operating System Random Source ------------------ |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 804 | |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 805 | class SystemRandom(Random): |
| 806 | """Alternate random number generator using sources provided |
| 807 | by the operating system (such as /dev/urandom on Unix or |
| 808 | CryptGenRandom on Windows). |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 809 | |
| 810 | Not available on all systems (see os.urandom() for details). |
| 811 | """ |
| 812 | |
| 813 | def random(self): |
| 814 | """Get the next random number in the range [0.0, 1.0).""" |
Tim Peters | 7c2a85b | 2004-08-31 02:19:55 +0000 | [diff] [blame] | 815 | return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 816 | |
| 817 | def getrandbits(self, k): |
| 818 | """getrandbits(k) -> x. Generates a long int with k random bits.""" |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 819 | if k <= 0: |
| 820 | raise ValueError('number of bits must be greater than zero') |
| 821 | if k != int(k): |
| 822 | raise TypeError('number of bits should be an integer') |
| 823 | bytes = (k + 7) // 8 # bits / 8 and rounded up |
| 824 | x = long(_hexlify(_urandom(bytes)), 16) |
| 825 | return x >> (bytes * 8 - k) # trim excess bits |
| 826 | |
| 827 | def _stub(self, *args, **kwds): |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 828 | "Stub method. Not used for a system random number generator." |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 829 | return None |
| 830 | seed = jumpahead = _stub |
| 831 | |
| 832 | def _notimplemented(self, *args, **kwds): |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 833 | "Method should not be called for a system random number generator." |
| 834 | raise NotImplementedError('System entropy source does not have state.') |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 835 | getstate = setstate = _notimplemented |
| 836 | |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 837 | ## -------------------- test program -------------------- |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 838 | |
Raymond Hettinger | 6229713 | 2003-08-30 01:24:19 +0000 | [diff] [blame] | 839 | def _test_generator(n, func, args): |
Tim Peters | 0c9886d | 2001-01-15 01:18:21 +0000 | [diff] [blame] | 840 | import time |
Raymond Hettinger | 6229713 | 2003-08-30 01:24:19 +0000 | [diff] [blame] | 841 | print n, 'times', func.__name__ |
Raymond Hettinger | b98154e | 2003-05-24 17:26:02 +0000 | [diff] [blame] | 842 | total = 0.0 |
Tim Peters | 0c9886d | 2001-01-15 01:18:21 +0000 | [diff] [blame] | 843 | sqsum = 0.0 |
| 844 | smallest = 1e10 |
| 845 | largest = -1e10 |
| 846 | t0 = time.time() |
| 847 | for i in range(n): |
Raymond Hettinger | 6229713 | 2003-08-30 01:24:19 +0000 | [diff] [blame] | 848 | x = func(*args) |
Raymond Hettinger | b98154e | 2003-05-24 17:26:02 +0000 | [diff] [blame] | 849 | total += x |
Tim Peters | 0c9886d | 2001-01-15 01:18:21 +0000 | [diff] [blame] | 850 | sqsum = sqsum + x*x |
| 851 | smallest = min(x, smallest) |
| 852 | largest = max(x, largest) |
| 853 | t1 = time.time() |
| 854 | print round(t1-t0, 3), 'sec,', |
Raymond Hettinger | b98154e | 2003-05-24 17:26:02 +0000 | [diff] [blame] | 855 | avg = total/n |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 856 | stddev = _sqrt(sqsum/n - avg*avg) |
Tim Peters | 0c9886d | 2001-01-15 01:18:21 +0000 | [diff] [blame] | 857 | print 'avg %g, stddev %g, min %g, max %g' % \ |
| 858 | (avg, stddev, smallest, largest) |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 859 | |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 860 | |
| 861 | def _test(N=2000): |
Raymond Hettinger | 6229713 | 2003-08-30 01:24:19 +0000 | [diff] [blame] | 862 | _test_generator(N, random, ()) |
| 863 | _test_generator(N, normalvariate, (0.0, 1.0)) |
| 864 | _test_generator(N, lognormvariate, (0.0, 1.0)) |
| 865 | _test_generator(N, vonmisesvariate, (0.0, 1.0)) |
| 866 | _test_generator(N, gammavariate, (0.01, 1.0)) |
| 867 | _test_generator(N, gammavariate, (0.1, 1.0)) |
| 868 | _test_generator(N, gammavariate, (0.1, 2.0)) |
| 869 | _test_generator(N, gammavariate, (0.5, 1.0)) |
| 870 | _test_generator(N, gammavariate, (0.9, 1.0)) |
| 871 | _test_generator(N, gammavariate, (1.0, 1.0)) |
| 872 | _test_generator(N, gammavariate, (2.0, 1.0)) |
| 873 | _test_generator(N, gammavariate, (20.0, 1.0)) |
| 874 | _test_generator(N, gammavariate, (200.0, 1.0)) |
| 875 | _test_generator(N, gauss, (0.0, 1.0)) |
| 876 | _test_generator(N, betavariate, (3.0, 3.0)) |
Raymond Hettinger | bbc50ea | 2008-03-23 13:32:32 +0000 | [diff] [blame] | 877 | _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0)) |
Tim Peters | cd80410 | 2001-01-25 20:25:57 +0000 | [diff] [blame] | 878 | |
Tim Peters | 715c4c4 | 2001-01-26 22:56:56 +0000 | [diff] [blame] | 879 | # Create one instance, seeded from current time, and export its methods |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 880 | # as module-level functions. The functions share state across all uses |
| 881 | #(both in the user's code and in the Python libraries), but that's fine |
| 882 | # for most programs and is easier for the casual user than making them |
| 883 | # instantiate their own Random() instance. |
| 884 | |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 885 | _inst = Random() |
| 886 | seed = _inst.seed |
| 887 | random = _inst.random |
| 888 | uniform = _inst.uniform |
Raymond Hettinger | bbc50ea | 2008-03-23 13:32:32 +0000 | [diff] [blame] | 889 | triangular = _inst.triangular |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 890 | randint = _inst.randint |
| 891 | choice = _inst.choice |
| 892 | randrange = _inst.randrange |
Raymond Hettinger | f24eb35 | 2002-11-12 17:41:57 +0000 | [diff] [blame] | 893 | sample = _inst.sample |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 894 | shuffle = _inst.shuffle |
| 895 | normalvariate = _inst.normalvariate |
| 896 | lognormvariate = _inst.lognormvariate |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 897 | expovariate = _inst.expovariate |
| 898 | vonmisesvariate = _inst.vonmisesvariate |
| 899 | gammavariate = _inst.gammavariate |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 900 | gauss = _inst.gauss |
| 901 | betavariate = _inst.betavariate |
| 902 | paretovariate = _inst.paretovariate |
| 903 | weibullvariate = _inst.weibullvariate |
| 904 | getstate = _inst.getstate |
| 905 | setstate = _inst.setstate |
Tim Peters | d52269b | 2001-01-25 06:23:18 +0000 | [diff] [blame] | 906 | jumpahead = _inst.jumpahead |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 907 | getrandbits = _inst.getrandbits |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 908 | |
Guido van Rossum | ff03b1a | 1994-03-09 12:55:02 +0000 | [diff] [blame] | 909 | if __name__ == '__main__': |
Tim Peters | d7b5e88 | 2001-01-25 03:36:26 +0000 | [diff] [blame] | 910 | _test() |