]>
git.saurik.com Git - apple/libc.git/blob - stdlib/random.c
83c3926dc19519d17fdcd09ce51d39fd6b08829a
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
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
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.
23 * @APPLE_LICENSE_HEADER_END@
26 * Copyright (c) 1983, 1993
27 * The Regents of the University of California. All rights reserved.
29 * Redistribution and use in source and binary forms, with or without
30 * modification, are permitted provided that the following conditions
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.
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
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.
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).
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.
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.
109 #define TYPE_0 0 /* linear congruential */
114 #define TYPE_1 1 /* x**7 + x**3 + 1 */
119 #define TYPE_2 2 /* x**15 + x + 1 */
124 #define TYPE_3 3 /* x**31 + x**3 + 1 */
129 #define TYPE_4 4 /* x**63 + x + 1 */
135 * Array versions of the above information to make code run faster --
136 * relies on fact that TYPE_i == i.
138 #define MAX_TYPES 5 /* max number of types above */
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
};
144 * Initially, everything is set up as if from:
146 * initstate(1, &randtbl, 128);
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
154 * MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
157 static long randtbl
[DEG_3
+ 1] = {
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,
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
175 * initstate(1, randtbl, 128);
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).
181 static long *fptr
= &randtbl
[SEP_3
+ 1];
182 static long *rptr
= &randtbl
[1];
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.
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];
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.
218 if (rand_type
== TYPE_0
)
222 for (i
= 1; i
< rand_deg
; i
++)
223 state
[i
] = 1103515245 * state
[i
- 1] + 12345;
224 fptr
= &state
[rand_sep
];
226 for (i
= 0; i
< 10 * rand_deg
; i
++)
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.
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().
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.
248 * Returns a pointer to the old state.
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.
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 */
260 register char *ostate
= (char *)(&state
[-1]);
261 register long *long_arg_state
= (long *) arg_state
;
263 if (rand_type
== TYPE_0
)
264 state
[-1] = rand_type
;
266 state
[-1] = MAX_TYPES
* (rptr
- state
) + rand_type
;
268 (void)fprintf(stderr
,
269 "random: not enough state (%ld bytes); ignored.\n", n
);
276 } else if (n
< BREAK_2
) {
280 } else if (n
< BREAK_3
) {
284 } else if (n
< BREAK_4
) {
293 state
= (long *) (long_arg_state
+ 1); /* first location */
294 end_ptr
= &state
[rand_deg
]; /* must set end_ptr before srandom */
296 if (rand_type
== TYPE_0
)
297 long_arg_state
[0] = rand_type
;
299 long_arg_state
[0] = MAX_TYPES
* (rptr
- state
) + rand_type
;
306 * Restore the state from the given state array.
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.
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.
316 * Returns a pointer to the old state information.
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.
324 char *arg_state
; /* pointer to state array */
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]);
331 if (rand_type
== TYPE_0
)
332 state
[-1] = rand_type
;
334 state
[-1] = MAX_TYPES
* (rptr
- state
) + rand_type
;
342 rand_deg
= degrees
[type
];
343 rand_sep
= seps
[type
];
346 (void)fprintf(stderr
,
347 "random: state info corrupted; not changed.\n");
349 state
= (long *) (new_state
+ 1);
350 if (rand_type
!= TYPE_0
) {
352 fptr
= &state
[(rear
+ rand_sep
) % rand_deg
];
354 end_ptr
= &state
[rand_deg
]; /* set end_ptr too */
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.
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.
373 * Returns a 31-bit random number.
379 register long *f
, *r
;
381 if (rand_type
== TYPE_0
) {
383 state
[0] = i
= (i
* 1103515245 + 12345) & 0x7fffffff;
386 * Use local variables rather than static variables for speed.
390 i
= (*f
>> 1) & 0x7fffffff; /* chucking least random bit */
391 if (++f
>= end_ptr
) {
395 else if (++r
>= end_ptr
) {