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