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 <wilhelmi@ira.uka.de>.
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/.
47 G_LOCK_DEFINE_STATIC (global_random);
48 static GRand* global_random = NULL;
50 /* Period parameters */
53 #define MATRIX_A 0x9908b0df /* constant vector a */
54 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
55 #define LOWER_MASK 0x7fffffff /* least significant r bits */
57 /* Tempering parameters */
58 #define TEMPERING_MASK_B 0x9d2c5680
59 #define TEMPERING_MASK_C 0xefc60000
60 #define TEMPERING_SHIFT_U(y) (y >> 11)
61 #define TEMPERING_SHIFT_S(y) (y << 7)
62 #define TEMPERING_SHIFT_T(y) (y << 15)
63 #define TEMPERING_SHIFT_L(y) (y >> 18)
66 get_random_version (void)
68 static gboolean initialized = FALSE;
69 static guint random_version;
73 const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
74 if (!version_string || version_string[0] == '\000' ||
75 strcmp (version_string, "2.2") == 0)
77 else if (strcmp (version_string, "2.0") == 0)
81 g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
88 return random_version;
91 /* This is called from g_thread_init(). It's used to
92 * initialize some static data in a threadsafe way.
97 (void)get_random_version ();
102 guint32 mt[N]; /* the array for the state vector */
107 * g_rand_new_with_seed:
108 * @seed: a value to initialize the random number generator.
110 * Creates a new random number generator initialized with @seed.
112 * Return value: the new #GRand.
115 g_rand_new_with_seed (guint32 seed)
117 GRand *rand = g_new0 (GRand, 1);
118 g_rand_set_seed (rand, seed);
125 * Creates a new random number generator initialized with a seed taken
126 * either from <filename>/dev/urandom</filename> (if existing) or from
127 * the current time (as a fallback).
129 * Return value: the new #GRand.
137 static gboolean dev_urandom_exists = TRUE;
139 if (dev_urandom_exists)
141 FILE* dev_urandom = fopen("/dev/urandom", "rb");
144 if (fread (&seed, sizeof (seed), 1, dev_urandom) != 1)
145 dev_urandom_exists = FALSE;
146 fclose (dev_urandom);
149 dev_urandom_exists = FALSE;
152 static gboolean dev_urandom_exists = FALSE;
155 if (!dev_urandom_exists)
157 g_get_current_time (&now);
158 seed = now.tv_sec ^ now.tv_usec;
161 return g_rand_new_with_seed (seed);
168 * Frees the memory allocated for the #GRand.
171 g_rand_free (GRand* rand)
173 g_return_if_fail (rand != NULL);
181 * @seed: a value to reinitialize the random number generator.
183 * Sets the seed for the random number generator #GRand to @seed.
186 g_rand_set_seed (GRand* rand, guint32 seed)
188 g_return_if_fail (rand != NULL);
190 switch (get_random_version ())
193 /* setting initial seeds to mt[N] using */
194 /* the generator Line 25 of Table 1 in */
195 /* [KNUTH 1981, The Art of Computer Programming */
196 /* Vol. 2 (2nd Ed.), pp102] */
198 if (seed == 0) /* This would make the PRNG procude only zeros */
199 seed = 0x6b842128; /* Just set it to another number */
202 for (rand->mti=1; rand->mti<N; rand->mti++)
203 rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
207 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
208 /* In the previous version (see above), MSBs of the */
209 /* seed affect only MSBs of the array mt[]. */
212 for (rand->mti=1; rand->mti<N; rand->mti++)
213 rand->mt[rand->mti] = 1812433253UL *
214 (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti;
217 g_assert_not_reached ();
225 * Returns the next random #guint32 from @rand_ equally distributed over
226 * the range [0..2^32-1].
228 * Return value: A random number.
231 g_rand_int (GRand* rand)
234 static const guint32 mag01[2]={0x0, MATRIX_A};
235 /* mag01[x] = x * MATRIX_A for x=0,1 */
237 g_return_val_if_fail (rand != NULL, 0);
239 if (rand->mti >= N) { /* generate N words at one time */
242 for (kk=0;kk<N-M;kk++) {
243 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
244 rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
247 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
248 rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
250 y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
251 rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
256 y = rand->mt[rand->mti++];
257 y ^= TEMPERING_SHIFT_U(y);
258 y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
259 y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
260 y ^= TEMPERING_SHIFT_L(y);
265 /* transform [0..2^32] -> [0..1] */
266 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
271 * @begin: lower closed bound of the interval.
272 * @end: upper open bound of the interval.
274 * Returns the next random #gint32 from @rand_ equally distributed over
275 * the range [@begin..@end-1].
277 * Return value: A random number.
280 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
282 guint32 dist = end - begin;
285 g_return_val_if_fail (rand != NULL, begin);
286 g_return_val_if_fail (end > begin, begin);
288 /* All tricks doing modulo calculations do not have a perfect
289 * distribution -> We must use the slower way through gdouble for
290 * maximal quality. */
292 if (dist <= 0x10000L) /* 2^16 */
294 /* This method, which only calls g_rand_int once is only good
295 * for (end - begin) <= 2^16, because we only have 32 bits set
296 * from the one call to g_rand_int (). */
298 /* we are using (trans + trans * trans), because g_rand_int only
299 * covers [0..2^32-1] and thus g_rand_int * trans only covers
300 * [0..1-2^-32], but the biggest double < 1 is 1-2^-52.
303 gdouble double_rand = g_rand_int (rand) *
304 (G_RAND_DOUBLE_TRANSFORM +
305 G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
307 random = (gint32) (double_rand * dist);
311 /* Now we use g_rand_double_range (), which will set 52 bits for
312 us, so that it is safe to round and still get a decent
314 random = (gint32) g_rand_double_range (rand, 0, dist);
317 return begin + random;
324 * Returns the next random #gdouble from @rand_ equally distributed over
327 * Return value: A random number.
330 g_rand_double (GRand* rand)
332 /* We set all 52 bits after the point for this, not only the first
333 32. Thats why we need two calls to g_rand_int */
334 gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
335 retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
337 /* The following might happen due to very bad rounding luck, but
338 * actually this should be more than rare, we just try again then */
340 return g_rand_double (rand);
346 * g_rand_double_range:
348 * @begin: lower closed bound of the interval.
349 * @end: upper open bound of the interval.
351 * Returns the next random #gdouble from @rand_ equally distributed over
352 * the range [@begin..@end).
354 * Return value: A random number.
357 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
359 return g_rand_double (rand) * (end - begin) + begin;
365 * Return a random #guint32 equally distributed over the range
368 * Return value: A random number.
374 G_LOCK (global_random);
376 global_random = g_rand_new ();
378 result = g_rand_int (global_random);
379 G_UNLOCK (global_random);
384 * g_random_int_range:
385 * @begin: lower closed bound of the interval.
386 * @end: upper open bound of the interval.
388 * Returns a random #gint32 equally distributed over the range
391 * Return value: A random number.
394 g_random_int_range (gint32 begin, gint32 end)
397 G_LOCK (global_random);
399 global_random = g_rand_new ();
401 result = g_rand_int_range (global_random, begin, end);
402 G_UNLOCK (global_random);
409 * Returns a random #gdouble equally distributed over the range [0..1).
411 * Return value: A random number.
414 g_random_double (void)
417 G_LOCK (global_random);
419 global_random = g_rand_new ();
421 result = g_rand_double (global_random);
422 G_UNLOCK (global_random);
427 * g_random_double_range:
428 * @begin: lower closed bound of the interval.
429 * @end: upper open bound of the interval.
431 * Returns a random #gdouble equally distributed over the range [@begin..@end).
433 * Return value: A random number.
436 g_random_double_range (gdouble begin, gdouble end)
439 G_LOCK (global_random);
441 global_random = g_rand_new ();
443 result = g_rand_double_range (global_random, begin, end);
444 G_UNLOCK (global_random);
450 * @seed: a value to reinitialize the global random number generator.
452 * Sets the seed for the global random number generator, which is used
453 * by the <function>g_random_*</function> functions, to @seed.
456 g_random_set_seed (guint32 seed)
458 G_LOCK (global_random);
460 global_random = g_rand_new_with_seed (seed);
462 g_rand_set_seed (global_random, seed);
463 G_UNLOCK (global_random);