1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 /* Originally developed and coded by Makoto Matsumoto and Takuji
21 * Nishimura. Please mail <matumoto@math.keio.ac.jp>, if you're using
22 * code from this file in your own programs or libraries.
23 * Further information on the Mersenne Twister can be found at
24 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
25 * This code was adapted to glib by Sebastian Wilhelmi.
29 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
30 * file for a list of people on the GLib Team. See the ChangeLog
31 * files for a list of changes. These files are distributed with
32 * GLib at ftp://ftp.gtk.org/pub/gtk/.
46 #include <sys/types.h>
52 #include "gtestutils.h"
62 #include <process.h> /* For getpid() */
66 * SECTION:random_numbers
67 * @title: Random Numbers
68 * @short_description: pseudo-random number generator
70 * The following functions allow you to use a portable, fast and good
71 * pseudo-random number generator (PRNG).
73 * Do not use this API for cryptographic purposes such as key
74 * generation, nonces, salts or one-time pads.
76 * This PRNG is suitable for non-cryptographic use such as in games
77 * (shuffling a card deck, generating levels), generating data for
78 * a test suite, etc. If you need random data for cryptographic
79 * purposes, it is recommended to use platform-specific APIs such
80 * as `/dev/random` on UNIX, or CryptGenRandom() on Windows.
82 * GRand uses the Mersenne Twister PRNG, which was originally
83 * developed by Makoto Matsumoto and Takuji Nishimura. Further
84 * information can be found at
85 * [this page](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html).
87 * If you just need a random number, you simply call the g_random_*
88 * functions, which will create a globally used #GRand and use the
89 * according g_rand_* functions internally. Whenever you need a
90 * stream of reproducible random numbers, you better create a
91 * #GRand yourself and use the g_rand_* functions directly, which
92 * will also be slightly faster. Initializing a #GRand with a
93 * certain seed will produce exactly the same series of random
94 * numbers on all platforms. This can thus be used as a seed for
97 * The g_rand*_range functions will return high quality equally
98 * distributed random numbers, whereas for example the
99 * `(g_random_int()%max)` approach often
100 * doesn't yield equally distributed numbers.
102 * GLib changed the seeding algorithm for the pseudo-random number
103 * generator Mersenne Twister, as used by #GRand. This was necessary,
104 * because some seeds would yield very bad pseudo-random streams.
105 * Also the pseudo-random integers generated by g_rand*_int_range()
106 * will have a slightly better equal distribution with the new
109 * The original seeding and generation algorithms, as found in
110 * GLib 2.0.x, can be used instead of the new ones by setting the
111 * environment variable `G_RANDOM_VERSION` to the value of '2.0'.
112 * Use the GLib-2.0 algorithms only if you have sequences of numbers
113 * generated with Glib-2.0 that you need to reproduce exactly.
119 * The GRand struct is an opaque data structure. It should only be
120 * accessed through the g_rand_* functions.
123 G_LOCK_DEFINE_STATIC (global_random);
125 /* Period parameters */
128 #define MATRIX_A 0x9908b0df /* constant vector a */
129 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
130 #define LOWER_MASK 0x7fffffff /* least significant r bits */
132 /* Tempering parameters */
133 #define TEMPERING_MASK_B 0x9d2c5680
134 #define TEMPERING_MASK_C 0xefc60000
135 #define TEMPERING_SHIFT_U(y) (y >> 11)
136 #define TEMPERING_SHIFT_S(y) (y << 7)
137 #define TEMPERING_SHIFT_T(y) (y << 15)
138 #define TEMPERING_SHIFT_L(y) (y >> 18)
141 get_random_version (void)
143 static gsize initialized = FALSE;
144 static guint random_version;
146 if (g_once_init_enter (&initialized))
148 const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
149 if (!version_string || version_string[0] == '\000' ||
150 strcmp (version_string, "2.2") == 0)
152 else if (strcmp (version_string, "2.0") == 0)
156 g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
160 g_once_init_leave (&initialized, TRUE);
163 return random_version;
168 guint32 mt[N]; /* the array for the state vector */
173 * g_rand_new_with_seed:
174 * @seed: a value to initialize the random number generator
176 * Creates a new random number generator initialized with @seed.
178 * Returns: the new #GRand
181 g_rand_new_with_seed (guint32 seed)
183 GRand *rand = g_new0 (GRand, 1);
184 g_rand_set_seed (rand, seed);
189 * g_rand_new_with_seed_array:
190 * @seed: an array of seeds to initialize the random number generator
191 * @seed_length: an array of seeds to initialize the random number
194 * Creates a new random number generator initialized with @seed.
196 * Returns: the new #GRand
201 g_rand_new_with_seed_array (const guint32 *seed,
204 GRand *rand = g_new0 (GRand, 1);
205 g_rand_set_seed_array (rand, seed, seed_length);
212 * Creates a new random number generator initialized with a seed taken
213 * either from `/dev/urandom` (if existing) or from the current time
216 * On Windows, the seed is taken from rand_s().
218 * Returns: the new #GRand
225 static gboolean dev_urandom_exists = TRUE;
227 if (dev_urandom_exists)
233 dev_urandom = fopen ("/dev/urandom", "rbe");
235 while G_UNLIKELY (dev_urandom == NULL && errno == EINTR);
241 setvbuf (dev_urandom, NULL, _IONBF, 0);
245 r = fread (seed, sizeof (seed), 1, dev_urandom);
247 while G_UNLIKELY (errno == EINTR);
250 dev_urandom_exists = FALSE;
252 fclose (dev_urandom);
255 dev_urandom_exists = FALSE;
258 if (!dev_urandom_exists)
260 gint64 now_us = g_get_real_time ();
261 seed[0] = now_us / G_USEC_PER_SEC;
262 seed[1] = now_us % G_USEC_PER_SEC;
264 seed[3] = getppid ();
266 #else /* G_OS_WIN32 */
267 /* rand_s() is only available since Visual Studio 2005 and
268 * MinGW-w64 has a wrapper that will emulate rand_s() if it's not in msvcrt
270 #if (defined(_MSC_VER) && _MSC_VER >= 1400) || defined(__MINGW64_VERSION_MAJOR)
273 for (i = 0; i < G_N_ELEMENTS (seed); i++)
276 #warning Using insecure seed for random number generation because of missing rand_s() in Windows XP
279 g_get_current_time (&now);
280 seed[0] = now.tv_sec;
281 seed[1] = now.tv_usec;
288 return g_rand_new_with_seed_array (seed, 4);
295 * Frees the memory allocated for the #GRand.
298 g_rand_free (GRand *rand)
300 g_return_if_fail (rand != NULL);
309 * Copies a #GRand into a new one with the same exact state as before.
310 * This way you can take a snapshot of the random number generator for
313 * Returns: the new #GRand
318 g_rand_copy (GRand *rand)
322 g_return_val_if_fail (rand != NULL, NULL);
324 new_rand = g_new0 (GRand, 1);
325 memcpy (new_rand, rand, sizeof (GRand));
333 * @seed: a value to reinitialize the random number generator
335 * Sets the seed for the random number generator #GRand to @seed.
338 g_rand_set_seed (GRand *rand,
341 g_return_if_fail (rand != NULL);
343 switch (get_random_version ())
346 /* setting initial seeds to mt[N] using */
347 /* the generator Line 25 of Table 1 in */
348 /* [KNUTH 1981, The Art of Computer Programming */
349 /* Vol. 2 (2nd Ed.), pp102] */
351 if (seed == 0) /* This would make the PRNG produce only zeros */
352 seed = 0x6b842128; /* Just set it to another number */
355 for (rand->mti=1; rand->mti<N; rand->mti++)
356 rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
360 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
361 /* In the previous version (see above), MSBs of the */
362 /* seed affect only MSBs of the array mt[]. */
365 for (rand->mti=1; rand->mti<N; rand->mti++)
366 rand->mt[rand->mti] = 1812433253UL *
367 (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti;
370 g_assert_not_reached ();
375 * g_rand_set_seed_array:
377 * @seed: array to initialize with
378 * @seed_length: length of array
380 * Initializes the random number generator by an array of longs.
381 * Array can be of arbitrary size, though only the first 624 values
382 * are taken. This function is useful if you have many low entropy
383 * seeds, or if you require more then 32 bits of actual entropy for
389 g_rand_set_seed_array (GRand *rand,
395 g_return_if_fail (rand != NULL);
396 g_return_if_fail (seed_length >= 1);
398 g_rand_set_seed (rand, 19650218UL);
401 k = (N>seed_length ? N : seed_length);
404 rand->mt[i] = (rand->mt[i] ^
405 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
406 + seed[j] + j; /* non linear */
407 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
411 rand->mt[0] = rand->mt[N-1];
419 rand->mt[i] = (rand->mt[i] ^
420 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
421 - i; /* non linear */
422 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
426 rand->mt[0] = rand->mt[N-1];
431 rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
438 * Returns a random #gboolean from @rand_.
439 * This corresponds to an unbiased coin toss.
441 * Returns: a random #gboolean
447 * Returns the next random #guint32 from @rand_ equally distributed over
448 * the range [0..2^32-1].
450 * Returns: a random number
453 g_rand_int (GRand *rand)
456 static const guint32 mag01[2]={0x0, MATRIX_A};
457 /* mag01[x] = x * MATRIX_A for x=0,1 */
459 g_return_val_if_fail (rand != NULL, 0);
461 if (rand->mti >= N) { /* generate N words at one time */
464 for (kk = 0; kk < N - M; kk++) {
465 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
466 rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
468 for (; kk < N - 1; kk++) {
469 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
470 rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
472 y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
473 rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
478 y = rand->mt[rand->mti++];
479 y ^= TEMPERING_SHIFT_U(y);
480 y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
481 y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
482 y ^= TEMPERING_SHIFT_L(y);
487 /* transform [0..2^32] -> [0..1] */
488 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
493 * @begin: lower closed bound of the interval
494 * @end: upper open bound of the interval
496 * Returns the next random #gint32 from @rand_ equally distributed over
497 * the range [@begin..@end-1].
499 * Returns: a random number
502 g_rand_int_range (GRand *rand,
506 guint32 dist = end - begin;
509 g_return_val_if_fail (rand != NULL, begin);
510 g_return_val_if_fail (end > begin, begin);
512 switch (get_random_version ())
515 if (dist <= 0x10000L) /* 2^16 */
517 /* This method, which only calls g_rand_int once is only good
518 * for (end - begin) <= 2^16, because we only have 32 bits set
519 * from the one call to g_rand_int ().
521 * We are using (trans + trans * trans), because g_rand_int only
522 * covers [0..2^32-1] and thus g_rand_int * trans only covers
523 * [0..1-2^-32], but the biggest double < 1 is 1-2^-52.
526 gdouble double_rand = g_rand_int (rand) *
527 (G_RAND_DOUBLE_TRANSFORM +
528 G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
530 random = (gint32) (double_rand * dist);
534 /* Now we use g_rand_double_range (), which will set 52 bits
535 * for us, so that it is safe to round and still get a decent
538 random = (gint32) g_rand_double_range (rand, 0, dist);
546 /* maxvalue is set to the predecessor of the greatest
547 * multiple of dist less or equal 2^32.
550 if (dist <= 0x80000000u) /* 2^31 */
552 /* maxvalue = 2^32 - 1 - (2^32 % dist) */
553 guint32 leftover = (0x80000000u % dist) * 2;
554 if (leftover >= dist) leftover -= dist;
555 maxvalue = 0xffffffffu - leftover;
561 random = g_rand_int (rand);
562 while (random > maxvalue);
568 g_assert_not_reached ();
571 return begin + random;
578 * Returns the next random #gdouble from @rand_ equally distributed over
581 * Returns: a random number
584 g_rand_double (GRand *rand)
586 /* We set all 52 bits after the point for this, not only the first
587 32. That's why we need two calls to g_rand_int */
588 gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
589 retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
591 /* The following might happen due to very bad rounding luck, but
592 * actually this should be more than rare, we just try again then */
594 return g_rand_double (rand);
600 * g_rand_double_range:
602 * @begin: lower closed bound of the interval
603 * @end: upper open bound of the interval
605 * Returns the next random #gdouble from @rand_ equally distributed over
606 * the range [@begin..@end).
608 * Returns: a random number
611 g_rand_double_range (GRand *rand,
617 r = g_rand_double (rand);
619 return r * end - (r - 1) * begin;
623 get_global_random (void)
625 static GRand *global_random;
627 /* called while locked */
629 global_random = g_rand_new ();
631 return global_random;
637 * Returns a random #gboolean.
638 * This corresponds to an unbiased coin toss.
640 * Returns: a random #gboolean
645 * Return a random #guint32 equally distributed over the range
648 * Returns: a random number
654 G_LOCK (global_random);
655 result = g_rand_int (get_global_random ());
656 G_UNLOCK (global_random);
661 * g_random_int_range:
662 * @begin: lower closed bound of the interval
663 * @end: upper open bound of the interval
665 * Returns a random #gint32 equally distributed over the range
668 * Returns: a random number
671 g_random_int_range (gint32 begin,
675 G_LOCK (global_random);
676 result = g_rand_int_range (get_global_random (), begin, end);
677 G_UNLOCK (global_random);
684 * Returns a random #gdouble equally distributed over the range [0..1).
686 * Returns: a random number
689 g_random_double (void)
692 G_LOCK (global_random);
693 result = g_rand_double (get_global_random ());
694 G_UNLOCK (global_random);
699 * g_random_double_range:
700 * @begin: lower closed bound of the interval
701 * @end: upper open bound of the interval
703 * Returns a random #gdouble equally distributed over the range
706 * Returns: a random number
709 g_random_double_range (gdouble begin,
713 G_LOCK (global_random);
714 result = g_rand_double_range (get_global_random (), begin, end);
715 G_UNLOCK (global_random);
721 * @seed: a value to reinitialize the global random number generator
723 * Sets the seed for the global random number generator, which is used
724 * by the g_random_* functions, to @seed.
727 g_random_set_seed (guint32 seed)
729 G_LOCK (global_random);
730 g_rand_set_seed (get_global_random (), seed);
731 G_UNLOCK (global_random);