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.keio.ac.jp/~matumoto/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>
49 #include "gthreadinit.h"
51 G_LOCK_DEFINE_STATIC (global_random);
52 static GRand* global_random = NULL;
54 /* Period parameters */
57 #define MATRIX_A 0x9908b0df /* constant vector a */
58 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
59 #define LOWER_MASK 0x7fffffff /* least significant r bits */
61 /* Tempering parameters */
62 #define TEMPERING_MASK_B 0x9d2c5680
63 #define TEMPERING_MASK_C 0xefc60000
64 #define TEMPERING_SHIFT_U(y) (y >> 11)
65 #define TEMPERING_SHIFT_S(y) (y << 7)
66 #define TEMPERING_SHIFT_T(y) (y << 15)
67 #define TEMPERING_SHIFT_L(y) (y >> 18)
70 get_random_version (void)
72 static gboolean initialized = FALSE;
73 static guint random_version;
77 const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
78 if (!version_string || version_string[0] == '\000' ||
79 strcmp (version_string, "2.2") == 0)
81 else if (strcmp (version_string, "2.0") == 0)
85 g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
92 return random_version;
95 /* This is called from g_thread_init(). It's used to
96 * initialize some static data in a threadsafe way.
99 _g_rand_thread_init (void)
101 (void)get_random_version ();
106 guint32 mt[N]; /* the array for the state vector */
111 * g_rand_new_with_seed:
112 * @seed: a value to initialize the random number generator.
114 * Creates a new random number generator initialized with @seed.
116 * Return value: the new #GRand.
119 g_rand_new_with_seed (guint32 seed)
121 GRand *rand = g_new0 (GRand, 1);
122 g_rand_set_seed (rand, seed);
127 * g_rand_new_with_seed_array:
128 * @seed: an array of seeds to initialize the random number generator.
129 * @seed_length: an array of seeds to initialize the random number generator.
131 * Creates a new random number generator initialized with @seed.
133 * Return value: the new #GRand.
136 g_rand_new_with_seed_array (const guint32 *seed, guint seed_length)
138 GRand *rand = g_new0 (GRand, 1);
139 g_rand_set_seed_array (rand, seed, seed_length);
146 * Creates a new random number generator initialized with a seed taken
147 * either from <filename>/dev/urandom</filename> (if existing) or from
148 * the current time (as a fallback).
150 * Return value: the new #GRand.
158 static gboolean dev_urandom_exists = TRUE;
160 if (dev_urandom_exists)
167 dev_urandom = fopen("/dev/urandom", "rb");
169 while G_UNLIKELY (errno == EINTR);
178 r = fread (seed, sizeof (seed), 1, dev_urandom);
180 while G_UNLIKELY (errno == EINTR);
183 dev_urandom_exists = FALSE;
188 fclose (dev_urandom);
190 while G_UNLIKELY (errno == EINTR);
193 dev_urandom_exists = FALSE;
196 static gboolean dev_urandom_exists = FALSE;
199 if (!dev_urandom_exists)
201 g_get_current_time (&now);
202 seed[0] = now.tv_sec;
203 seed[1] = now.tv_usec;
205 seed[3] = getppid ();
208 return g_rand_new_with_seed_array (seed, 4);
215 * Frees the memory allocated for the #GRand.
218 g_rand_free (GRand* rand)
220 g_return_if_fail (rand != NULL);
229 * Copies a #GRand into a new one with the same exact state as before.
230 * This way you can take a snapshot of the random number generator for
233 * Return value: the new #GRand.
236 g_rand_copy (GRand* rand)
240 g_return_val_if_fail (rand != NULL, NULL);
242 new_rand = g_new0 (GRand, 1);
243 memcpy (new_rand, rand, sizeof (GRand));
251 * @seed: a value to reinitialize the random number generator.
253 * Sets the seed for the random number generator #GRand to @seed.
256 g_rand_set_seed (GRand* rand, guint32 seed)
258 g_return_if_fail (rand != NULL);
260 switch (get_random_version ())
263 /* setting initial seeds to mt[N] using */
264 /* the generator Line 25 of Table 1 in */
265 /* [KNUTH 1981, The Art of Computer Programming */
266 /* Vol. 2 (2nd Ed.), pp102] */
268 if (seed == 0) /* This would make the PRNG procude only zeros */
269 seed = 0x6b842128; /* Just set it to another number */
272 for (rand->mti=1; rand->mti<N; rand->mti++)
273 rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
277 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
278 /* In the previous version (see above), MSBs of the */
279 /* seed affect only MSBs of the array mt[]. */
282 for (rand->mti=1; rand->mti<N; rand->mti++)
283 rand->mt[rand->mti] = 1812433253UL *
284 (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti;
287 g_assert_not_reached ();
292 * g_rand_set_seed_array:
294 * @seed: array to initialize with
295 * @seed_length: length of array
297 * Initializes the random number generator by an array of
298 * longs. Array can be of arbitrary size, though only the
299 * first 624 values are taken. This function is useful
300 * if you have many low entropy seeds, or if you require more then
301 * 32bits of actual entropy for your application.
304 g_rand_set_seed_array (GRand* rand, const guint32 *seed, guint seed_length)
308 g_return_if_fail (rand != NULL);
309 g_return_if_fail (seed_length >= 1);
311 g_rand_set_seed (rand, 19650218UL);
314 k = (N>seed_length ? N : seed_length);
317 rand->mt[i] = (rand->mt[i] ^
318 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
319 + seed[j] + j; /* non linear */
320 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
324 rand->mt[0] = rand->mt[N-1];
332 rand->mt[i] = (rand->mt[i] ^
333 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
334 - i; /* non linear */
335 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
339 rand->mt[0] = rand->mt[N-1];
344 rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
351 * Returns the next random #guint32 from @rand_ equally distributed over
352 * the range [0..2^32-1].
354 * Return value: A random number.
357 g_rand_int (GRand* rand)
360 static const guint32 mag01[2]={0x0, MATRIX_A};
361 /* mag01[x] = x * MATRIX_A for x=0,1 */
363 g_return_val_if_fail (rand != NULL, 0);
365 if (rand->mti >= N) { /* generate N words at one time */
368 for (kk=0;kk<N-M;kk++) {
369 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
370 rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
373 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
374 rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
376 y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
377 rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
382 y = rand->mt[rand->mti++];
383 y ^= TEMPERING_SHIFT_U(y);
384 y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
385 y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
386 y ^= TEMPERING_SHIFT_L(y);
391 /* transform [0..2^32] -> [0..1] */
392 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
397 * @begin: lower closed bound of the interval.
398 * @end: upper open bound of the interval.
400 * Returns the next random #gint32 from @rand_ equally distributed over
401 * the range [@begin..@end-1].
403 * Return value: A random number.
406 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
408 guint32 dist = end - begin;
411 g_return_val_if_fail (rand != NULL, begin);
412 g_return_val_if_fail (end > begin, begin);
414 switch (get_random_version ())
417 if (dist <= 0x10000L) /* 2^16 */
419 /* This method, which only calls g_rand_int once is only good
420 * for (end - begin) <= 2^16, because we only have 32 bits set
421 * from the one call to g_rand_int (). */
423 /* we are using (trans + trans * trans), because g_rand_int only
424 * covers [0..2^32-1] and thus g_rand_int * trans only covers
425 * [0..1-2^-32], but the biggest double < 1 is 1-2^-52.
428 gdouble double_rand = g_rand_int (rand) *
429 (G_RAND_DOUBLE_TRANSFORM +
430 G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
432 random = (gint32) (double_rand * dist);
436 /* Now we use g_rand_double_range (), which will set 52 bits for
437 us, so that it is safe to round and still get a decent
439 random = (gint32) g_rand_double_range (rand, 0, dist);
447 /* maxvalue is set to the predecessor of the greatest
448 * multiple of dist less or equal 2^32. */
450 if (dist <= 0x80000000u) /* 2^31 */
452 /* maxvalue = 2^32 - 1 - (2^32 % dist) */
453 guint32 leftover = (0x80000000u % dist) * 2;
454 if (leftover >= dist) leftover -= dist;
455 maxvalue = 0xffffffffu - leftover;
461 random = g_rand_int (rand);
462 while (random > maxvalue);
468 random = 0; /* Quiet GCC */
469 g_assert_not_reached ();
472 return begin + random;
479 * Returns the next random #gdouble from @rand_ equally distributed over
482 * Return value: A random number.
485 g_rand_double (GRand* rand)
487 /* We set all 52 bits after the point for this, not only the first
488 32. Thats why we need two calls to g_rand_int */
489 gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
490 retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
492 /* The following might happen due to very bad rounding luck, but
493 * actually this should be more than rare, we just try again then */
495 return g_rand_double (rand);
501 * g_rand_double_range:
503 * @begin: lower closed bound of the interval.
504 * @end: upper open bound of the interval.
506 * Returns the next random #gdouble from @rand_ equally distributed over
507 * the range [@begin..@end).
509 * Return value: A random number.
512 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
514 return g_rand_double (rand) * (end - begin) + begin;
520 * Return a random #guint32 equally distributed over the range
523 * Return value: A random number.
529 G_LOCK (global_random);
531 global_random = g_rand_new ();
533 result = g_rand_int (global_random);
534 G_UNLOCK (global_random);
539 * g_random_int_range:
540 * @begin: lower closed bound of the interval.
541 * @end: upper open bound of the interval.
543 * Returns a random #gint32 equally distributed over the range
546 * Return value: A random number.
549 g_random_int_range (gint32 begin, gint32 end)
552 G_LOCK (global_random);
554 global_random = g_rand_new ();
556 result = g_rand_int_range (global_random, begin, end);
557 G_UNLOCK (global_random);
564 * Returns a random #gdouble equally distributed over the range [0..1).
566 * Return value: A random number.
569 g_random_double (void)
572 G_LOCK (global_random);
574 global_random = g_rand_new ();
576 result = g_rand_double (global_random);
577 G_UNLOCK (global_random);
582 * g_random_double_range:
583 * @begin: lower closed bound of the interval.
584 * @end: upper open bound of the interval.
586 * Returns a random #gdouble equally distributed over the range [@begin..@end).
588 * Return value: A random number.
591 g_random_double_range (gdouble begin, gdouble end)
594 G_LOCK (global_random);
596 global_random = g_rand_new ();
598 result = g_rand_double_range (global_random, begin, end);
599 G_UNLOCK (global_random);
605 * @seed: a value to reinitialize the global random number generator.
607 * Sets the seed for the global random number generator, which is used
608 * by the <function>g_random_*</function> functions, to @seed.
611 g_random_set_seed (guint32 seed)
613 G_LOCK (global_random);
615 global_random = g_rand_new_with_seed (seed);
617 g_rand_set_seed (global_random, seed);
618 G_UNLOCK (global_random);