gmain: fix some silly code in a programmer-error case
[glib.git] / glib / grand.c
bloba70ce7b875d493607c559f531a869ac2c0b37a1a
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/.
36 * MT safe
39 #include "config.h"
41 #include <math.h>
42 #include <errno.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <sys/types.h>
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
50 #include "grand.h"
52 #include "gmain.h"
53 #include "gmem.h"
54 #include "gtestutils.h"
55 #include "gthread.h"
56 #include "gthreadprivate.h"
58 #ifdef G_OS_WIN32
59 #include <process.h> /* For getpid() */
60 #endif
62 /**
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.keio.ac.jp/~matumoto/emt.html">
72 * www.math.keio.ac.jp/~matumoto/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.
83 * games.
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()&percnt;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.
106 * GRand:
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 */
116 #define N 624
117 #define M 397
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)
130 static guint
131 get_random_version (void)
133 static gboolean initialized = FALSE;
134 static guint random_version;
136 if (!initialized)
138 const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
139 if (!version_string || version_string[0] == '\000' ||
140 strcmp (version_string, "2.2") == 0)
141 random_version = 22;
142 else if (strcmp (version_string, "2.0") == 0)
143 random_version = 20;
144 else
146 g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
147 version_string);
148 random_version = 22;
150 initialized = TRUE;
153 return random_version;
156 /* This is called from g_thread_init(). It's used to
157 * initialize some static data in a threadsafe way.
159 void
160 _g_rand_thread_init (void)
162 (void)get_random_version ();
165 struct _GRand
167 guint32 mt[N]; /* the array for the state vector */
168 guint mti;
172 * g_rand_new_with_seed:
173 * @seed: a value to initialize the random number generator.
175 * Creates a new random number generator initialized with @seed.
177 * Return value: the new #GRand.
179 GRand*
180 g_rand_new_with_seed (guint32 seed)
182 GRand *rand = g_new0 (GRand, 1);
183 g_rand_set_seed (rand, seed);
184 return rand;
188 * g_rand_new_with_seed_array:
189 * @seed: an array of seeds to initialize the random number generator.
190 * @seed_length: an array of seeds to initialize the random number generator.
192 * Creates a new random number generator initialized with @seed.
194 * Return value: the new #GRand.
196 * Since: 2.4
198 GRand*
199 g_rand_new_with_seed_array (const guint32 *seed, guint seed_length)
201 GRand *rand = g_new0 (GRand, 1);
202 g_rand_set_seed_array (rand, seed, seed_length);
203 return rand;
207 * g_rand_new:
209 * Creates a new random number generator initialized with a seed taken
210 * either from <filename>/dev/urandom</filename> (if existing) or from
211 * the current time (as a fallback).
213 * Return value: the new #GRand.
215 GRand*
216 g_rand_new (void)
218 guint32 seed[4];
219 GTimeVal now;
220 #ifdef G_OS_UNIX
221 static gboolean dev_urandom_exists = TRUE;
223 if (dev_urandom_exists)
225 FILE* dev_urandom;
229 errno = 0;
230 dev_urandom = fopen("/dev/urandom", "rb");
232 while G_UNLIKELY (errno == EINTR);
234 if (dev_urandom)
236 int r;
238 setvbuf (dev_urandom, NULL, _IONBF, 0);
241 errno = 0;
242 r = fread (seed, sizeof (seed), 1, dev_urandom);
244 while G_UNLIKELY (errno == EINTR);
246 if (r != 1)
247 dev_urandom_exists = FALSE;
249 fclose (dev_urandom);
251 else
252 dev_urandom_exists = FALSE;
254 #else
255 static gboolean dev_urandom_exists = FALSE;
256 #endif
258 if (!dev_urandom_exists)
260 g_get_current_time (&now);
261 seed[0] = now.tv_sec;
262 seed[1] = now.tv_usec;
263 seed[2] = getpid ();
264 #ifdef G_OS_UNIX
265 seed[3] = getppid ();
266 #else
267 seed[3] = 0;
268 #endif
271 return g_rand_new_with_seed_array (seed, 4);
275 * g_rand_free:
276 * @rand_: a #GRand.
278 * Frees the memory allocated for the #GRand.
280 void
281 g_rand_free (GRand* rand)
283 g_return_if_fail (rand != NULL);
285 g_free (rand);
289 * g_rand_copy:
290 * @rand_: a #GRand.
292 * Copies a #GRand into a new one with the same exact state as before.
293 * This way you can take a snapshot of the random number generator for
294 * replaying later.
296 * Return value: the new #GRand.
298 * Since: 2.4
300 GRand *
301 g_rand_copy (GRand* rand)
303 GRand* new_rand;
305 g_return_val_if_fail (rand != NULL, NULL);
307 new_rand = g_new0 (GRand, 1);
308 memcpy (new_rand, rand, sizeof (GRand));
310 return new_rand;
314 * g_rand_set_seed:
315 * @rand_: a #GRand.
316 * @seed: a value to reinitialize the random number generator.
318 * Sets the seed for the random number generator #GRand to @seed.
320 void
321 g_rand_set_seed (GRand* rand, guint32 seed)
323 g_return_if_fail (rand != NULL);
325 switch (get_random_version ())
327 case 20:
328 /* setting initial seeds to mt[N] using */
329 /* the generator Line 25 of Table 1 in */
330 /* [KNUTH 1981, The Art of Computer Programming */
331 /* Vol. 2 (2nd Ed.), pp102] */
333 if (seed == 0) /* This would make the PRNG procude only zeros */
334 seed = 0x6b842128; /* Just set it to another number */
336 rand->mt[0]= seed;
337 for (rand->mti=1; rand->mti<N; rand->mti++)
338 rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
340 break;
341 case 22:
342 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
343 /* In the previous version (see above), MSBs of the */
344 /* seed affect only MSBs of the array mt[]. */
346 rand->mt[0]= seed;
347 for (rand->mti=1; rand->mti<N; rand->mti++)
348 rand->mt[rand->mti] = 1812433253UL *
349 (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti;
350 break;
351 default:
352 g_assert_not_reached ();
357 * g_rand_set_seed_array:
358 * @rand_: a #GRand.
359 * @seed: array to initialize with
360 * @seed_length: length of array
362 * Initializes the random number generator by an array of
363 * longs. Array can be of arbitrary size, though only the
364 * first 624 values are taken. This function is useful
365 * if you have many low entropy seeds, or if you require more then
366 * 32bits of actual entropy for your application.
368 * Since: 2.4
370 void
371 g_rand_set_seed_array (GRand* rand, const guint32 *seed, guint seed_length)
373 int i, j, k;
375 g_return_if_fail (rand != NULL);
376 g_return_if_fail (seed_length >= 1);
378 g_rand_set_seed (rand, 19650218UL);
380 i=1; j=0;
381 k = (N>seed_length ? N : seed_length);
382 for (; k; k--)
384 rand->mt[i] = (rand->mt[i] ^
385 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
386 + seed[j] + j; /* non linear */
387 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
388 i++; j++;
389 if (i>=N)
391 rand->mt[0] = rand->mt[N-1];
392 i=1;
394 if (j>=seed_length)
395 j=0;
397 for (k=N-1; k; k--)
399 rand->mt[i] = (rand->mt[i] ^
400 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
401 - i; /* non linear */
402 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
403 i++;
404 if (i>=N)
406 rand->mt[0] = rand->mt[N-1];
407 i=1;
411 rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
415 * g_rand_boolean:
416 * @rand_: a #GRand.
417 * @Returns: a random #gboolean.
419 * Returns a random #gboolean from @rand_. This corresponds to a
420 * unbiased coin toss.
423 * g_rand_int:
424 * @rand_: a #GRand.
426 * Returns the next random #guint32 from @rand_ equally distributed over
427 * the range [0..2^32-1].
429 * Return value: A random number.
431 guint32
432 g_rand_int (GRand* rand)
434 guint32 y;
435 static const guint32 mag01[2]={0x0, MATRIX_A};
436 /* mag01[x] = x * MATRIX_A for x=0,1 */
438 g_return_val_if_fail (rand != NULL, 0);
440 if (rand->mti >= N) { /* generate N words at one time */
441 int kk;
443 for (kk=0;kk<N-M;kk++) {
444 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
445 rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
447 for (;kk<N-1;kk++) {
448 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
449 rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
451 y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
452 rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
454 rand->mti = 0;
457 y = rand->mt[rand->mti++];
458 y ^= TEMPERING_SHIFT_U(y);
459 y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
460 y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
461 y ^= TEMPERING_SHIFT_L(y);
463 return y;
466 /* transform [0..2^32] -> [0..1] */
467 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
470 * g_rand_int_range:
471 * @rand_: a #GRand.
472 * @begin: lower closed bound of the interval.
473 * @end: upper open bound of the interval.
475 * Returns the next random #gint32 from @rand_ equally distributed over
476 * the range [@begin..@end-1].
478 * Return value: A random number.
480 gint32
481 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
483 guint32 dist = end - begin;
484 guint32 random;
486 g_return_val_if_fail (rand != NULL, begin);
487 g_return_val_if_fail (end > begin, begin);
489 switch (get_random_version ())
491 case 20:
492 if (dist <= 0x10000L) /* 2^16 */
494 /* This method, which only calls g_rand_int once is only good
495 * for (end - begin) <= 2^16, because we only have 32 bits set
496 * from the one call to g_rand_int (). */
498 /* we are using (trans + trans * trans), because g_rand_int only
499 * covers [0..2^32-1] and thus g_rand_int * trans only covers
500 * [0..1-2^-32], but the biggest double < 1 is 1-2^-52.
503 gdouble double_rand = g_rand_int (rand) *
504 (G_RAND_DOUBLE_TRANSFORM +
505 G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
507 random = (gint32) (double_rand * dist);
509 else
511 /* Now we use g_rand_double_range (), which will set 52 bits for
512 us, so that it is safe to round and still get a decent
513 distribution */
514 random = (gint32) g_rand_double_range (rand, 0, dist);
516 break;
517 case 22:
518 if (dist == 0)
519 random = 0;
520 else
522 /* maxvalue is set to the predecessor of the greatest
523 * multiple of dist less or equal 2^32. */
524 guint32 maxvalue;
525 if (dist <= 0x80000000u) /* 2^31 */
527 /* maxvalue = 2^32 - 1 - (2^32 % dist) */
528 guint32 leftover = (0x80000000u % dist) * 2;
529 if (leftover >= dist) leftover -= dist;
530 maxvalue = 0xffffffffu - leftover;
532 else
533 maxvalue = dist - 1;
536 random = g_rand_int (rand);
537 while (random > maxvalue);
539 random %= dist;
541 break;
542 default:
543 random = 0; /* Quiet GCC */
544 g_assert_not_reached ();
547 return begin + random;
551 * g_rand_double:
552 * @rand_: a #GRand.
554 * Returns the next random #gdouble from @rand_ equally distributed over
555 * the range [0..1).
557 * Return value: A random number.
559 gdouble
560 g_rand_double (GRand* rand)
562 /* We set all 52 bits after the point for this, not only the first
563 32. Thats why we need two calls to g_rand_int */
564 gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
565 retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
567 /* The following might happen due to very bad rounding luck, but
568 * actually this should be more than rare, we just try again then */
569 if (retval >= 1.0)
570 return g_rand_double (rand);
572 return retval;
576 * g_rand_double_range:
577 * @rand_: a #GRand.
578 * @begin: lower closed bound of the interval.
579 * @end: upper open bound of the interval.
581 * Returns the next random #gdouble from @rand_ equally distributed over
582 * the range [@begin..@end).
584 * Return value: A random number.
586 gdouble
587 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
589 return g_rand_double (rand) * (end - begin) + begin;
593 * g_random_boolean:
594 * @Returns: a random #gboolean.
596 * Returns a random #gboolean. This corresponds to a unbiased coin toss.
599 * g_random_int:
601 * Return a random #guint32 equally distributed over the range
602 * [0..2^32-1].
604 * Return value: A random number.
606 guint32
607 g_random_int (void)
609 guint32 result;
610 G_LOCK (global_random);
611 if (!global_random)
612 global_random = g_rand_new ();
614 result = g_rand_int (global_random);
615 G_UNLOCK (global_random);
616 return result;
620 * g_random_int_range:
621 * @begin: lower closed bound of the interval.
622 * @end: upper open bound of the interval.
624 * Returns a random #gint32 equally distributed over the range
625 * [@begin..@end-1].
627 * Return value: A random number.
629 gint32
630 g_random_int_range (gint32 begin, gint32 end)
632 gint32 result;
633 G_LOCK (global_random);
634 if (!global_random)
635 global_random = g_rand_new ();
637 result = g_rand_int_range (global_random, begin, end);
638 G_UNLOCK (global_random);
639 return result;
643 * g_random_double:
645 * Returns a random #gdouble equally distributed over the range [0..1).
647 * Return value: A random number.
649 gdouble
650 g_random_double (void)
652 double result;
653 G_LOCK (global_random);
654 if (!global_random)
655 global_random = g_rand_new ();
657 result = g_rand_double (global_random);
658 G_UNLOCK (global_random);
659 return result;
663 * g_random_double_range:
664 * @begin: lower closed bound of the interval.
665 * @end: upper open bound of the interval.
667 * Returns a random #gdouble equally distributed over the range [@begin..@end).
669 * Return value: A random number.
671 gdouble
672 g_random_double_range (gdouble begin, gdouble end)
674 double result;
675 G_LOCK (global_random);
676 if (!global_random)
677 global_random = g_rand_new ();
679 result = g_rand_double_range (global_random, begin, end);
680 G_UNLOCK (global_random);
681 return result;
685 * g_random_set_seed:
686 * @seed: a value to reinitialize the global random number generator.
688 * Sets the seed for the global random number generator, which is used
689 * by the <function>g_random_*</function> functions, to @seed.
691 void
692 g_random_set_seed (guint32 seed)
694 G_LOCK (global_random);
695 if (!global_random)
696 global_random = g_rand_new_with_seed (seed);
697 else
698 g_rand_set_seed (global_random, seed);
699 G_UNLOCK (global_random);