1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 /* Originally developed and coded by Makoto Matsumoto and Takuji
19 * Nishimura. Please mail <matumoto@math.keio.ac.jp>, if you're using
20 * code from this file in your own programs or libraries.
21 * Further information on the Mersenne Twister can be found at
22 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
23 * This code was adapted to glib by Sebastian Wilhelmi.
27 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
28 * file for a list of people on the GLib Team. See the ChangeLog
29 * files for a list of changes. These files are distributed with
30 * GLib at ftp://ftp.gtk.org/pub/gtk/.
44 #include <sys/types.h>
50 #include "gtestutils.h"
62 * SECTION:random_numbers
63 * @title: Random Numbers
64 * @short_description: pseudo-random number generator
66 * The following functions allow you to use a portable, fast and good
67 * pseudo-random number generator (PRNG).
69 * Do not use this API for cryptographic purposes such as key
70 * generation, nonces, salts or one-time pads.
72 * This PRNG is suitable for non-cryptographic use such as in games
73 * (shuffling a card deck, generating levels), generating data for a
74 * test suite, etc. If you need random data for cryptographic
75 * purposes, it is recommended to use platform-specific APIs such as
76 * <literal>/dev/random</literal> on Unix, or CryptGenRandom() on
79 * GRand uses the Mersenne Twister PRNG, which was originally
80 * developed by Makoto Matsumoto and Takuji Nishimura. Further
81 * information can be found at <ulink
82 * url="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html">
83 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</ulink>.
85 * If you just need a random number, you simply call the g_random_*
86 * functions, which will create a globally used #GRand and use the
87 * according g_rand_* functions internally. Whenever you need a
88 * stream of reproducible random numbers, you better create a
89 * #GRand yourself and use the g_rand_* functions directly, which
90 * will also be slightly faster. Initializing a #GRand with a
91 * certain seed will produce exactly the same series of random
92 * numbers on all platforms. This can thus be used as a seed for
95 * The g_rand*_range functions will return high quality equally
96 * distributed random numbers, whereas for example the
97 * <literal>(g_random_int()%max)</literal> approach often
98 * doesn't yield equally distributed numbers.
100 * GLib changed the seeding algorithm for the pseudo-random number
101 * generator Mersenne Twister, as used by #GRand. This was necessary,
102 * because some seeds would yield very bad pseudo-random streams.
103 * Also the pseudo-random integers generated by g_rand*_int_range()
104 * will have a slightly better equal distribution with the new
107 * The original seeding and generation algorithms, as found in
108 * GLib 2.0.x, can be used instead of the new ones by setting the
109 * environment variable `G_RANDOM_VERSION` to the value of '2.0'.
110 * Use the GLib-2.0 algorithms only if you have sequences of numbers
111 * generated with Glib-2.0 that you need to reproduce exactly.
117 * The GRand struct is an opaque data structure. It should only be
118 * accessed through the g_rand_* functions.
121 G_LOCK_DEFINE_STATIC (global_random);
123 /* Period parameters */
126 #define MATRIX_A 0x9908b0df /* constant vector a */
127 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
128 #define LOWER_MASK 0x7fffffff /* least significant r bits */
130 /* Tempering parameters */
131 #define TEMPERING_MASK_B 0x9d2c5680
132 #define TEMPERING_MASK_C 0xefc60000
133 #define TEMPERING_SHIFT_U(y) (y >> 11)
134 #define TEMPERING_SHIFT_S(y) (y << 7)
135 #define TEMPERING_SHIFT_T(y) (y << 15)
136 #define TEMPERING_SHIFT_L(y) (y >> 18)
139 get_random_version (void)
141 static gsize initialized = FALSE;
142 static guint random_version;
144 if (g_once_init_enter (&initialized))
146 const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
147 if (!version_string || version_string[0] == '\000' ||
148 strcmp (version_string, "2.2") == 0)
150 else if (strcmp (version_string, "2.0") == 0)
154 g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
158 g_once_init_leave (&initialized, TRUE);
161 return random_version;
166 guint32 mt[N]; /* the array for the state vector */
171 * g_rand_new_with_seed:
172 * @seed: a value to initialize the random number generator
174 * Creates a new random number generator initialized with @seed.
176 * Return value: the new #GRand
179 g_rand_new_with_seed (guint32 seed)
181 GRand *rand = g_new0 (GRand, 1);
182 g_rand_set_seed (rand, seed);
187 * g_rand_new_with_seed_array:
188 * @seed: an array of seeds to initialize the random number generator
189 * @seed_length: an array of seeds to initialize the random number
192 * Creates a new random number generator initialized with @seed.
194 * Return value: the new #GRand
199 g_rand_new_with_seed_array (const guint32 *seed,
202 GRand *rand = g_new0 (GRand, 1);
203 g_rand_set_seed_array (rand, seed, seed_length);
210 * Creates a new random number generator initialized with a seed taken
211 * either from `/dev/urandom` (if existing) or from the current time
214 * On Windows, the seed is taken from rand_s().
216 * Return value: the new #GRand
223 static gboolean dev_urandom_exists = TRUE;
226 if (dev_urandom_exists)
232 dev_urandom = fopen("/dev/urandom", "rb");
234 while G_UNLIKELY (dev_urandom == NULL && errno == EINTR);
240 setvbuf (dev_urandom, NULL, _IONBF, 0);
244 r = fread (seed, sizeof (seed), 1, dev_urandom);
246 while G_UNLIKELY (errno == EINTR);
249 dev_urandom_exists = FALSE;
251 fclose (dev_urandom);
254 dev_urandom_exists = FALSE;
257 if (!dev_urandom_exists)
259 g_get_current_time (&now);
260 seed[0] = now.tv_sec;
261 seed[1] = now.tv_usec;
263 seed[3] = getppid ();
265 #else /* G_OS_WIN32 */
268 for (i = 0; i < G_N_ELEMENTS (seed); i++)
272 return g_rand_new_with_seed_array (seed, 4);
279 * Frees the memory allocated for the #GRand.
282 g_rand_free (GRand *rand)
284 g_return_if_fail (rand != NULL);
293 * Copies a #GRand into a new one with the same exact state as before.
294 * This way you can take a snapshot of the random number generator for
297 * Return value: the new #GRand
302 g_rand_copy (GRand *rand)
306 g_return_val_if_fail (rand != NULL, NULL);
308 new_rand = g_new0 (GRand, 1);
309 memcpy (new_rand, rand, sizeof (GRand));
317 * @seed: a value to reinitialize the random number generator
319 * Sets the seed for the random number generator #GRand to @seed.
322 g_rand_set_seed (GRand *rand,
325 g_return_if_fail (rand != NULL);
327 switch (get_random_version ())
330 /* setting initial seeds to mt[N] using */
331 /* the generator Line 25 of Table 1 in */
332 /* [KNUTH 1981, The Art of Computer Programming */
333 /* Vol. 2 (2nd Ed.), pp102] */
335 if (seed == 0) /* This would make the PRNG produce only zeros */
336 seed = 0x6b842128; /* Just set it to another number */
339 for (rand->mti=1; rand->mti<N; rand->mti++)
340 rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
344 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
345 /* In the previous version (see above), MSBs of the */
346 /* seed affect only MSBs of the array mt[]. */
349 for (rand->mti=1; rand->mti<N; rand->mti++)
350 rand->mt[rand->mti] = 1812433253UL *
351 (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti;
354 g_assert_not_reached ();
359 * g_rand_set_seed_array:
361 * @seed: array to initialize with
362 * @seed_length: length of array
364 * Initializes the random number generator by an array of longs.
365 * Array can be of arbitrary size, though only the first 624 values
366 * are taken. This function is useful if you have many low entropy
367 * seeds, or if you require more then 32 bits of actual entropy for
373 g_rand_set_seed_array (GRand *rand,
379 g_return_if_fail (rand != NULL);
380 g_return_if_fail (seed_length >= 1);
382 g_rand_set_seed (rand, 19650218UL);
385 k = (N>seed_length ? N : seed_length);
388 rand->mt[i] = (rand->mt[i] ^
389 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
390 + seed[j] + j; /* non linear */
391 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
395 rand->mt[0] = rand->mt[N-1];
403 rand->mt[i] = (rand->mt[i] ^
404 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
405 - i; /* non linear */
406 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
410 rand->mt[0] = rand->mt[N-1];
415 rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
422 * Returns a random #gboolean from @rand_.
423 * This corresponds to a unbiased coin toss.
425 * Returns: a random #gboolean
431 * Returns the next random #guint32 from @rand_ equally distributed over
432 * the range [0..2^32-1].
434 * Return value: a random number
437 g_rand_int (GRand *rand)
440 static const guint32 mag01[2]={0x0, MATRIX_A};
441 /* mag01[x] = x * MATRIX_A for x=0,1 */
443 g_return_val_if_fail (rand != NULL, 0);
445 if (rand->mti >= N) { /* generate N words at one time */
448 for (kk = 0; kk < N - M; kk++) {
449 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
450 rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
452 for (; kk < N - 1; kk++) {
453 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
454 rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
456 y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
457 rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
462 y = rand->mt[rand->mti++];
463 y ^= TEMPERING_SHIFT_U(y);
464 y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
465 y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
466 y ^= TEMPERING_SHIFT_L(y);
471 /* transform [0..2^32] -> [0..1] */
472 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
477 * @begin: lower closed bound of the interval
478 * @end: upper open bound of the interval
480 * Returns the next random #gint32 from @rand_ equally distributed over
481 * the range [@begin..@end-1].
483 * Return value: a random number
486 g_rand_int_range (GRand *rand,
490 guint32 dist = end - begin;
493 g_return_val_if_fail (rand != NULL, begin);
494 g_return_val_if_fail (end > begin, begin);
496 switch (get_random_version ())
499 if (dist <= 0x10000L) /* 2^16 */
501 /* This method, which only calls g_rand_int once is only good
502 * for (end - begin) <= 2^16, because we only have 32 bits set
503 * from the one call to g_rand_int ().
505 * We are using (trans + trans * trans), because g_rand_int only
506 * covers [0..2^32-1] and thus g_rand_int * trans only covers
507 * [0..1-2^-32], but the biggest double < 1 is 1-2^-52.
510 gdouble double_rand = g_rand_int (rand) *
511 (G_RAND_DOUBLE_TRANSFORM +
512 G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
514 random = (gint32) (double_rand * dist);
518 /* Now we use g_rand_double_range (), which will set 52 bits
519 * for us, so that it is safe to round and still get a decent
522 random = (gint32) g_rand_double_range (rand, 0, dist);
530 /* maxvalue is set to the predecessor of the greatest
531 * multiple of dist less or equal 2^32.
534 if (dist <= 0x80000000u) /* 2^31 */
536 /* maxvalue = 2^32 - 1 - (2^32 % dist) */
537 guint32 leftover = (0x80000000u % dist) * 2;
538 if (leftover >= dist) leftover -= dist;
539 maxvalue = 0xffffffffu - leftover;
545 random = g_rand_int (rand);
546 while (random > maxvalue);
552 random = 0; /* Quiet GCC */
553 g_assert_not_reached ();
556 return begin + random;
563 * Returns the next random #gdouble from @rand_ equally distributed over
566 * Return value: a random number
569 g_rand_double (GRand *rand)
571 /* We set all 52 bits after the point for this, not only the first
572 32. Thats why we need two calls to g_rand_int */
573 gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
574 retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
576 /* The following might happen due to very bad rounding luck, but
577 * actually this should be more than rare, we just try again then */
579 return g_rand_double (rand);
585 * g_rand_double_range:
587 * @begin: lower closed bound of the interval
588 * @end: upper open bound of the interval
590 * Returns the next random #gdouble from @rand_ equally distributed over
591 * the range [@begin..@end).
593 * Return value: a random number
596 g_rand_double_range (GRand *rand,
602 r = g_rand_double (rand);
604 return r * end - (r - 1) * begin;
608 get_global_random (void)
610 static GRand *global_random;
612 /* called while locked */
614 global_random = g_rand_new ();
616 return global_random;
622 * Returns a random #gboolean.
623 * This corresponds to a unbiased coin toss.
625 * Returns: a random #gboolean
630 * Return a random #guint32 equally distributed over the range
633 * Return value: a random number
639 G_LOCK (global_random);
640 result = g_rand_int (get_global_random ());
641 G_UNLOCK (global_random);
646 * g_random_int_range:
647 * @begin: lower closed bound of the interval
648 * @end: upper open bound of the interval
650 * Returns a random #gint32 equally distributed over the range
653 * Return value: a random number
656 g_random_int_range (gint32 begin,
660 G_LOCK (global_random);
661 result = g_rand_int_range (get_global_random (), begin, end);
662 G_UNLOCK (global_random);
669 * Returns a random #gdouble equally distributed over the range [0..1).
671 * Return value: a random number
674 g_random_double (void)
677 G_LOCK (global_random);
678 result = g_rand_double (get_global_random ());
679 G_UNLOCK (global_random);
684 * g_random_double_range:
685 * @begin: lower closed bound of the interval
686 * @end: upper open bound of the interval
688 * Returns a random #gdouble equally distributed over the range
691 * Return value: a random number
694 g_random_double_range (gdouble begin,
698 G_LOCK (global_random);
699 result = g_rand_double_range (get_global_random (), begin, end);
700 G_UNLOCK (global_random);
706 * @seed: a value to reinitialize the global random number generator
708 * Sets the seed for the global random number generator, which is used
709 * by the g_random_* functions, to @seed.
712 g_random_set_seed (guint32 seed)
714 G_LOCK (global_random);
715 g_rand_set_seed (get_global_random (), seed);
716 G_UNLOCK (global_random);