Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 1 | # WICHMANN-HILL RANDOM NUMBER GENERATOR |
| 2 | # |
| 3 | # Wichmann, B. A. & Hill, I. D. (1982) |
| 4 | # Algorithm AS 183: |
| 5 | # An efficient and portable pseudo-random number generator |
| 6 | # Applied Statistics 31 (1982) 188-190 |
| 7 | # |
| 8 | # see also: |
| 9 | # Correction to Algorithm AS 183 |
| 10 | # Applied Statistics 33 (1984) 123 |
| 11 | # |
| 12 | # McLeod, A. I. (1985) |
| 13 | # A remark on Algorithm AS 183 |
| 14 | # Applied Statistics 34 (1985),198-200 |
| 15 | # |
| 16 | # |
| 17 | # USE: |
| 18 | # whrandom.random() yields double precision random numbers |
| 19 | # uniformly distributed between 0 and 1. |
| 20 | # |
| 21 | # whrandom.seed() must be called before whrandom.random() |
| 22 | # to seed the generator |
| 23 | |
| 24 | |
| 25 | # Translated by Guido van Rossum from C source provided by |
| 26 | # Adrian Baddeley. |
| 27 | |
| 28 | |
| 29 | # The seed |
| 30 | # |
| 31 | _seed = [0, 0, 0] |
| 32 | |
| 33 | |
| 34 | # Set the seed |
| 35 | # |
| 36 | def seed(x, y, z): |
| 37 | _seed[:] = [x, y, z] |
| 38 | |
| 39 | |
| 40 | # Return the next random number in the range [0.0 .. 1.0) |
| 41 | # |
| 42 | def random(): |
| 43 | from math import floor # floor() function |
| 44 | # |
| 45 | [x, y, z] = _seed |
| 46 | x = 171 * (x % 177) - 2 * (x/177) |
| 47 | y = 172 * (y % 176) - 35 * (y/176) |
| 48 | z = 170 * (z % 178) - 63 * (z/178) |
| 49 | # |
| 50 | if x < 0: x = x + 30269 |
| 51 | if y < 0: y = y + 30307 |
| 52 | if z < 0: z = z + 30323 |
| 53 | # |
| 54 | _seed[:] = [x, y, z] |
| 55 | # |
| 56 | term = float(x)/30269.0 + float(y)/30307.0 + float(z)/30323.0 |
| 57 | rand = term - floor(term) |
| 58 | # |
| 59 | if rand >= 1.0: rand = 0.0 # floor() inaccuracy? |
| 60 | # |
| 61 | return rand |
| 62 | |
| 63 | |
| 64 | # Initialize from the current time |
| 65 | # |
| 66 | def init(): |
| 67 | import time |
| 68 | t = time.time() |
| 69 | seed(t%256, t/256%256, t/65536%256) |
| 70 | |
| 71 | |
| 72 | # Make sure the generator is preset to a nonzero value |
| 73 | # |
| 74 | init() |