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