]> git.saurik.com Git - apple/libc.git/blob - stdlib/random.c
83c3926dc19519d17fdcd09ce51d39fd6b08829a
[apple/libc.git] / stdlib / random.c
1 /*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
7 *
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * file.
14 *
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
22 *
23 * @APPLE_LICENSE_HEADER_END@
24 */
25 /*
26 * Copyright (c) 1983, 1993
27 * The Regents of the University of California. All rights reserved.
28 *
29 * Redistribution and use in source and binary forms, with or without
30 * modification, are permitted provided that the following conditions
31 * are met:
32 * 1. Redistributions of source code must retain the above copyright
33 * notice, this list of conditions and the following disclaimer.
34 * 2. Redistributions in binary form must reproduce the above copyright
35 * notice, this list of conditions and the following disclaimer in the
36 * documentation and/or other materials provided with the distribution.
37 * 3. All advertising materials mentioning features or use of this software
38 * must display the following acknowledgement:
39 * This product includes software developed by the University of
40 * California, Berkeley and its contributors.
41 * 4. Neither the name of the University nor the names of its contributors
42 * may be used to endorse or promote products derived from this software
43 * without specific prior written permission.
44 *
45 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * SUCH DAMAGE.
56 */
57
58
59 #include <stdio.h>
60 #include <stdlib.h>
61
62 /*
63 * random.c:
64 *
65 * An improved random number generation package. In addition to the standard
66 * rand()/srand() like interface, this package also has a special state info
67 * interface. The initstate() routine is called with a seed, an array of
68 * bytes, and a count of how many bytes are being passed in; this array is
69 * then initialized to contain information for random number generation with
70 * that much state information. Good sizes for the amount of state
71 * information are 32, 64, 128, and 256 bytes. The state can be switched by
72 * calling the setstate() routine with the same array as was initiallized
73 * with initstate(). By default, the package runs with 128 bytes of state
74 * information and generates far better random numbers than a linear
75 * congruential generator. If the amount of state information is less than
76 * 32 bytes, a simple linear congruential R.N.G. is used.
77 *
78 * Internally, the state information is treated as an array of longs; the
79 * zeroeth element of the array is the type of R.N.G. being used (small
80 * integer); the remainder of the array is the state information for the
81 * R.N.G. Thus, 32 bytes of state information will give 7 longs worth of
82 * state information, which will allow a degree seven polynomial. (Note:
83 * the zeroeth word of state information also has some other information
84 * stored in it -- see setstate() for details).
85 *
86 * The random number generation technique is a linear feedback shift register
87 * approach, employing trinomials (since there are fewer terms to sum up that
88 * way). In this approach, the least significant bit of all the numbers in
89 * the state table will act as a linear feedback shift register, and will
90 * have period 2^deg - 1 (where deg is the degree of the polynomial being
91 * used, assuming that the polynomial is irreducible and primitive). The
92 * higher order bits will have longer periods, since their values are also
93 * influenced by pseudo-random carries out of the lower bits. The total
94 * period of the generator is approximately deg*(2**deg - 1); thus doubling
95 * the amount of state information has a vast influence on the period of the
96 * generator. Note: the deg*(2**deg - 1) is an approximation only good for
97 * large deg, when the period of the shift register is the dominant factor.
98 * With deg equal to seven, the period is actually much longer than the
99 * 7*(2**7 - 1) predicted by this formula.
100 */
101
102 /*
103 * For each of the currently supported random number generators, we have a
104 * break value on the amount of state information (you need at least this
105 * many bytes of state info to support this random number generator), a degree
106 * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
107 * the separation between the two lower order coefficients of the trinomial.
108 */
109 #define TYPE_0 0 /* linear congruential */
110 #define BREAK_0 8
111 #define DEG_0 0
112 #define SEP_0 0
113
114 #define TYPE_1 1 /* x**7 + x**3 + 1 */
115 #define BREAK_1 32
116 #define DEG_1 7
117 #define SEP_1 3
118
119 #define TYPE_2 2 /* x**15 + x + 1 */
120 #define BREAK_2 64
121 #define DEG_2 15
122 #define SEP_2 1
123
124 #define TYPE_3 3 /* x**31 + x**3 + 1 */
125 #define BREAK_3 128
126 #define DEG_3 31
127 #define SEP_3 3
128
129 #define TYPE_4 4 /* x**63 + x + 1 */
130 #define BREAK_4 256
131 #define DEG_4 63
132 #define SEP_4 1
133
134 /*
135 * Array versions of the above information to make code run faster --
136 * relies on fact that TYPE_i == i.
137 */
138 #define MAX_TYPES 5 /* max number of types above */
139
140 static long degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
141 static long seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
142
143 /*
144 * Initially, everything is set up as if from:
145 *
146 * initstate(1, &randtbl, 128);
147 *
148 * Note that this initialization takes advantage of the fact that srandom()
149 * advances the front and rear pointers 10*rand_deg times, and hence the
150 * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
151 * element of the state information, which contains info about the current
152 * position of the rear pointer is just
153 *
154 * MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
155 */
156
157 static long randtbl[DEG_3 + 1] = {
158 TYPE_3,
159 0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
160 0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd,
161 0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88,
162 0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc,
163 0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
164 0x27fb47b9,
165 };
166
167 /*
168 * fptr and rptr are two pointers into the state info, a front and a rear
169 * pointer. These two pointers are always rand_sep places aparts, as they
170 * cycle cyclically through the state information. (Yes, this does mean we
171 * could get away with just one pointer, but the code for random() is more
172 * efficient this way). The pointers are left positioned as they would be
173 * from the call
174 *
175 * initstate(1, randtbl, 128);
176 *
177 * (The position of the rear pointer, rptr, is really 0 (as explained above
178 * in the initialization of randtbl) because the state table pointer is set
179 * to point to randtbl[1] (as explained below).
180 */
181 static long *fptr = &randtbl[SEP_3 + 1];
182 static long *rptr = &randtbl[1];
183
184 /*
185 * The following things are the pointer to the state information table, the
186 * type of the current generator, the degree of the current polynomial being
187 * used, and the separation between the two pointers. Note that for efficiency
188 * of random(), we remember the first location of the state information, not
189 * the zeroeth. Hence it is valid to access state[-1], which is used to
190 * store the type of the R.N.G. Also, we remember the last location, since
191 * this is more efficient than indexing every time to find the address of
192 * the last element to see if the front and rear pointers have wrapped.
193 */
194 static long *state = &randtbl[1];
195 static long rand_type = TYPE_3;
196 static long rand_deg = DEG_3;
197 static long rand_sep = SEP_3;
198 static long *end_ptr = &randtbl[DEG_3 + 1];
199
200 /*
201 * srandom:
202 *
203 * Initialize the random number generator based on the given seed. If the
204 * type is the trivial no-state-information type, just remember the seed.
205 * Otherwise, initializes state[] based on the given "seed" via a linear
206 * congruential generator. Then, the pointers are set to known locations
207 * that are exactly rand_sep places apart. Lastly, it cycles the state
208 * information a given number of times to get rid of any initial dependencies
209 * introduced by the L.C.R.N.G. Note that the initialization of randtbl[]
210 * for default usage relies on values produced by this routine.
211 */
212 void
213 srandom(x)
214 unsigned long x;
215 {
216 register long i;
217
218 if (rand_type == TYPE_0)
219 state[0] = x;
220 else {
221 state[0] = x;
222 for (i = 1; i < rand_deg; i++)
223 state[i] = 1103515245 * state[i - 1] + 12345;
224 fptr = &state[rand_sep];
225 rptr = &state[0];
226 for (i = 0; i < 10 * rand_deg; i++)
227 (void)random();
228 }
229 }
230
231 /*
232 * initstate:
233 *
234 * Initialize the state information in the given array of n bytes for future
235 * random number generation. Based on the number of bytes we are given, and
236 * the break values for the different R.N.G.'s, we choose the best (largest)
237 * one we can and set things up for it. srandom() is then called to
238 * initialize the state information.
239 *
240 * Note that on return from srandom(), we set state[-1] to be the type
241 * multiplexed with the current value of the rear pointer; this is so
242 * successive calls to initstate() won't lose this information and will be
243 * able to restart with setstate().
244 *
245 * Note: the first thing we do is save the current state, if any, just like
246 * setstate() so that it doesn't matter when initstate is called.
247 *
248 * Returns a pointer to the old state.
249 *
250 * Note: The Sparc platform requires that arg_state begin on a long
251 * word boundary; otherwise a bus error will occur. Even so, lint will
252 * complain about mis-alignment, but you should disregard these messages.
253 */
254 char *
255 initstate(seed, arg_state, n)
256 unsigned long seed; /* seed for R.N.G. */
257 char *arg_state; /* pointer to state array */
258 long n; /* # bytes of state info */
259 {
260 register char *ostate = (char *)(&state[-1]);
261 register long *long_arg_state = (long *) arg_state;
262
263 if (rand_type == TYPE_0)
264 state[-1] = rand_type;
265 else
266 state[-1] = MAX_TYPES * (rptr - state) + rand_type;
267 if (n < BREAK_0) {
268 (void)fprintf(stderr,
269 "random: not enough state (%ld bytes); ignored.\n", n);
270 return(0);
271 }
272 if (n < BREAK_1) {
273 rand_type = TYPE_0;
274 rand_deg = DEG_0;
275 rand_sep = SEP_0;
276 } else if (n < BREAK_2) {
277 rand_type = TYPE_1;
278 rand_deg = DEG_1;
279 rand_sep = SEP_1;
280 } else if (n < BREAK_3) {
281 rand_type = TYPE_2;
282 rand_deg = DEG_2;
283 rand_sep = SEP_2;
284 } else if (n < BREAK_4) {
285 rand_type = TYPE_3;
286 rand_deg = DEG_3;
287 rand_sep = SEP_3;
288 } else {
289 rand_type = TYPE_4;
290 rand_deg = DEG_4;
291 rand_sep = SEP_4;
292 }
293 state = (long *) (long_arg_state + 1); /* first location */
294 end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */
295 srandom(seed);
296 if (rand_type == TYPE_0)
297 long_arg_state[0] = rand_type;
298 else
299 long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type;
300 return(ostate);
301 }
302
303 /*
304 * setstate:
305 *
306 * Restore the state from the given state array.
307 *
308 * Note: it is important that we also remember the locations of the pointers
309 * in the current state information, and restore the locations of the pointers
310 * from the old state information. This is done by multiplexing the pointer
311 * location into the zeroeth word of the state information.
312 *
313 * Note that due to the order in which things are done, it is OK to call
314 * setstate() with the same state as the current state.
315 *
316 * Returns a pointer to the old state information.
317 *
318 * Note: The Sparc platform requires that arg_state begin on a long
319 * word boundary; otherwise a bus error will occur. Even so, lint will
320 * complain about mis-alignment, but you should disregard these messages.
321 */
322 char *
323 setstate(arg_state)
324 char *arg_state; /* pointer to state array */
325 {
326 register long *new_state = (long *) arg_state;
327 register long type = new_state[0] % MAX_TYPES;
328 register long rear = new_state[0] / MAX_TYPES;
329 char *ostate = (char *)(&state[-1]);
330
331 if (rand_type == TYPE_0)
332 state[-1] = rand_type;
333 else
334 state[-1] = MAX_TYPES * (rptr - state) + rand_type;
335 switch(type) {
336 case TYPE_0:
337 case TYPE_1:
338 case TYPE_2:
339 case TYPE_3:
340 case TYPE_4:
341 rand_type = type;
342 rand_deg = degrees[type];
343 rand_sep = seps[type];
344 break;
345 default:
346 (void)fprintf(stderr,
347 "random: state info corrupted; not changed.\n");
348 }
349 state = (long *) (new_state + 1);
350 if (rand_type != TYPE_0) {
351 rptr = &state[rear];
352 fptr = &state[(rear + rand_sep) % rand_deg];
353 }
354 end_ptr = &state[rand_deg]; /* set end_ptr too */
355 return(ostate);
356 }
357
358 /*
359 * random:
360 *
361 * If we are using the trivial TYPE_0 R.N.G., just do the old linear
362 * congruential bit. Otherwise, we do our fancy trinomial stuff, which is
363 * the same in all the other cases due to all the global variables that have
364 * been set up. The basic operation is to add the number at the rear pointer
365 * into the one at the front pointer. Then both pointers are advanced to
366 * the next location cyclically in the table. The value returned is the sum
367 * generated, reduced to 31 bits by throwing away the "least random" low bit.
368 *
369 * Note: the code takes advantage of the fact that both the front and
370 * rear pointers can't wrap on the same call by not testing the rear
371 * pointer if the front one has wrapped.
372 *
373 * Returns a 31-bit random number.
374 */
375 long
376 random()
377 {
378 register long i;
379 register long *f, *r;
380
381 if (rand_type == TYPE_0) {
382 i = state[0];
383 state[0] = i = (i * 1103515245 + 12345) & 0x7fffffff;
384 } else {
385 /*
386 * Use local variables rather than static variables for speed.
387 */
388 f = fptr; r = rptr;
389 *f += *r;
390 i = (*f >> 1) & 0x7fffffff; /* chucking least random bit */
391 if (++f >= end_ptr) {
392 f = state;
393 ++r;
394 }
395 else if (++r >= end_ptr) {
396 r = state;
397 }
398
399 fptr = f; rptr = r;
400 }
401 return(i);
402 }