xref: /csrg-svn/lib/libc/stdlib/random.c (revision 46575)
121354Sdist /*
221354Sdist  * Copyright (c) 1983 Regents of the University of California.
334955Sbostic  * All rights reserved.
434955Sbostic  *
542625Sbostic  * %sccs.include.redist.c%
621354Sdist  */
721354Sdist 
826578Sdonn #if defined(LIBC_SCCS) && !defined(lint)
9*46575Sbostic static char sccsid[] = "@(#)random.c	5.9 (Berkeley) 02/23/91";
1034955Sbostic #endif /* LIBC_SCCS and not lint */
119316Smckusick 
1234955Sbostic #include <stdio.h>
1346573Sdonn #include <stdlib.h>
149316Smckusick 
159316Smckusick /*
169316Smckusick  * random.c:
17*46575Sbostic  *
189316Smckusick  * An improved random number generation package.  In addition to the standard
199316Smckusick  * rand()/srand() like interface, this package also has a special state info
209316Smckusick  * interface.  The initstate() routine is called with a seed, an array of
21*46575Sbostic  * bytes, and a count of how many bytes are being passed in; this array is
22*46575Sbostic  * then initialized to contain information for random number generation with
23*46575Sbostic  * that much state information.  Good sizes for the amount of state
24*46575Sbostic  * information are 32, 64, 128, and 256 bytes.  The state can be switched by
25*46575Sbostic  * calling the setstate() routine with the same array as was initiallized
26*46575Sbostic  * with initstate().  By default, the package runs with 128 bytes of state
27*46575Sbostic  * information and generates far better random numbers than a linear
28*46575Sbostic  * congruential generator.  If the amount of state information is less than
29*46575Sbostic  * 32 bytes, a simple linear congruential R.N.G. is used.
30*46575Sbostic  *
319316Smckusick  * Internally, the state information is treated as an array of longs; the
329316Smckusick  * zeroeth element of the array is the type of R.N.G. being used (small
339316Smckusick  * integer); the remainder of the array is the state information for the
349316Smckusick  * R.N.G.  Thus, 32 bytes of state information will give 7 longs worth of
35*46575Sbostic  * state information, which will allow a degree seven polynomial.  (Note:
36*46575Sbostic  * the zeroeth word of state information also has some other information
37*46575Sbostic  * stored in it -- see setstate() for details).
38*46575Sbostic  *
399316Smckusick  * The random number generation technique is a linear feedback shift register
409316Smckusick  * approach, employing trinomials (since there are fewer terms to sum up that
419316Smckusick  * way).  In this approach, the least significant bit of all the numbers in
42*46575Sbostic  * the state table will act as a linear feedback shift register, and will
43*46575Sbostic  * have period 2^deg - 1 (where deg is the degree of the polynomial being
44*46575Sbostic  * used, assuming that the polynomial is irreducible and primitive).  The
45*46575Sbostic  * higher order bits will have longer periods, since their values are also
46*46575Sbostic  * influenced by pseudo-random carries out of the lower bits.  The total
47*46575Sbostic  * period of the generator is approximately deg*(2**deg - 1); thus doubling
48*46575Sbostic  * the amount of state information has a vast influence on the period of the
49*46575Sbostic  * generator.  Note: the deg*(2**deg - 1) is an approximation only good for
50*46575Sbostic  * large deg, when the period of the shift register is the dominant factor.
51*46575Sbostic  * With deg equal to seven, the period is actually much longer than the
52*46575Sbostic  * 7*(2**7 - 1) predicted by this formula.
539316Smckusick  */
549316Smckusick 
559316Smckusick /*
569316Smckusick  * For each of the currently supported random number generators, we have a
579316Smckusick  * break value on the amount of state information (you need at least this
589316Smckusick  * many bytes of state info to support this random number generator), a degree
599316Smckusick  * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
609316Smckusick  * the separation between the two lower order coefficients of the trinomial.
619316Smckusick  */
62*46575Sbostic #define	TYPE_0		0		/* linear congruential */
63*46575Sbostic #define	BREAK_0		8
64*46575Sbostic #define	DEG_0		0
65*46575Sbostic #define	SEP_0		0
669316Smckusick 
67*46575Sbostic #define	TYPE_1		1		/* x**7 + x**3 + 1 */
68*46575Sbostic #define	BREAK_1		32
69*46575Sbostic #define	DEG_1		7
70*46575Sbostic #define	SEP_1		3
719316Smckusick 
72*46575Sbostic #define	TYPE_2		2		/* x**15 + x + 1 */
73*46575Sbostic #define	BREAK_2		64
74*46575Sbostic #define	DEG_2		15
75*46575Sbostic #define	SEP_2		1
769316Smckusick 
77*46575Sbostic #define	TYPE_3		3		/* x**31 + x**3 + 1 */
78*46575Sbostic #define	BREAK_3		128
79*46575Sbostic #define	DEG_3		31
80*46575Sbostic #define	SEP_3		3
819316Smckusick 
82*46575Sbostic #define	TYPE_4		4		/* x**63 + x + 1 */
83*46575Sbostic #define	BREAK_4		256
84*46575Sbostic #define	DEG_4		63
85*46575Sbostic #define	SEP_4		1
869316Smckusick 
879316Smckusick /*
88*46575Sbostic  * Array versions of the above information to make code run faster --
89*46575Sbostic  * relies on fact that TYPE_i == i.
909316Smckusick  */
91*46575Sbostic #define	MAX_TYPES	5		/* max number of types above */
929316Smckusick 
93*46575Sbostic static int degrees[MAX_TYPES] =	{ DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
94*46575Sbostic static int seps [MAX_TYPES] =	{ SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
959316Smckusick 
969316Smckusick /*
97*46575Sbostic  * Initially, everything is set up as if from:
98*46575Sbostic  *
99*46575Sbostic  *	initstate(1, &randtbl, 128);
100*46575Sbostic  *
1019316Smckusick  * Note that this initialization takes advantage of the fact that srandom()
1029316Smckusick  * advances the front and rear pointers 10*rand_deg times, and hence the
1039316Smckusick  * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
1049316Smckusick  * element of the state information, which contains info about the current
1059316Smckusick  * position of the rear pointer is just
106*46575Sbostic  *
107*46575Sbostic  *	MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
1089316Smckusick  */
1099316Smckusick 
110*46575Sbostic static long randtbl[DEG_3 + 1] = {
111*46575Sbostic 	TYPE_3,
112*46575Sbostic 	0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
113*46575Sbostic 	0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd,
114*46575Sbostic 	0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88,
115*46575Sbostic 	0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc,
116*46575Sbostic 	0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
117*46575Sbostic 	0x27fb47b9,
118*46575Sbostic };
1199316Smckusick 
1209316Smckusick /*
1219316Smckusick  * fptr and rptr are two pointers into the state info, a front and a rear
122*46575Sbostic  * pointer.  These two pointers are always rand_sep places aparts, as they
123*46575Sbostic  * cycle cyclically through the state information.  (Yes, this does mean we
124*46575Sbostic  * could get away with just one pointer, but the code for random() is more
125*46575Sbostic  * efficient this way).  The pointers are left positioned as they would be
126*46575Sbostic  * from the call
127*46575Sbostic  *
128*46575Sbostic  *	initstate(1, randtbl, 128);
129*46575Sbostic  *
1309316Smckusick  * (The position of the rear pointer, rptr, is really 0 (as explained above
1319316Smckusick  * in the initialization of randtbl) because the state table pointer is set
1329316Smckusick  * to point to randtbl[1] (as explained below).
1339316Smckusick  */
134*46575Sbostic static long *fptr = &randtbl[SEP_3 + 1];
135*46575Sbostic static long *rptr = &randtbl[1];
1369316Smckusick 
1379316Smckusick /*
138*46575Sbostic  * The following things are the pointer to the state information table, the
139*46575Sbostic  * type of the current generator, the degree of the current polynomial being
140*46575Sbostic  * used, and the separation between the two pointers.  Note that for efficiency
141*46575Sbostic  * of random(), we remember the first location of the state information, not
142*46575Sbostic  * the zeroeth.  Hence it is valid to access state[-1], which is used to
143*46575Sbostic  * store the type of the R.N.G.  Also, we remember the last location, since
144*46575Sbostic  * this is more efficient than indexing every time to find the address of
145*46575Sbostic  * the last element to see if the front and rear pointers have wrapped.
1469316Smckusick  */
147*46575Sbostic static long *state = &randtbl[1];
148*46575Sbostic static int rand_type = TYPE_3;
149*46575Sbostic static int rand_deg = DEG_3;
150*46575Sbostic static int rand_sep = SEP_3;
151*46575Sbostic static long *end_ptr = &randtbl[DEG_3 + 1];
1529316Smckusick 
1539316Smckusick /*
1549316Smckusick  * srandom:
155*46575Sbostic  *
1569316Smckusick  * Initialize the random number generator based on the given seed.  If the
1579316Smckusick  * type is the trivial no-state-information type, just remember the seed.
1589316Smckusick  * Otherwise, initializes state[] based on the given "seed" via a linear
1599316Smckusick  * congruential generator.  Then, the pointers are set to known locations
1609316Smckusick  * that are exactly rand_sep places apart.  Lastly, it cycles the state
1619316Smckusick  * information a given number of times to get rid of any initial dependencies
162*46575Sbostic  * introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
163*46575Sbostic  * for default usage relies on values produced by this routine.
1649316Smckusick  */
16546573Sdonn void
166*46575Sbostic srandom(x)
167*46575Sbostic 	u_int x;
1689316Smckusick {
169*46575Sbostic 	register int i, j;
1709316Smckusick 
171*46575Sbostic 	if (rand_type == TYPE_0)
172*46575Sbostic 		state[0] = x;
173*46575Sbostic 	else {
174*46575Sbostic 		j = 1;
175*46575Sbostic 		state[0] = x;
176*46575Sbostic 		for (i = 1; i < rand_deg; i++)
177*46575Sbostic 			state[i] = 1103515245 * state[i - 1] + 12345;
178*46575Sbostic 		fptr = &state[rand_sep];
179*46575Sbostic 		rptr = &state[0];
180*46575Sbostic 		for (i = 0; i < 10 * rand_deg; i++)
181*46575Sbostic 			(void)random();
1829316Smckusick 	}
1839316Smckusick }
1849316Smckusick 
1859316Smckusick /*
1869316Smckusick  * initstate:
187*46575Sbostic  *
188*46575Sbostic  * Initialize the state information in the given array of n bytes for future
189*46575Sbostic  * random number generation.  Based on the number of bytes we are given, and
190*46575Sbostic  * the break values for the different R.N.G.'s, we choose the best (largest)
191*46575Sbostic  * one we can and set things up for it.  srandom() is then called to
192*46575Sbostic  * initialize the state information.
193*46575Sbostic  *
1949316Smckusick  * Note that on return from srandom(), we set state[-1] to be the type
1959316Smckusick  * multiplexed with the current value of the rear pointer; this is so
196*46575Sbostic  * successive calls to initstate() won't lose this information and will be
197*46575Sbostic  * able to restart with setstate().
198*46575Sbostic  *
1999316Smckusick  * Note: the first thing we do is save the current state, if any, just like
2009316Smckusick  * setstate() so that it doesn't matter when initstate is called.
201*46575Sbostic  *
2029316Smckusick  * Returns a pointer to the old state.
2039316Smckusick  */
204*46575Sbostic char *
205*46575Sbostic initstate(seed, arg_state, n)
206*46575Sbostic 	u_int seed;			/* seed for R.N.G. */
207*46575Sbostic 	char *arg_state;		/* pointer to state array */
208*46575Sbostic 	int n;				/* # bytes of state info */
2099316Smckusick {
210*46575Sbostic 	register char *ostate = (char *)(&state[-1]);
2119316Smckusick 
212*46575Sbostic 	if (rand_type == TYPE_0)
213*46575Sbostic 		state[-1] = rand_type;
214*46575Sbostic 	else
215*46575Sbostic 		state[-1] = MAX_TYPES * (rptr - state) + rand_type;
216*46575Sbostic 	if (n < BREAK_0) {
217*46575Sbostic 		(void)fprintf(stderr,
218*46575Sbostic 		    "random: not enough state (%d bytes); ignored.\n", n);
219*46575Sbostic 		return(0);
2209316Smckusick 	}
221*46575Sbostic 	if (n < BREAK_1) {
222*46575Sbostic 		rand_type = TYPE_0;
223*46575Sbostic 		rand_deg = DEG_0;
224*46575Sbostic 		rand_sep = SEP_0;
225*46575Sbostic 	} else if (n < BREAK_2) {
2269316Smckusick 		rand_type = TYPE_1;
2279316Smckusick 		rand_deg = DEG_1;
2289316Smckusick 		rand_sep = SEP_1;
229*46575Sbostic 	} else if (n < BREAK_3) {
230*46575Sbostic 		rand_type = TYPE_2;
231*46575Sbostic 		rand_deg = DEG_2;
232*46575Sbostic 		rand_sep = SEP_2;
233*46575Sbostic 	} else if (n < BREAK_4) {
234*46575Sbostic 		rand_type = TYPE_3;
235*46575Sbostic 		rand_deg = DEG_3;
236*46575Sbostic 		rand_sep = SEP_3;
237*46575Sbostic 	} else {
238*46575Sbostic 		rand_type = TYPE_4;
239*46575Sbostic 		rand_deg = DEG_4;
240*46575Sbostic 		rand_sep = SEP_4;
2419316Smckusick 	}
242*46575Sbostic 	state = &(((long *)arg_state)[1]);	/* first location */
243*46575Sbostic 	end_ptr = &state[rand_deg];	/* must set end_ptr before srandom */
244*46575Sbostic 	srandom(seed);
245*46575Sbostic 	if (rand_type == TYPE_0)
246*46575Sbostic 		state[-1] = rand_type;
247*46575Sbostic 	else
248*46575Sbostic 		state[-1] = MAX_TYPES*(rptr - state) + rand_type;
249*46575Sbostic 	return(ostate);
2509316Smckusick }
2519316Smckusick 
2529316Smckusick /*
2539316Smckusick  * setstate:
254*46575Sbostic  *
2559316Smckusick  * Restore the state from the given state array.
256*46575Sbostic  *
2579316Smckusick  * Note: it is important that we also remember the locations of the pointers
2589316Smckusick  * in the current state information, and restore the locations of the pointers
2599316Smckusick  * from the old state information.  This is done by multiplexing the pointer
2609316Smckusick  * location into the zeroeth word of the state information.
261*46575Sbostic  *
2629316Smckusick  * Note that due to the order in which things are done, it is OK to call
2639316Smckusick  * setstate() with the same state as the current state.
264*46575Sbostic  *
2659316Smckusick  * Returns a pointer to the old state information.
2669316Smckusick  */
267*46575Sbostic char *
268*46575Sbostic setstate(arg_state)
269*46575Sbostic 	char *arg_state;
2709316Smckusick {
271*46575Sbostic 	register long *new_state = (long *)arg_state;
272*46575Sbostic 	register int type = new_state[0] % MAX_TYPES;
273*46575Sbostic 	register int rear = new_state[0] / MAX_TYPES;
274*46575Sbostic 	char *ostate = (char *)(&state[-1]);
2759316Smckusick 
276*46575Sbostic 	if (rand_type == TYPE_0)
277*46575Sbostic 		state[-1] = rand_type;
278*46575Sbostic 	else
279*46575Sbostic 		state[-1] = MAX_TYPES * (rptr - state) + rand_type;
280*46575Sbostic 	switch(type) {
281*46575Sbostic 	case TYPE_0:
282*46575Sbostic 	case TYPE_1:
283*46575Sbostic 	case TYPE_2:
284*46575Sbostic 	case TYPE_3:
285*46575Sbostic 	case TYPE_4:
2869316Smckusick 		rand_type = type;
287*46575Sbostic 		rand_deg = degrees[type];
288*46575Sbostic 		rand_sep = seps[type];
2899316Smckusick 		break;
290*46575Sbostic 	default:
291*46575Sbostic 		(void)fprintf(stderr,
292*46575Sbostic 		    "random: state info corrupted; not changed.\n");
2939316Smckusick 	}
294*46575Sbostic 	state = &new_state[1];
295*46575Sbostic 	if (rand_type != TYPE_0) {
296*46575Sbostic 		rptr = &state[rear];
297*46575Sbostic 		fptr = &state[(rear + rand_sep) % rand_deg];
2989316Smckusick 	}
299*46575Sbostic 	end_ptr = &state[rand_deg];		/* set end_ptr too */
300*46575Sbostic 	return(ostate);
3019316Smckusick }
3029316Smckusick 
3039316Smckusick /*
3049316Smckusick  * random:
305*46575Sbostic  *
3069316Smckusick  * If we are using the trivial TYPE_0 R.N.G., just do the old linear
307*46575Sbostic  * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is
308*46575Sbostic  * the same in all the other cases due to all the global variables that have
309*46575Sbostic  * been set up.  The basic operation is to add the number at the rear pointer
310*46575Sbostic  * into the one at the front pointer.  Then both pointers are advanced to
311*46575Sbostic  * the next location cyclically in the table.  The value returned is the sum
312*46575Sbostic  * generated, reduced to 31 bits by throwing away the "least random" low bit.
313*46575Sbostic  *
3149316Smckusick  * Note: the code takes advantage of the fact that both the front and
3159316Smckusick  * rear pointers can't wrap on the same call by not testing the rear
3169316Smckusick  * pointer if the front one has wrapped.
317*46575Sbostic  *
3189316Smckusick  * Returns a 31-bit random number.
3199316Smckusick  */
3209316Smckusick long
3219316Smckusick random()
3229316Smckusick {
323*46575Sbostic 	long i;
324*46575Sbostic 
325*46575Sbostic 	if (rand_type == TYPE_0)
326*46575Sbostic 		i = state[0] = (state[0] * 1103515245 + 12345) & 0x7fffffff;
327*46575Sbostic 	else {
328*46575Sbostic 		*fptr += *rptr;
329*46575Sbostic 		i = (*fptr >> 1) & 0x7fffffff;	/* chucking least random bit */
330*46575Sbostic 		if (++fptr >= end_ptr) {
331*46575Sbostic 			fptr = state;
332*46575Sbostic 			++rptr;
333*46575Sbostic 		} else if (++rptr >= end_ptr)
334*46575Sbostic 			rptr = state;
3359316Smckusick 	}
336*46575Sbostic 	return(i);
3379316Smckusick }
338