Line | |
---|
1 | /*** This is a portable random number generator whose origins are |
---|
2 | *** unknown. As far as can be told, this is public domain software. |
---|
3 | |
---|
4 | |
---|
5 | /*** portable random number generator */ |
---|
6 | |
---|
7 | /*** Note that every variable used here must have at least 31 bits |
---|
8 | *** of precision, exclusive of sign. Long integers should be enough. |
---|
9 | *** The generator is the congruential: i = 7**5 * i mod (2^31-1). |
---|
10 | ***/ |
---|
11 | |
---|
12 | #define MULTIPLIER 16807 |
---|
13 | #define MODULUS 2147483647 |
---|
14 | |
---|
15 | static long saved_seed; |
---|
16 | |
---|
17 | |
---|
18 | /*** set_random - initialize constants and seed */ |
---|
19 | |
---|
20 | void set_random(seed) |
---|
21 | long seed; |
---|
22 | { |
---|
23 | saved_seed = seed; |
---|
24 | } |
---|
25 | |
---|
26 | |
---|
27 | /*** ng_random - generate a random integer in the interval [a,b] (b >= a >= 0) */ |
---|
28 | |
---|
29 | long ng_random(a, b) |
---|
30 | long a, b; |
---|
31 | { |
---|
32 | register long hi, lo; |
---|
33 | |
---|
34 | hi = MULTIPLIER * (saved_seed >> 16); |
---|
35 | lo = MULTIPLIER * (saved_seed & 0xffff); |
---|
36 | hi += (lo>>16); |
---|
37 | lo &= 0xffff; |
---|
38 | lo += (hi>>15); |
---|
39 | hi &= 0x7fff; |
---|
40 | lo -= MODULUS; |
---|
41 | if ((saved_seed = (hi<<16) + lo) < 0) |
---|
42 | saved_seed += MODULUS; |
---|
43 | |
---|
44 | if (b <= a) |
---|
45 | return b; |
---|
46 | return a + saved_seed % (b - a + 1); |
---|
47 | } |
---|
Note: See
TracBrowser
for help on using the repository browser.