Fri Jan 26 12:20:45 1996 Roland McGrath <roland@churchy.gnu.ai.mit.edu>
[glibc.git] / stdlib / random.c
blobc3f8eaa0a3f5da972eba9f857e6d8e9db48606c9
1 /*
2 * Copyright (c) 1983 Regents of the University of California.
3 * All rights reserved.
5 * Redistribution and use in source and binary forms are permitted
6 * provided that the above copyright notice and this paragraph are
7 * duplicated in all such forms and that any documentation,
8 * advertising materials, and other materials related to such
9 * distribution and use acknowledge that the software was developed
10 * by the University of California, Berkeley. The name of the
11 * University may not be used to endorse or promote products derived
12 * from this software without specific prior written permission.
13 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19 * This is derived from the Berkeley source:
20 * @(#)random.c 5.5 (Berkeley) 7/6/88
21 * It was reworked for the GNU C Library by Roland McGrath.
22 * Rewritten to use reentrent functions by Ulrich Drepper, 1995.
25 #include <limits.h>
26 #include <stddef.h>
27 #include <stdlib.h>
30 /* An improved random number generation package. In addition to the standard
31 rand()/srand() like interface, this package also has a special state info
32 interface. The initstate() routine is called with a seed, an array of
33 bytes, and a count of how many bytes are being passed in; this array is
34 then initialized to contain information for random number generation with
35 that much state information. Good sizes for the amount of state
36 information are 32, 64, 128, and 256 bytes. The state can be switched by
37 calling the setstate() function with the same array as was initiallized
38 with initstate(). By default, the package runs with 128 bytes of state
39 information and generates far better random numbers than a linear
40 congruential generator. If the amount of state information is less than
41 32 bytes, a simple linear congruential R.N.G. is used. Internally, the
42 state information is treated as an array of longs; the zeroeth element of
43 the array is the type of R.N.G. being used (small integer); the remainder
44 of the array is the state information for the R.N.G. Thus, 32 bytes of
45 state information will give 7 longs worth of state information, which will
46 allow a degree seven polynomial. (Note: The zeroeth word of state
47 information also has some other information stored in it; see setstate
48 for details). The random number generation technique is a linear feedback
49 shift register approach, employing trinomials (since there are fewer terms
50 to sum up that way). In this approach, the least significant bit of all
51 the numbers in the state table will act as a linear feedback shift register,
52 and will have period 2^deg - 1 (where deg is the degree of the polynomial
53 being used, assuming that the polynomial is irreducible and primitive).
54 The higher order bits will have longer periods, since their values are
55 also influenced by pseudo-random carries out of the lower bits. The
56 total period of the generator is approximately deg*(2**deg - 1); thus
57 doubling the amount of state information has a vast influence on the
58 period of the generator. Note: The deg*(2**deg - 1) is an approximation
59 only good for large deg, when the period of the shift register is the
60 dominant factor. With deg equal to seven, the period is actually much
61 longer than the 7*(2**7 - 1) predicted by this formula. */
65 /* For each of the currently supported random number generators, we have a
66 break value on the amount of state information (you need at least thi
67 bytes of state info to support this random number generator), a degree for
68 the polynomial (actually a trinomial) that the R.N.G. is based on, and
69 separation between the two lower order coefficients of the trinomial. */
71 /* Linear congruential. */
72 #define TYPE_0 0
73 #define BREAK_0 8
74 #define DEG_0 0
75 #define SEP_0 0
77 /* x**7 + x**3 + 1. */
78 #define TYPE_1 1
79 #define BREAK_1 32
80 #define DEG_1 7
81 #define SEP_1 3
83 /* x**15 + x + 1. */
84 #define TYPE_2 2
85 #define BREAK_2 64
86 #define DEG_2 15
87 #define SEP_2 1
89 /* x**31 + x**3 + 1. */
90 #define TYPE_3 3
91 #define BREAK_3 128
92 #define DEG_3 31
93 #define SEP_3 3
95 /* x**63 + x + 1. */
96 #define TYPE_4 4
97 #define BREAK_4 256
98 #define DEG_4 63
99 #define SEP_4 1
102 /* Array versions of the above information to make code run faster.
103 Relies on fact that TYPE_i == i. */
105 #define MAX_TYPES 5 /* Max number of types above. */
108 /* Initially, everything is set up as if from:
109 initstate(1, randtbl, 128);
110 Note that this initialization takes advantage of the fact that srandom
111 advances the front and rear pointers 10*rand_deg times, and hence the
112 rear pointer which starts at 0 will also end up at zero; thus the zeroeth
113 element of the state information, which contains info about the current
114 position of the rear pointer is just
115 (MAX_TYPES * (rptr - state)) + TYPE_3 == TYPE_3. */
117 static long int randtbl[DEG_3 + 1] =
119 TYPE_3,
121 -1726662223, 379960547, 1735697613, 1040273694, 1313901226,
122 1627687941, -179304937, -2073333483, 1780058412, -1989503057,
123 -615974602, 344556628, 939512070, -1249116260, 1507946756,
124 -812545463, 154635395, 1388815473, -1926676823, 525320961,
125 -1009028674, 968117788, -123449607, 1284210865, 435012392,
126 -2017506339, -911064859, -370259173, 1132637927, 1398500161,
127 -205601318,
131 static struct random_data unsafe_state =
133 /* FPTR and RPTR are two pointers into the state info, a front and a rear
134 pointer. These two pointers are always rand_sep places aparts, as they
135 cycle through the state information. (Yes, this does mean we could get
136 away with just one pointer, but the code for random is more efficient
137 this way). The pointers are left positioned as they would be from the call:
138 initstate(1, randtbl, 128);
139 (The position of the rear pointer, rptr, is really 0 (as explained above
140 in the initialization of randtbl) because the state table pointer is set
141 to point to randtbl[1] (as explained below).) */
143 fptr : &randtbl[SEP_3 + 1],
144 rptr : &randtbl[1],
146 /* The following things are the pointer to the state information table,
147 the type of the current generator, the degree of the current polynomial
148 being used, and the separation between the two pointers.
149 Note that for efficiency of random, we remember the first location of
150 the state information, not the zeroeth. Hence it is valid to access
151 state[-1], which is used to store the type of the R.N.G.
152 Also, we remember the last location, since this is more efficient than
153 indexing every time to find the address of the last element to see if
154 the front and rear pointers have wrapped. */
156 state : &randtbl[1],
158 rand_type : TYPE_3,
159 rand_deg : DEG_3,
160 rand_sep : SEP_3,
162 end_ptr : &randtbl[sizeof (randtbl) / sizeof (randtbl[0])]
165 /* Initialize the random number generator based on the given seed. If the
166 type is the trivial no-state-information type, just remember the seed.
167 Otherwise, initializes state[] based on the given "seed" via a linear
168 congruential generator. Then, the pointers are set to known locations
169 that are exactly rand_sep places apart. Lastly, it cycles the state
170 information a given number of times to get rid of any initial dependencies
171 introduced by the L.C.R.N.G. Note that the initialization of randtbl[]
172 for default usage relies on values produced by this routine. */
173 void
174 __srandom (x)
175 unsigned int x;
177 (void) __srandom_r (x, &unsafe_state);
180 weak_alias (__srandom, srandom)
181 weak_alias (__srandom, srand)
183 /* Initialize the state information in the given array of N bytes for
184 future random number generation. Based on the number of bytes we
185 are given, and the break values for the different R.N.G.'s, we choose
186 the best (largest) one we can and set things up for it. srandom is
187 then called to initialize the state information. Note that on return
188 from srandom, we set state[-1] to be the type multiplexed with the current
189 value of the rear pointer; this is so successive calls to initstate won't
190 lose this information and will be able to restart with setstate.
191 Note: The first thing we do is save the current state, if any, just like
192 setstate so that it doesn't matter when initstate is called.
193 Returns a pointer to the old state. */
194 void *
195 __initstate (seed, arg_state, n)
196 unsigned int seed;
197 void *arg_state;
198 size_t n;
200 void *ostate = (void *) &unsafe_state.state[-1];
202 __initstate_r (seed, arg_state, n, &unsafe_state);
204 return ostate;
207 weak_alias (__initstate, initstate)
209 /* Restore the state from the given state array.
210 Note: It is important that we also remember the locations of the pointers
211 in the current state information, and restore the locations of the pointers
212 from the old state information. This is done by multiplexing the pointer
213 location into the zeroeth word of the state information. Note that due
214 to the order in which things are done, it is OK to call setstate with the
215 same state as the current state
216 Returns a pointer to the old state information. */
217 void *
218 __setstate (arg_state)
219 void *arg_state;
221 void *ostate = (void *) &unsafe_state.state[-1];
223 if (__setstate_r (arg_state, &unsafe_state) < 0)
224 return NULL;
226 return ostate;
229 weak_alias (__setstate, setstate)
231 /* If we are using the trivial TYPE_0 R.N.G., just do the old linear
232 congruential bit. Otherwise, we do our fancy trinomial stuff, which is the
233 same in all ther other cases due to all the global variables that have been
234 set up. The basic operation is to add the number at the rear pointer into
235 the one at the front pointer. Then both pointers are advanced to the next
236 location cyclically in the table. The value returned is the sum generated,
237 reduced to 31 bits by throwing away the "least random" low bit.
238 Note: The code takes advantage of the fact that both the front and
239 rear pointers can't wrap on the same call by not testing the rear
240 pointer if the front one has wrapped. Returns a 31-bit random number. */
242 long int
243 __random ()
245 long int retval;
247 (void) __random_r (&unsafe_state, &retval);
249 return retval;
252 weak_alias (__random, random)