xref: /csrg-svn/lib/libc/stdlib/random.c (revision 69552)
121354Sdist /*
261180Sbostic  * Copyright (c) 1983, 1993
361180Sbostic  *	The Regents of the University of California.  All rights reserved.
434955Sbostic  *
542625Sbostic  * %sccs.include.redist.c%
621354Sdist  */
721354Sdist 
826578Sdonn #if defined(LIBC_SCCS) && !defined(lint)
9*69552Smckusick static char sccsid[] = "@(#)random.c	8.2 (Berkeley) 05/19/95";
1034955Sbostic #endif /* LIBC_SCCS and not lint */
119316Smckusick 
1234955Sbostic #include <stdio.h>
1346573Sdonn #include <stdlib.h>
149316Smckusick 
159316Smckusick /*
169316Smckusick  * random.c:
1746575Sbostic  *
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
2146575Sbostic  * bytes, and a count of how many bytes are being passed in; this array is
2246575Sbostic  * then initialized to contain information for random number generation with
2346575Sbostic  * that much state information.  Good sizes for the amount of state
2446575Sbostic  * information are 32, 64, 128, and 256 bytes.  The state can be switched by
2546575Sbostic  * calling the setstate() routine with the same array as was initiallized
2646575Sbostic  * with initstate().  By default, the package runs with 128 bytes of state
2746575Sbostic  * information and generates far better random numbers than a linear
2846575Sbostic  * congruential generator.  If the amount of state information is less than
2946575Sbostic  * 32 bytes, a simple linear congruential R.N.G. is used.
3046575Sbostic  *
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
3546575Sbostic  * state information, which will allow a degree seven polynomial.  (Note:
3646575Sbostic  * the zeroeth word of state information also has some other information
3746575Sbostic  * stored in it -- see setstate() for details).
3846575Sbostic  *
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
4246575Sbostic  * the state table will act as a linear feedback shift register, and will
4346575Sbostic  * have period 2^deg - 1 (where deg is the degree of the polynomial being
4446575Sbostic  * used, assuming that the polynomial is irreducible and primitive).  The
4546575Sbostic  * higher order bits will have longer periods, since their values are also
4646575Sbostic  * influenced by pseudo-random carries out of the lower bits.  The total
4746575Sbostic  * period of the generator is approximately deg*(2**deg - 1); thus doubling
4846575Sbostic  * the amount of state information has a vast influence on the period of the
4946575Sbostic  * generator.  Note: the deg*(2**deg - 1) is an approximation only good for
5046575Sbostic  * large deg, when the period of the shift register is the dominant factor.
5146575Sbostic  * With deg equal to seven, the period is actually much longer than the
5246575Sbostic  * 7*(2**7 - 1) predicted by this formula.
53*69552Smckusick  *
54*69552Smckusick  * Modified 28 December 1994 by Jacob S. Rosenberg.
55*69552Smckusick  * The following changes have been made:
56*69552Smckusick  * All references to the type u_int have been changed to unsigned long.
57*69552Smckusick  * All references to type int have been changed to type long.  Other
58*69552Smckusick  * cleanups have been made as well.  A warning for both initstate and
59*69552Smckusick  * setstate has been inserted to the effect that on Sparc platforms
60*69552Smckusick  * the 'arg_state' variable must be forced to begin on word boundaries.
61*69552Smckusick  * This can be easily done by casting a long integer array to char *.
62*69552Smckusick  * The overall logic has been left STRICTLY alone.  This software was
63*69552Smckusick  * tested on both a VAX and Sun SpacsStation with exactly the same
64*69552Smckusick  * results.  The new version and the original give IDENTICAL results.
65*69552Smckusick  * The new version is somewhat faster than the original.  As the
66*69552Smckusick  * documentation says:  "By default, the package runs with 128 bytes of
67*69552Smckusick  * state information and generates far better random numbers than a linear
68*69552Smckusick  * congruential generator.  If the amount of state information is less than
69*69552Smckusick  * 32 bytes, a simple linear congruential R.N.G. is used."  For a buffer of
70*69552Smckusick  * 128 bytes, this new version runs about 19 percent faster and for a 16
71*69552Smckusick  * byte buffer it is about 5 percent faster.
729316Smckusick  */
739316Smckusick 
749316Smckusick /*
759316Smckusick  * For each of the currently supported random number generators, we have a
769316Smckusick  * break value on the amount of state information (you need at least this
779316Smckusick  * many bytes of state info to support this random number generator), a degree
789316Smckusick  * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
799316Smckusick  * the separation between the two lower order coefficients of the trinomial.
809316Smckusick  */
8146575Sbostic #define	TYPE_0		0		/* linear congruential */
8246575Sbostic #define	BREAK_0		8
8346575Sbostic #define	DEG_0		0
8446575Sbostic #define	SEP_0		0
859316Smckusick 
8646575Sbostic #define	TYPE_1		1		/* x**7 + x**3 + 1 */
8746575Sbostic #define	BREAK_1		32
8846575Sbostic #define	DEG_1		7
8946575Sbostic #define	SEP_1		3
909316Smckusick 
9146575Sbostic #define	TYPE_2		2		/* x**15 + x + 1 */
9246575Sbostic #define	BREAK_2		64
9346575Sbostic #define	DEG_2		15
9446575Sbostic #define	SEP_2		1
959316Smckusick 
9646575Sbostic #define	TYPE_3		3		/* x**31 + x**3 + 1 */
9746575Sbostic #define	BREAK_3		128
9846575Sbostic #define	DEG_3		31
9946575Sbostic #define	SEP_3		3
1009316Smckusick 
10146575Sbostic #define	TYPE_4		4		/* x**63 + x + 1 */
10246575Sbostic #define	BREAK_4		256
10346575Sbostic #define	DEG_4		63
10446575Sbostic #define	SEP_4		1
1059316Smckusick 
1069316Smckusick /*
10746575Sbostic  * Array versions of the above information to make code run faster --
10846575Sbostic  * relies on fact that TYPE_i == i.
1099316Smckusick  */
11046575Sbostic #define	MAX_TYPES	5		/* max number of types above */
1119316Smckusick 
112*69552Smckusick static long degrees[MAX_TYPES] =	{ DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
113*69552Smckusick static long seps [MAX_TYPES] =	{ SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
1149316Smckusick 
1159316Smckusick /*
11646575Sbostic  * Initially, everything is set up as if from:
11746575Sbostic  *
11846575Sbostic  *	initstate(1, &randtbl, 128);
11946575Sbostic  *
1209316Smckusick  * Note that this initialization takes advantage of the fact that srandom()
1219316Smckusick  * advances the front and rear pointers 10*rand_deg times, and hence the
1229316Smckusick  * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
1239316Smckusick  * element of the state information, which contains info about the current
1249316Smckusick  * position of the rear pointer is just
12546575Sbostic  *
12646575Sbostic  *	MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
1279316Smckusick  */
1289316Smckusick 
12946575Sbostic static long randtbl[DEG_3 + 1] = {
13046575Sbostic 	TYPE_3,
13146575Sbostic 	0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
13246575Sbostic 	0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd,
13346575Sbostic 	0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88,
13446575Sbostic 	0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc,
13546575Sbostic 	0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
13646575Sbostic 	0x27fb47b9,
13746575Sbostic };
1389316Smckusick 
1399316Smckusick /*
1409316Smckusick  * fptr and rptr are two pointers into the state info, a front and a rear
14146575Sbostic  * pointer.  These two pointers are always rand_sep places aparts, as they
14246575Sbostic  * cycle cyclically through the state information.  (Yes, this does mean we
14346575Sbostic  * could get away with just one pointer, but the code for random() is more
14446575Sbostic  * efficient this way).  The pointers are left positioned as they would be
14546575Sbostic  * from the call
14646575Sbostic  *
14746575Sbostic  *	initstate(1, randtbl, 128);
14846575Sbostic  *
1499316Smckusick  * (The position of the rear pointer, rptr, is really 0 (as explained above
1509316Smckusick  * in the initialization of randtbl) because the state table pointer is set
1519316Smckusick  * to point to randtbl[1] (as explained below).
1529316Smckusick  */
15346575Sbostic static long *fptr = &randtbl[SEP_3 + 1];
15446575Sbostic static long *rptr = &randtbl[1];
1559316Smckusick 
1569316Smckusick /*
15746575Sbostic  * The following things are the pointer to the state information table, the
15846575Sbostic  * type of the current generator, the degree of the current polynomial being
15946575Sbostic  * used, and the separation between the two pointers.  Note that for efficiency
16046575Sbostic  * of random(), we remember the first location of the state information, not
16146575Sbostic  * the zeroeth.  Hence it is valid to access state[-1], which is used to
16246575Sbostic  * store the type of the R.N.G.  Also, we remember the last location, since
16346575Sbostic  * this is more efficient than indexing every time to find the address of
16446575Sbostic  * the last element to see if the front and rear pointers have wrapped.
1659316Smckusick  */
16646575Sbostic static long *state = &randtbl[1];
167*69552Smckusick static long rand_type = TYPE_3;
168*69552Smckusick static long rand_deg = DEG_3;
169*69552Smckusick static long rand_sep = SEP_3;
17046575Sbostic static long *end_ptr = &randtbl[DEG_3 + 1];
1719316Smckusick 
1729316Smckusick /*
1739316Smckusick  * srandom:
17446575Sbostic  *
1759316Smckusick  * Initialize the random number generator based on the given seed.  If the
1769316Smckusick  * type is the trivial no-state-information type, just remember the seed.
1779316Smckusick  * Otherwise, initializes state[] based on the given "seed" via a linear
1789316Smckusick  * congruential generator.  Then, the pointers are set to known locations
1799316Smckusick  * that are exactly rand_sep places apart.  Lastly, it cycles the state
1809316Smckusick  * information a given number of times to get rid of any initial dependencies
18146575Sbostic  * introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
18246575Sbostic  * for default usage relies on values produced by this routine.
1839316Smckusick  */
18446573Sdonn void
srandom(x)18546575Sbostic srandom(x)
186*69552Smckusick 	unsigned long x;
1879316Smckusick {
188*69552Smckusick 	register long i;
1899316Smckusick 
19046575Sbostic 	if (rand_type == TYPE_0)
19146575Sbostic 		state[0] = x;
19246575Sbostic 	else {
19346575Sbostic 		state[0] = x;
19446575Sbostic 		for (i = 1; i < rand_deg; i++)
19546575Sbostic 			state[i] = 1103515245 * state[i - 1] + 12345;
19646575Sbostic 		fptr = &state[rand_sep];
19746575Sbostic 		rptr = &state[0];
19846575Sbostic 		for (i = 0; i < 10 * rand_deg; i++)
19946575Sbostic 			(void)random();
2009316Smckusick 	}
2019316Smckusick }
2029316Smckusick 
2039316Smckusick /*
2049316Smckusick  * initstate:
20546575Sbostic  *
20646575Sbostic  * Initialize the state information in the given array of n bytes for future
20746575Sbostic  * random number generation.  Based on the number of bytes we are given, and
20846575Sbostic  * the break values for the different R.N.G.'s, we choose the best (largest)
20946575Sbostic  * one we can and set things up for it.  srandom() is then called to
21046575Sbostic  * initialize the state information.
21146575Sbostic  *
2129316Smckusick  * Note that on return from srandom(), we set state[-1] to be the type
2139316Smckusick  * multiplexed with the current value of the rear pointer; this is so
21446575Sbostic  * successive calls to initstate() won't lose this information and will be
21546575Sbostic  * able to restart with setstate().
21646575Sbostic  *
2179316Smckusick  * Note: the first thing we do is save the current state, if any, just like
2189316Smckusick  * setstate() so that it doesn't matter when initstate is called.
21946575Sbostic  *
2209316Smckusick  * Returns a pointer to the old state.
221*69552Smckusick  *
222*69552Smckusick  * Note: The Sparc platform requires that arg_state begin on a long
223*69552Smckusick  * word boundary; otherwise a bus error will occur. Even so, lint will
224*69552Smckusick  * complain about mis-alignment, but you should disregard these messages.
2259316Smckusick  */
22646575Sbostic char *
initstate(seed,arg_state,n)22746575Sbostic initstate(seed, arg_state, n)
228*69552Smckusick 	unsigned long seed;		/* seed for R.N.G. */
22946575Sbostic 	char *arg_state;		/* pointer to state array */
230*69552Smckusick 	long n;				/* # bytes of state info */
2319316Smckusick {
23246575Sbostic 	register char *ostate = (char *)(&state[-1]);
233*69552Smckusick 	register long *long_arg_state = (long *) arg_state;
2349316Smckusick 
23546575Sbostic 	if (rand_type == TYPE_0)
23646575Sbostic 		state[-1] = rand_type;
23746575Sbostic 	else
23846575Sbostic 		state[-1] = MAX_TYPES * (rptr - state) + rand_type;
23946575Sbostic 	if (n < BREAK_0) {
24046575Sbostic 		(void)fprintf(stderr,
241*69552Smckusick 		    "random: not enough state (%ld bytes); ignored.\n", n);
24246575Sbostic 		return(0);
2439316Smckusick 	}
24446575Sbostic 	if (n < BREAK_1) {
24546575Sbostic 		rand_type = TYPE_0;
24646575Sbostic 		rand_deg = DEG_0;
24746575Sbostic 		rand_sep = SEP_0;
24846575Sbostic 	} else if (n < BREAK_2) {
2499316Smckusick 		rand_type = TYPE_1;
2509316Smckusick 		rand_deg = DEG_1;
2519316Smckusick 		rand_sep = SEP_1;
25246575Sbostic 	} else if (n < BREAK_3) {
25346575Sbostic 		rand_type = TYPE_2;
25446575Sbostic 		rand_deg = DEG_2;
25546575Sbostic 		rand_sep = SEP_2;
25646575Sbostic 	} else if (n < BREAK_4) {
25746575Sbostic 		rand_type = TYPE_3;
25846575Sbostic 		rand_deg = DEG_3;
25946575Sbostic 		rand_sep = SEP_3;
26046575Sbostic 	} else {
26146575Sbostic 		rand_type = TYPE_4;
26246575Sbostic 		rand_deg = DEG_4;
26346575Sbostic 		rand_sep = SEP_4;
2649316Smckusick 	}
265*69552Smckusick 	state = (long *) (long_arg_state + 1); /* first location */
26646575Sbostic 	end_ptr = &state[rand_deg];	/* must set end_ptr before srandom */
26746575Sbostic 	srandom(seed);
26846575Sbostic 	if (rand_type == TYPE_0)
269*69552Smckusick 		long_arg_state[0] = rand_type;
27046575Sbostic 	else
271*69552Smckusick 		long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type;
27246575Sbostic 	return(ostate);
2739316Smckusick }
2749316Smckusick 
2759316Smckusick /*
2769316Smckusick  * setstate:
27746575Sbostic  *
2789316Smckusick  * Restore the state from the given state array.
27946575Sbostic  *
2809316Smckusick  * Note: it is important that we also remember the locations of the pointers
2819316Smckusick  * in the current state information, and restore the locations of the pointers
2829316Smckusick  * from the old state information.  This is done by multiplexing the pointer
2839316Smckusick  * location into the zeroeth word of the state information.
28446575Sbostic  *
2859316Smckusick  * Note that due to the order in which things are done, it is OK to call
2869316Smckusick  * setstate() with the same state as the current state.
28746575Sbostic  *
2889316Smckusick  * Returns a pointer to the old state information.
289*69552Smckusick  *
290*69552Smckusick  * Note: The Sparc platform requires that arg_state begin on a long
291*69552Smckusick  * word boundary; otherwise a bus error will occur. Even so, lint will
292*69552Smckusick  * complain about mis-alignment, but you should disregard these messages.
2939316Smckusick  */
29446575Sbostic char *
setstate(arg_state)29546575Sbostic setstate(arg_state)
296*69552Smckusick 	char *arg_state;		/* pointer to state array */
2979316Smckusick {
298*69552Smckusick 	register long *new_state = (long *) arg_state;
299*69552Smckusick 	register long type = new_state[0] % MAX_TYPES;
300*69552Smckusick 	register long rear = new_state[0] / MAX_TYPES;
30146575Sbostic 	char *ostate = (char *)(&state[-1]);
3029316Smckusick 
30346575Sbostic 	if (rand_type == TYPE_0)
30446575Sbostic 		state[-1] = rand_type;
30546575Sbostic 	else
30646575Sbostic 		state[-1] = MAX_TYPES * (rptr - state) + rand_type;
30746575Sbostic 	switch(type) {
30846575Sbostic 	case TYPE_0:
30946575Sbostic 	case TYPE_1:
31046575Sbostic 	case TYPE_2:
31146575Sbostic 	case TYPE_3:
31246575Sbostic 	case TYPE_4:
3139316Smckusick 		rand_type = type;
31446575Sbostic 		rand_deg = degrees[type];
31546575Sbostic 		rand_sep = seps[type];
3169316Smckusick 		break;
31746575Sbostic 	default:
31846575Sbostic 		(void)fprintf(stderr,
31946575Sbostic 		    "random: state info corrupted; not changed.\n");
3209316Smckusick 	}
321*69552Smckusick 	state = (long *) (new_state + 1);
32246575Sbostic 	if (rand_type != TYPE_0) {
32346575Sbostic 		rptr = &state[rear];
32446575Sbostic 		fptr = &state[(rear + rand_sep) % rand_deg];
3259316Smckusick 	}
32646575Sbostic 	end_ptr = &state[rand_deg];		/* set end_ptr too */
32746575Sbostic 	return(ostate);
3289316Smckusick }
3299316Smckusick 
3309316Smckusick /*
3319316Smckusick  * random:
33246575Sbostic  *
3339316Smckusick  * If we are using the trivial TYPE_0 R.N.G., just do the old linear
33446575Sbostic  * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is
33546575Sbostic  * the same in all the other cases due to all the global variables that have
33646575Sbostic  * been set up.  The basic operation is to add the number at the rear pointer
33746575Sbostic  * into the one at the front pointer.  Then both pointers are advanced to
33846575Sbostic  * the next location cyclically in the table.  The value returned is the sum
33946575Sbostic  * generated, reduced to 31 bits by throwing away the "least random" low bit.
34046575Sbostic  *
3419316Smckusick  * Note: the code takes advantage of the fact that both the front and
3429316Smckusick  * rear pointers can't wrap on the same call by not testing the rear
3439316Smckusick  * pointer if the front one has wrapped.
34446575Sbostic  *
3459316Smckusick  * Returns a 31-bit random number.
3469316Smckusick  */
3479316Smckusick long
random()3489316Smckusick random()
3499316Smckusick {
350*69552Smckusick 	register long i;
351*69552Smckusick 	register long *f, *r;
35246575Sbostic 
353*69552Smckusick 	if (rand_type == TYPE_0) {
354*69552Smckusick 		i = state[0];
355*69552Smckusick 		state[0] = i = (i * 1103515245 + 12345) & 0x7fffffff;
356*69552Smckusick 	} else {
357*69552Smckusick 		/*
358*69552Smckusick 		 * Use local variables rather than static variables for speed.
359*69552Smckusick 		 */
360*69552Smckusick 		f = fptr; r = rptr;
361*69552Smckusick 		*f += *r;
362*69552Smckusick 		i = (*f >> 1) & 0x7fffffff;	/* chucking least random bit */
363*69552Smckusick 		if (++f >= end_ptr) {
364*69552Smckusick 			f = state;
365*69552Smckusick 			++r;
366*69552Smckusick 		}
367*69552Smckusick 		else if (++r >= end_ptr) {
368*69552Smckusick 			r = state;
369*69552Smckusick 		}
370*69552Smckusick 
371*69552Smckusick 		fptr = f; rptr = r;
3729316Smckusick 	}
37346575Sbostic 	return(i);
3749316Smckusick }
375