random.c revision 118731
11573Srgrimes/*
21573Srgrimes * Copyright (c) 1983, 1993
31573Srgrimes *	The Regents of the University of California.  All rights reserved.
41573Srgrimes *
51573Srgrimes * Redistribution and use in source and binary forms, with or without
61573Srgrimes * modification, are permitted provided that the following conditions
71573Srgrimes * are met:
81573Srgrimes * 1. Redistributions of source code must retain the above copyright
91573Srgrimes *    notice, this list of conditions and the following disclaimer.
101573Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111573Srgrimes *    notice, this list of conditions and the following disclaimer in the
121573Srgrimes *    documentation and/or other materials provided with the distribution.
131573Srgrimes * 3. All advertising materials mentioning features or use of this software
141573Srgrimes *    must display the following acknowledgement:
151573Srgrimes *	This product includes software developed by the University of
161573Srgrimes *	California, Berkeley and its contributors.
171573Srgrimes * 4. Neither the name of the University nor the names of its contributors
181573Srgrimes *    may be used to endorse or promote products derived from this software
191573Srgrimes *    without specific prior written permission.
201573Srgrimes *
211573Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
221573Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
231573Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
241573Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
251573Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
261573Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
271573Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
281573Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
291573Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
301573Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311573Srgrimes * SUCH DAMAGE.
321573Srgrimes */
331573Srgrimes
341573Srgrimes#if defined(LIBC_SCCS) && !defined(lint)
3523662Speterstatic char sccsid[] = "@(#)random.c	8.2 (Berkeley) 5/19/95";
361573Srgrimes#endif /* LIBC_SCCS and not lint */
3792986Sobrien#include <sys/cdefs.h>
3892986Sobrien__FBSDID("$FreeBSD: head/lib/libc/stdlib/random.c 118731 2003-08-10 17:49:55Z ache $");
391573Srgrimes
4071579Sdeischen#include "namespace.h"
4126624Sache#include <sys/time.h>          /* for srandomdev() */
4224151Sache#include <fcntl.h>             /* for srandomdev() */
431573Srgrimes#include <stdio.h>
441573Srgrimes#include <stdlib.h>
4524151Sache#include <unistd.h>            /* for srandomdev() */
4671579Sdeischen#include "un-namespace.h"
471573Srgrimes
481573Srgrimes/*
491573Srgrimes * random.c:
501573Srgrimes *
511573Srgrimes * An improved random number generation package.  In addition to the standard
521573Srgrimes * rand()/srand() like interface, this package also has a special state info
531573Srgrimes * interface.  The initstate() routine is called with a seed, an array of
541573Srgrimes * bytes, and a count of how many bytes are being passed in; this array is
551573Srgrimes * then initialized to contain information for random number generation with
561573Srgrimes * that much state information.  Good sizes for the amount of state
571573Srgrimes * information are 32, 64, 128, and 256 bytes.  The state can be switched by
581573Srgrimes * calling the setstate() routine with the same array as was initiallized
591573Srgrimes * with initstate().  By default, the package runs with 128 bytes of state
601573Srgrimes * information and generates far better random numbers than a linear
611573Srgrimes * congruential generator.  If the amount of state information is less than
621573Srgrimes * 32 bytes, a simple linear congruential R.N.G. is used.
631573Srgrimes *
641573Srgrimes * Internally, the state information is treated as an array of longs; the
651573Srgrimes * zeroeth element of the array is the type of R.N.G. being used (small
661573Srgrimes * integer); the remainder of the array is the state information for the
671573Srgrimes * R.N.G.  Thus, 32 bytes of state information will give 7 longs worth of
681573Srgrimes * state information, which will allow a degree seven polynomial.  (Note:
691573Srgrimes * the zeroeth word of state information also has some other information
701573Srgrimes * stored in it -- see setstate() for details).
718870Srgrimes *
721573Srgrimes * The random number generation technique is a linear feedback shift register
731573Srgrimes * approach, employing trinomials (since there are fewer terms to sum up that
741573Srgrimes * way).  In this approach, the least significant bit of all the numbers in
751573Srgrimes * the state table will act as a linear feedback shift register, and will
761573Srgrimes * have period 2^deg - 1 (where deg is the degree of the polynomial being
771573Srgrimes * used, assuming that the polynomial is irreducible and primitive).  The
781573Srgrimes * higher order bits will have longer periods, since their values are also
791573Srgrimes * influenced by pseudo-random carries out of the lower bits.  The total
801573Srgrimes * period of the generator is approximately deg*(2**deg - 1); thus doubling
811573Srgrimes * the amount of state information has a vast influence on the period of the
821573Srgrimes * generator.  Note: the deg*(2**deg - 1) is an approximation only good for
8392889Sobrien * large deg, when the period of the shift is the dominant factor.
841573Srgrimes * With deg equal to seven, the period is actually much longer than the
851573Srgrimes * 7*(2**7 - 1) predicted by this formula.
8623662Speter *
8723662Speter * Modified 28 December 1994 by Jacob S. Rosenberg.
8823662Speter * The following changes have been made:
8923662Speter * All references to the type u_int have been changed to unsigned long.
9023662Speter * All references to type int have been changed to type long.  Other
9123662Speter * cleanups have been made as well.  A warning for both initstate and
9223662Speter * setstate has been inserted to the effect that on Sparc platforms
9323662Speter * the 'arg_state' variable must be forced to begin on word boundaries.
9423662Speter * This can be easily done by casting a long integer array to char *.
9523662Speter * The overall logic has been left STRICTLY alone.  This software was
9623662Speter * tested on both a VAX and Sun SpacsStation with exactly the same
9723662Speter * results.  The new version and the original give IDENTICAL results.
9823662Speter * The new version is somewhat faster than the original.  As the
9923662Speter * documentation says:  "By default, the package runs with 128 bytes of
10023662Speter * state information and generates far better random numbers than a linear
10123662Speter * congruential generator.  If the amount of state information is less than
10223662Speter * 32 bytes, a simple linear congruential R.N.G. is used."  For a buffer of
10323662Speter * 128 bytes, this new version runs about 19 percent faster and for a 16
10423662Speter * byte buffer it is about 5 percent faster.
1051573Srgrimes */
1061573Srgrimes
1071573Srgrimes/*
1081573Srgrimes * For each of the currently supported random number generators, we have a
1091573Srgrimes * break value on the amount of state information (you need at least this
1101573Srgrimes * many bytes of state info to support this random number generator), a degree
1111573Srgrimes * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
1121573Srgrimes * the separation between the two lower order coefficients of the trinomial.
1131573Srgrimes */
1141573Srgrimes#define	TYPE_0		0		/* linear congruential */
1151573Srgrimes#define	BREAK_0		8
1161573Srgrimes#define	DEG_0		0
1171573Srgrimes#define	SEP_0		0
1181573Srgrimes
1191573Srgrimes#define	TYPE_1		1		/* x**7 + x**3 + 1 */
1201573Srgrimes#define	BREAK_1		32
1211573Srgrimes#define	DEG_1		7
1221573Srgrimes#define	SEP_1		3
1231573Srgrimes
1241573Srgrimes#define	TYPE_2		2		/* x**15 + x + 1 */
1251573Srgrimes#define	BREAK_2		64
1261573Srgrimes#define	DEG_2		15
1271573Srgrimes#define	SEP_2		1
1281573Srgrimes
1291573Srgrimes#define	TYPE_3		3		/* x**31 + x**3 + 1 */
1301573Srgrimes#define	BREAK_3		128
1311573Srgrimes#define	DEG_3		31
1321573Srgrimes#define	SEP_3		3
1331573Srgrimes
1341573Srgrimes#define	TYPE_4		4		/* x**63 + x + 1 */
1351573Srgrimes#define	BREAK_4		256
1361573Srgrimes#define	DEG_4		63
1371573Srgrimes#define	SEP_4		1
1381573Srgrimes
1391573Srgrimes/*
1401573Srgrimes * Array versions of the above information to make code run faster --
1411573Srgrimes * relies on fact that TYPE_i == i.
1421573Srgrimes */
1431573Srgrimes#define	MAX_TYPES	5		/* max number of types above */
1441573Srgrimes
145118731Sache#ifdef  USE_WEAK_SEEDING
146118731Sache#define NSHUFF 0
147118731Sache#else   /* !USE_WEAK_SEEDING */
148118731Sache#define NSHUFF 50       /* to drop some "seed -> 1st value" linearity */
149118731Sache#endif  /* !USE_WEAK_SEEDING */
150110321Sache
15123662Speterstatic long degrees[MAX_TYPES] =	{ DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
15223662Speterstatic long seps [MAX_TYPES] =	{ SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
1531573Srgrimes
1541573Srgrimes/*
1551573Srgrimes * Initially, everything is set up as if from:
1561573Srgrimes *
15718832Sache *	initstate(1, randtbl, 128);
1581573Srgrimes *
1591573Srgrimes * Note that this initialization takes advantage of the fact that srandom()
1601573Srgrimes * advances the front and rear pointers 10*rand_deg times, and hence the
1611573Srgrimes * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
1621573Srgrimes * element of the state information, which contains info about the current
1631573Srgrimes * position of the rear pointer is just
1641573Srgrimes *
1651573Srgrimes *	MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
1661573Srgrimes */
1671573Srgrimes
1681573Srgrimesstatic long randtbl[DEG_3 + 1] = {
1691573Srgrimes	TYPE_3,
17018832Sache#ifdef  USE_WEAK_SEEDING
17118832Sache/* Historic implementation compatibility */
17218832Sache/* The random sequences do not vary much with the seed */
1731573Srgrimes	0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
1741573Srgrimes	0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd,
1751573Srgrimes	0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88,
1761573Srgrimes	0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc,
1771573Srgrimes	0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
1781573Srgrimes	0x27fb47b9,
17918832Sache#else   /* !USE_WEAK_SEEDING */
18018832Sache	0x991539b1, 0x16a5bce3, 0x6774a4cd, 0x3e01511e, 0x4e508aaa, 0x61048c05,
18118832Sache	0xf5500617, 0x846b7115, 0x6a19892c, 0x896a97af, 0xdb48f936, 0x14898454,
18218832Sache	0x37ffd106, 0xb58bff9c, 0x59e17104, 0xcf918a49, 0x09378c83, 0x52c7a471,
18318832Sache	0x8d293ea9, 0x1f4fc301, 0xc3db71be, 0x39b44e1c, 0xf8a44ef9, 0x4c8b80b1,
18418832Sache	0x19edc328, 0x87bf4bdd, 0xc9b240e5, 0xe9ee4b1b, 0x4382aee7, 0x535b6b41,
18518832Sache	0xf3bec5da
18618832Sache#endif  /* !USE_WEAK_SEEDING */
1871573Srgrimes};
1881573Srgrimes
1891573Srgrimes/*
1901573Srgrimes * fptr and rptr are two pointers into the state info, a front and a rear
1911573Srgrimes * pointer.  These two pointers are always rand_sep places aparts, as they
1921573Srgrimes * cycle cyclically through the state information.  (Yes, this does mean we
1931573Srgrimes * could get away with just one pointer, but the code for random() is more
1941573Srgrimes * efficient this way).  The pointers are left positioned as they would be
1951573Srgrimes * from the call
1961573Srgrimes *
1971573Srgrimes *	initstate(1, randtbl, 128);
1981573Srgrimes *
1991573Srgrimes * (The position of the rear pointer, rptr, is really 0 (as explained above
2001573Srgrimes * in the initialization of randtbl) because the state table pointer is set
2011573Srgrimes * to point to randtbl[1] (as explained below).
2021573Srgrimes */
2031573Srgrimesstatic long *fptr = &randtbl[SEP_3 + 1];
2041573Srgrimesstatic long *rptr = &randtbl[1];
2051573Srgrimes
2061573Srgrimes/*
2071573Srgrimes * The following things are the pointer to the state information table, the
2081573Srgrimes * type of the current generator, the degree of the current polynomial being
2091573Srgrimes * used, and the separation between the two pointers.  Note that for efficiency
2101573Srgrimes * of random(), we remember the first location of the state information, not
2111573Srgrimes * the zeroeth.  Hence it is valid to access state[-1], which is used to
2121573Srgrimes * store the type of the R.N.G.  Also, we remember the last location, since
2131573Srgrimes * this is more efficient than indexing every time to find the address of
2141573Srgrimes * the last element to see if the front and rear pointers have wrapped.
2151573Srgrimes */
2161573Srgrimesstatic long *state = &randtbl[1];
21723662Speterstatic long rand_type = TYPE_3;
21823662Speterstatic long rand_deg = DEG_3;
21923662Speterstatic long rand_sep = SEP_3;
2201573Srgrimesstatic long *end_ptr = &randtbl[DEG_3 + 1];
2211573Srgrimes
22292905Sobrienstatic inline long good_rand(long);
22318832Sache
22418832Sachestatic inline long good_rand (x)
22592889Sobrien	long x;
22618832Sache{
22718832Sache#ifdef  USE_WEAK_SEEDING
2281573Srgrimes/*
22918832Sache * Historic implementation compatibility.
23018832Sache * The random sequences do not vary much with the seed,
23118832Sache * even with overflowing.
23218832Sache */
23318832Sache	return (1103515245 * x + 12345);
23418832Sache#else   /* !USE_WEAK_SEEDING */
23518832Sache/*
23618832Sache * Compute x = (7^5 * x) mod (2^31 - 1)
23718832Sache * wihout overflowing 31 bits:
23818832Sache *      (2^31 - 1) = 127773 * (7^5) + 2836
23918832Sache * From "Random number generators: good ones are hard to find",
24018832Sache * Park and Miller, Communications of the ACM, vol. 31, no. 10,
24118832Sache * October 1988, p. 1195.
24218832Sache */
24392889Sobrien	long hi, lo;
24418832Sache
245110280Sache	/* Can't be initialized with 0, so use another value. */
246110280Sache	if (x == 0)
247110280Sache		x = 123459876;
24818832Sache	hi = x / 127773;
24918832Sache	lo = x % 127773;
25018832Sache	x = 16807 * lo - 2836 * hi;
251110280Sache	if (x < 0)
25218832Sache		x += 0x7fffffff;
25318832Sache	return (x);
25418832Sache#endif  /* !USE_WEAK_SEEDING */
25518832Sache}
25618832Sache
25718832Sache/*
2581573Srgrimes * srandom:
2591573Srgrimes *
2601573Srgrimes * Initialize the random number generator based on the given seed.  If the
2611573Srgrimes * type is the trivial no-state-information type, just remember the seed.
2621573Srgrimes * Otherwise, initializes state[] based on the given "seed" via a linear
2631573Srgrimes * congruential generator.  Then, the pointers are set to known locations
2641573Srgrimes * that are exactly rand_sep places apart.  Lastly, it cycles the state
2651573Srgrimes * information a given number of times to get rid of any initial dependencies
2661573Srgrimes * introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
2671573Srgrimes * for default usage relies on values produced by this routine.
2681573Srgrimes */
2691573Srgrimesvoid
2701573Srgrimessrandom(x)
27123662Speter	unsigned long x;
2721573Srgrimes{
273110321Sache	long i, lim;
2741573Srgrimes
275110321Sache	state[0] = x;
2761573Srgrimes	if (rand_type == TYPE_0)
277110321Sache		lim = NSHUFF;
2781573Srgrimes	else {
2791573Srgrimes		for (i = 1; i < rand_deg; i++)
28018832Sache			state[i] = good_rand(state[i - 1]);
2811573Srgrimes		fptr = &state[rand_sep];
2821573Srgrimes		rptr = &state[0];
283110321Sache		lim = 10 * rand_deg;
2841573Srgrimes	}
285110321Sache	for (i = 0; i < lim; i++)
286110321Sache		(void)random();
2871573Srgrimes}
2881573Srgrimes
2891573Srgrimes/*
29024151Sache * srandomdev:
29124151Sache *
29224151Sache * Many programs choose the seed value in a totally predictable manner.
29324151Sache * This often causes problems.  We seed the generator using the much more
29477851Sdd * secure random(4) interface.  Note that this particular seeding
29524151Sache * procedure can generate states which are impossible to reproduce by
29624151Sache * calling srandom() with any value, since the succeeding terms in the
29724151Sache * state buffer are no longer derived from the LC algorithm applied to
29824151Sache * a fixed seed.
29924151Sache */
30026624Sachevoid
30124151Sachesrandomdev()
30224151Sache{
30326624Sache	int fd, done;
30424151Sache	size_t len;
30524151Sache
30624151Sache	if (rand_type == TYPE_0)
30724151Sache		len = sizeof state[0];
30824151Sache	else
30924151Sache		len = rand_deg * sizeof state[0];
31024151Sache
31126624Sache	done = 0;
31285752Smarkm	fd = _open("/dev/random", O_RDONLY, 0);
31326624Sache	if (fd >= 0) {
31456698Sjasone		if (_read(fd, (void *) state, len) == (ssize_t) len)
31526624Sache			done = 1;
31656698Sjasone		_close(fd);
31724151Sache	}
31824151Sache
31926624Sache	if (!done) {
32026624Sache		struct timeval tv;
32126665Sache		unsigned long junk;
32226624Sache
32326624Sache		gettimeofday(&tv, NULL);
32475862Sache		srandom((getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec ^ junk);
32526624Sache		return;
32626624Sache	}
32726624Sache
32824151Sache	if (rand_type != TYPE_0) {
32924151Sache		fptr = &state[rand_sep];
33024151Sache		rptr = &state[0];
33124151Sache	}
33224151Sache}
33324151Sache
33424151Sache/*
3351573Srgrimes * initstate:
3361573Srgrimes *
3371573Srgrimes * Initialize the state information in the given array of n bytes for future
3381573Srgrimes * random number generation.  Based on the number of bytes we are given, and
3391573Srgrimes * the break values for the different R.N.G.'s, we choose the best (largest)
3401573Srgrimes * one we can and set things up for it.  srandom() is then called to
3411573Srgrimes * initialize the state information.
3428870Srgrimes *
3431573Srgrimes * Note that on return from srandom(), we set state[-1] to be the type
3441573Srgrimes * multiplexed with the current value of the rear pointer; this is so
3451573Srgrimes * successive calls to initstate() won't lose this information and will be
3461573Srgrimes * able to restart with setstate().
3478870Srgrimes *
3481573Srgrimes * Note: the first thing we do is save the current state, if any, just like
3491573Srgrimes * setstate() so that it doesn't matter when initstate is called.
3501573Srgrimes *
3511573Srgrimes * Returns a pointer to the old state.
35223662Speter *
35323662Speter * Note: The Sparc platform requires that arg_state begin on a long
35423662Speter * word boundary; otherwise a bus error will occur. Even so, lint will
35523662Speter * complain about mis-alignment, but you should disregard these messages.
3561573Srgrimes */
3571573Srgrimeschar *
3581573Srgrimesinitstate(seed, arg_state, n)
35923662Speter	unsigned long seed;		/* seed for R.N.G. */
3601573Srgrimes	char *arg_state;		/* pointer to state array */
36123662Speter	long n;				/* # bytes of state info */
3621573Srgrimes{
36392889Sobrien	char *ostate = (char *)(&state[-1]);
36492889Sobrien	long *long_arg_state = (long *) arg_state;
3651573Srgrimes
3661573Srgrimes	if (rand_type == TYPE_0)
3671573Srgrimes		state[-1] = rand_type;
3681573Srgrimes	else
3691573Srgrimes		state[-1] = MAX_TYPES * (rptr - state) + rand_type;
3701573Srgrimes	if (n < BREAK_0) {
3711573Srgrimes		(void)fprintf(stderr,
37223662Speter		    "random: not enough state (%ld bytes); ignored.\n", n);
3731573Srgrimes		return(0);
3741573Srgrimes	}
3751573Srgrimes	if (n < BREAK_1) {
3761573Srgrimes		rand_type = TYPE_0;
3771573Srgrimes		rand_deg = DEG_0;
3781573Srgrimes		rand_sep = SEP_0;
3791573Srgrimes	} else if (n < BREAK_2) {
3801573Srgrimes		rand_type = TYPE_1;
3811573Srgrimes		rand_deg = DEG_1;
3821573Srgrimes		rand_sep = SEP_1;
3831573Srgrimes	} else if (n < BREAK_3) {
3841573Srgrimes		rand_type = TYPE_2;
3851573Srgrimes		rand_deg = DEG_2;
3861573Srgrimes		rand_sep = SEP_2;
3871573Srgrimes	} else if (n < BREAK_4) {
3881573Srgrimes		rand_type = TYPE_3;
3891573Srgrimes		rand_deg = DEG_3;
3901573Srgrimes		rand_sep = SEP_3;
3911573Srgrimes	} else {
3921573Srgrimes		rand_type = TYPE_4;
3931573Srgrimes		rand_deg = DEG_4;
3941573Srgrimes		rand_sep = SEP_4;
3951573Srgrimes	}
39623662Speter	state = (long *) (long_arg_state + 1); /* first location */
3971573Srgrimes	end_ptr = &state[rand_deg];	/* must set end_ptr before srandom */
3981573Srgrimes	srandom(seed);
3991573Srgrimes	if (rand_type == TYPE_0)
40023662Speter		long_arg_state[0] = rand_type;
4011573Srgrimes	else
40223662Speter		long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type;
4031573Srgrimes	return(ostate);
4041573Srgrimes}
4051573Srgrimes
4061573Srgrimes/*
4071573Srgrimes * setstate:
4081573Srgrimes *
4091573Srgrimes * Restore the state from the given state array.
4101573Srgrimes *
4111573Srgrimes * Note: it is important that we also remember the locations of the pointers
4121573Srgrimes * in the current state information, and restore the locations of the pointers
4131573Srgrimes * from the old state information.  This is done by multiplexing the pointer
4141573Srgrimes * location into the zeroeth word of the state information.
4151573Srgrimes *
4161573Srgrimes * Note that due to the order in which things are done, it is OK to call
4171573Srgrimes * setstate() with the same state as the current state.
4181573Srgrimes *
4191573Srgrimes * Returns a pointer to the old state information.
42023662Speter *
42123662Speter * Note: The Sparc platform requires that arg_state begin on a long
42223662Speter * word boundary; otherwise a bus error will occur. Even so, lint will
42323662Speter * complain about mis-alignment, but you should disregard these messages.
4241573Srgrimes */
4251573Srgrimeschar *
4261573Srgrimessetstate(arg_state)
42723662Speter	char *arg_state;		/* pointer to state array */
4281573Srgrimes{
42992889Sobrien	long *new_state = (long *) arg_state;
43092889Sobrien	long type = new_state[0] % MAX_TYPES;
43192889Sobrien	long rear = new_state[0] / MAX_TYPES;
4321573Srgrimes	char *ostate = (char *)(&state[-1]);
4331573Srgrimes
4341573Srgrimes	if (rand_type == TYPE_0)
4351573Srgrimes		state[-1] = rand_type;
4361573Srgrimes	else
4371573Srgrimes		state[-1] = MAX_TYPES * (rptr - state) + rand_type;
4381573Srgrimes	switch(type) {
4391573Srgrimes	case TYPE_0:
4401573Srgrimes	case TYPE_1:
4411573Srgrimes	case TYPE_2:
4421573Srgrimes	case TYPE_3:
4431573Srgrimes	case TYPE_4:
4441573Srgrimes		rand_type = type;
4451573Srgrimes		rand_deg = degrees[type];
4461573Srgrimes		rand_sep = seps[type];
4471573Srgrimes		break;
4481573Srgrimes	default:
4491573Srgrimes		(void)fprintf(stderr,
4501573Srgrimes		    "random: state info corrupted; not changed.\n");
4511573Srgrimes	}
45223662Speter	state = (long *) (new_state + 1);
4531573Srgrimes	if (rand_type != TYPE_0) {
4541573Srgrimes		rptr = &state[rear];
4551573Srgrimes		fptr = &state[(rear + rand_sep) % rand_deg];
4561573Srgrimes	}
4571573Srgrimes	end_ptr = &state[rand_deg];		/* set end_ptr too */
4581573Srgrimes	return(ostate);
4591573Srgrimes}
4601573Srgrimes
4611573Srgrimes/*
4621573Srgrimes * random:
4631573Srgrimes *
4641573Srgrimes * If we are using the trivial TYPE_0 R.N.G., just do the old linear
4651573Srgrimes * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is
4661573Srgrimes * the same in all the other cases due to all the global variables that have
4671573Srgrimes * been set up.  The basic operation is to add the number at the rear pointer
4681573Srgrimes * into the one at the front pointer.  Then both pointers are advanced to
4691573Srgrimes * the next location cyclically in the table.  The value returned is the sum
4701573Srgrimes * generated, reduced to 31 bits by throwing away the "least random" low bit.
4711573Srgrimes *
4721573Srgrimes * Note: the code takes advantage of the fact that both the front and
4731573Srgrimes * rear pointers can't wrap on the same call by not testing the rear
4741573Srgrimes * pointer if the front one has wrapped.
4751573Srgrimes *
4761573Srgrimes * Returns a 31-bit random number.
4771573Srgrimes */
4781573Srgrimeslong
4791573Srgrimesrandom()
4801573Srgrimes{
48192889Sobrien	long i;
48292889Sobrien	long *f, *r;
4831573Srgrimes
48423662Speter	if (rand_type == TYPE_0) {
48523662Speter		i = state[0];
48623662Speter		state[0] = i = (good_rand(i)) & 0x7fffffff;
48723662Speter	} else {
48823662Speter		/*
48923662Speter		 * Use local variables rather than static variables for speed.
49023662Speter		 */
49123662Speter		f = fptr; r = rptr;
49223662Speter		*f += *r;
49323662Speter		i = (*f >> 1) & 0x7fffffff;	/* chucking least random bit */
49423662Speter		if (++f >= end_ptr) {
49523662Speter			f = state;
49623662Speter			++r;
49723662Speter		}
49823662Speter		else if (++r >= end_ptr) {
49923662Speter			r = state;
50023662Speter		}
50123662Speter
50223662Speter		fptr = f; rptr = r;
5031573Srgrimes	}
5041573Srgrimes	return(i);
5051573Srgrimes}
506