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, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
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/.
45 #include <sys/types.h>
54 #include "gtestutils.h"
56 #include "gthreadprivate.h"
59 #include <process.h> /* For getpid() */
63 * SECTION:random_numbers
64 * @title: Random Numbers
65 * @short_description: pseudo-random number generator
67 * The following functions allow you to use a portable, fast and good
68 * pseudo-random number generator (PRNG). It uses the Mersenne Twister
69 * PRNG, which was originally developed by Makoto Matsumoto and Takuji
70 * Nishimura. Further information can be found at
71 * <ulink url="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html">
72 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</ulink>.
74 * If you just need a random number, you simply call the
75 * <function>g_random_*</function> functions, which will create a
76 * globally used #GRand and use the according
77 * <function>g_rand_*</function> functions internally. Whenever you
78 * need a stream of reproducible random numbers, you better create a
79 * #GRand yourself and use the <function>g_rand_*</function> functions
80 * directly, which will also be slightly faster. Initializing a #GRand
81 * with a certain seed will produce exactly the same series of random
82 * numbers on all platforms. This can thus be used as a seed for e.g.
85 * The <function>g_rand*_range</function> functions will return high
86 * quality equally distributed random numbers, whereas for example the
87 * <literal>(g_random_int()%max)</literal> approach often
88 * doesn't yield equally distributed numbers.
90 * GLib changed the seeding algorithm for the pseudo-random number
91 * generator Mersenne Twister, as used by
92 * <structname>GRand</structname> and <structname>GRandom</structname>.
93 * This was necessary, because some seeds would yield very bad
94 * pseudo-random streams. Also the pseudo-random integers generated by
95 * <function>g_rand*_int_range()</function> will have a slightly better
96 * equal distribution with the new version of GLib.
98 * The original seeding and generation algorithms, as found in GLib
99 * 2.0.x, can be used instead of the new ones by setting the
100 * environment variable <envar>G_RANDOM_VERSION</envar> to the value of
101 * '2.0'. Use the GLib-2.0 algorithms only if you have sequences of
102 * numbers generated with Glib-2.0 that you need to reproduce exactly.
108 * The #GRand struct is an opaque data structure. It should only be
109 * accessed through the <function>g_rand_*</function> functions.
112 G_LOCK_DEFINE_STATIC (global_random);
113 static GRand* global_random = NULL;
115 /* Period parameters */
118 #define MATRIX_A 0x9908b0df /* constant vector a */
119 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
120 #define LOWER_MASK 0x7fffffff /* least significant r bits */
122 /* Tempering parameters */
123 #define TEMPERING_MASK_B 0x9d2c5680
124 #define TEMPERING_MASK_C 0xefc60000
125 #define TEMPERING_SHIFT_U(y) (y >> 11)
126 #define TEMPERING_SHIFT_S(y) (y << 7)
127 #define TEMPERING_SHIFT_T(y) (y << 15)
128 #define TEMPERING_SHIFT_L(y) (y >> 18)
131 get_random_version (void)
133 static gsize initialized = FALSE;
134 static guint random_version;
136 g_thread_init_glib ();
138 if (g_once_init_enter (&initialized))
140 const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
141 if (!version_string || version_string[0] == '\000' ||
142 strcmp (version_string, "2.2") == 0)
144 else if (strcmp (version_string, "2.0") == 0)
148 g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
152 g_once_init_leave (&initialized, TRUE);
155 return random_version;
160 guint32 mt[N]; /* the array for the state vector */
165 * g_rand_new_with_seed:
166 * @seed: a value to initialize the random number generator.
168 * Creates a new random number generator initialized with @seed.
170 * Return value: the new #GRand.
173 g_rand_new_with_seed (guint32 seed)
175 GRand *rand = g_new0 (GRand, 1);
176 g_rand_set_seed (rand, seed);
181 * g_rand_new_with_seed_array:
182 * @seed: an array of seeds to initialize the random number generator.
183 * @seed_length: an array of seeds to initialize the random number generator.
185 * Creates a new random number generator initialized with @seed.
187 * Return value: the new #GRand.
192 g_rand_new_with_seed_array (const guint32 *seed, guint seed_length)
194 GRand *rand = g_new0 (GRand, 1);
195 g_rand_set_seed_array (rand, seed, seed_length);
202 * Creates a new random number generator initialized with a seed taken
203 * either from <filename>/dev/urandom</filename> (if existing) or from
204 * the current time (as a fallback).
206 * Return value: the new #GRand.
214 static gboolean dev_urandom_exists = TRUE;
216 if (dev_urandom_exists)
223 dev_urandom = fopen("/dev/urandom", "rb");
225 while G_UNLIKELY (errno == EINTR);
231 setvbuf (dev_urandom, NULL, _IONBF, 0);
235 r = fread (seed, sizeof (seed), 1, dev_urandom);
237 while G_UNLIKELY (errno == EINTR);
240 dev_urandom_exists = FALSE;
242 fclose (dev_urandom);
245 dev_urandom_exists = FALSE;
248 static gboolean dev_urandom_exists = FALSE;
251 if (!dev_urandom_exists)
253 g_get_current_time (&now);
254 seed[0] = now.tv_sec;
255 seed[1] = now.tv_usec;
258 seed[3] = getppid ();
264 return g_rand_new_with_seed_array (seed, 4);
271 * Frees the memory allocated for the #GRand.
274 g_rand_free (GRand* rand)
276 g_return_if_fail (rand != NULL);
285 * Copies a #GRand into a new one with the same exact state as before.
286 * This way you can take a snapshot of the random number generator for
289 * Return value: the new #GRand.
294 g_rand_copy (GRand* rand)
298 g_return_val_if_fail (rand != NULL, NULL);
300 new_rand = g_new0 (GRand, 1);
301 memcpy (new_rand, rand, sizeof (GRand));
309 * @seed: a value to reinitialize the random number generator.
311 * Sets the seed for the random number generator #GRand to @seed.
314 g_rand_set_seed (GRand* rand, guint32 seed)
316 g_return_if_fail (rand != NULL);
318 switch (get_random_version ())
321 /* setting initial seeds to mt[N] using */
322 /* the generator Line 25 of Table 1 in */
323 /* [KNUTH 1981, The Art of Computer Programming */
324 /* Vol. 2 (2nd Ed.), pp102] */
326 if (seed == 0) /* This would make the PRNG procude only zeros */
327 seed = 0x6b842128; /* Just set it to another number */
330 for (rand->mti=1; rand->mti<N; rand->mti++)
331 rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
335 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
336 /* In the previous version (see above), MSBs of the */
337 /* seed affect only MSBs of the array mt[]. */
340 for (rand->mti=1; rand->mti<N; rand->mti++)
341 rand->mt[rand->mti] = 1812433253UL *
342 (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti;
345 g_assert_not_reached ();
350 * g_rand_set_seed_array:
352 * @seed: array to initialize with
353 * @seed_length: length of array
355 * Initializes the random number generator by an array of
356 * longs. Array can be of arbitrary size, though only the
357 * first 624 values are taken. This function is useful
358 * if you have many low entropy seeds, or if you require more then
359 * 32bits of actual entropy for your application.
364 g_rand_set_seed_array (GRand* rand, const guint32 *seed, guint seed_length)
368 g_return_if_fail (rand != NULL);
369 g_return_if_fail (seed_length >= 1);
371 g_rand_set_seed (rand, 19650218UL);
374 k = (N>seed_length ? N : seed_length);
377 rand->mt[i] = (rand->mt[i] ^
378 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
379 + seed[j] + j; /* non linear */
380 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
384 rand->mt[0] = rand->mt[N-1];
392 rand->mt[i] = (rand->mt[i] ^
393 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
394 - i; /* non linear */
395 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
399 rand->mt[0] = rand->mt[N-1];
404 rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
410 * @Returns: a random #gboolean.
412 * Returns a random #gboolean from @rand_. This corresponds to a
413 * unbiased coin toss.
419 * Returns the next random #guint32 from @rand_ equally distributed over
420 * the range [0..2^32-1].
422 * Return value: A random number.
425 g_rand_int (GRand* rand)
428 static const guint32 mag01[2]={0x0, MATRIX_A};
429 /* mag01[x] = x * MATRIX_A for x=0,1 */
431 g_return_val_if_fail (rand != NULL, 0);
433 if (rand->mti >= N) { /* generate N words at one time */
436 for (kk=0;kk<N-M;kk++) {
437 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
438 rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
441 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
442 rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
444 y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
445 rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
450 y = rand->mt[rand->mti++];
451 y ^= TEMPERING_SHIFT_U(y);
452 y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
453 y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
454 y ^= TEMPERING_SHIFT_L(y);
459 /* transform [0..2^32] -> [0..1] */
460 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
465 * @begin: lower closed bound of the interval.
466 * @end: upper open bound of the interval.
468 * Returns the next random #gint32 from @rand_ equally distributed over
469 * the range [@begin..@end-1].
471 * Return value: A random number.
474 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
476 guint32 dist = end - begin;
479 g_return_val_if_fail (rand != NULL, begin);
480 g_return_val_if_fail (end > begin, begin);
482 switch (get_random_version ())
485 if (dist <= 0x10000L) /* 2^16 */
487 /* This method, which only calls g_rand_int once is only good
488 * for (end - begin) <= 2^16, because we only have 32 bits set
489 * from the one call to g_rand_int (). */
491 /* we are using (trans + trans * trans), because g_rand_int only
492 * covers [0..2^32-1] and thus g_rand_int * trans only covers
493 * [0..1-2^-32], but the biggest double < 1 is 1-2^-52.
496 gdouble double_rand = g_rand_int (rand) *
497 (G_RAND_DOUBLE_TRANSFORM +
498 G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
500 random = (gint32) (double_rand * dist);
504 /* Now we use g_rand_double_range (), which will set 52 bits for
505 us, so that it is safe to round and still get a decent
507 random = (gint32) g_rand_double_range (rand, 0, dist);
515 /* maxvalue is set to the predecessor of the greatest
516 * multiple of dist less or equal 2^32. */
518 if (dist <= 0x80000000u) /* 2^31 */
520 /* maxvalue = 2^32 - 1 - (2^32 % dist) */
521 guint32 leftover = (0x80000000u % dist) * 2;
522 if (leftover >= dist) leftover -= dist;
523 maxvalue = 0xffffffffu - leftover;
529 random = g_rand_int (rand);
530 while (random > maxvalue);
536 random = 0; /* Quiet GCC */
537 g_assert_not_reached ();
540 return begin + random;
547 * Returns the next random #gdouble from @rand_ equally distributed over
550 * Return value: A random number.
553 g_rand_double (GRand* rand)
555 /* We set all 52 bits after the point for this, not only the first
556 32. Thats why we need two calls to g_rand_int */
557 gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
558 retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
560 /* The following might happen due to very bad rounding luck, but
561 * actually this should be more than rare, we just try again then */
563 return g_rand_double (rand);
569 * g_rand_double_range:
571 * @begin: lower closed bound of the interval.
572 * @end: upper open bound of the interval.
574 * Returns the next random #gdouble from @rand_ equally distributed over
575 * the range [@begin..@end).
577 * Return value: A random number.
580 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
584 r = g_rand_double (rand);
586 return r * end - (r - 1) * begin;
591 * @Returns: a random #gboolean.
593 * Returns a random #gboolean. This corresponds to a unbiased coin toss.
598 * Return a random #guint32 equally distributed over the range
601 * Return value: A random number.
607 G_LOCK (global_random);
609 global_random = g_rand_new ();
611 result = g_rand_int (global_random);
612 G_UNLOCK (global_random);
617 * g_random_int_range:
618 * @begin: lower closed bound of the interval.
619 * @end: upper open bound of the interval.
621 * Returns a random #gint32 equally distributed over the range
624 * Return value: A random number.
627 g_random_int_range (gint32 begin, gint32 end)
630 G_LOCK (global_random);
632 global_random = g_rand_new ();
634 result = g_rand_int_range (global_random, begin, end);
635 G_UNLOCK (global_random);
642 * Returns a random #gdouble equally distributed over the range [0..1).
644 * Return value: A random number.
647 g_random_double (void)
650 G_LOCK (global_random);
652 global_random = g_rand_new ();
654 result = g_rand_double (global_random);
655 G_UNLOCK (global_random);
660 * g_random_double_range:
661 * @begin: lower closed bound of the interval.
662 * @end: upper open bound of the interval.
664 * Returns a random #gdouble equally distributed over the range [@begin..@end).
666 * Return value: A random number.
669 g_random_double_range (gdouble begin, gdouble end)
672 G_LOCK (global_random);
674 global_random = g_rand_new ();
676 result = g_rand_double_range (global_random, begin, end);
677 G_UNLOCK (global_random);
683 * @seed: a value to reinitialize the global random number generator.
685 * Sets the seed for the global random number generator, which is used
686 * by the <function>g_random_*</function> functions, to @seed.
689 g_random_set_seed (guint32 seed)
691 G_LOCK (global_random);
693 global_random = g_rand_new_with_seed (seed);
695 g_rand_set_seed (global_random, seed);
696 G_UNLOCK (global_random);