Don't use <envar> in docs
[platform/upstream/glib.git] / glib / grand.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
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.
8  *
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.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /* Originally developed and coded by Makoto Matsumoto and Takuji
19  * Nishimura.  Please mail <matumoto@math.keio.ac.jp>, if you're using
20  * code from this file in your own programs or libraries.
21  * Further information on the Mersenne Twister can be found at
22  * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
23  * This code was adapted to glib by Sebastian Wilhelmi.
24  */
25
26 /*
27  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
28  * file for a list of people on the GLib Team.  See the ChangeLog
29  * files for a list of changes.  These files are distributed with
30  * GLib at ftp://ftp.gtk.org/pub/gtk/.
31  */
32
33 /*
34  * MT safe
35  */
36
37 #include "config.h"
38 #define _CRT_RAND_S
39
40 #include <math.h>
41 #include <errno.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <sys/types.h>
45 #include "grand.h"
46
47 #include "genviron.h"
48 #include "gmain.h"
49 #include "gmem.h"
50 #include "gtestutils.h"
51 #include "gthread.h"
52
53 #ifdef G_OS_UNIX
54 #include <unistd.h>
55 #endif
56
57 #ifdef G_OS_WIN32
58 #include <stdlib.h>
59 #endif
60
61 /**
62  * SECTION:random_numbers
63  * @title: Random Numbers
64  * @short_description: pseudo-random number generator
65  *
66  * The following functions allow you to use a portable, fast and good
67  * pseudo-random number generator (PRNG).
68  * 
69  * Do not use this API for cryptographic purposes such as key
70  * generation, nonces, salts or one-time pads.
71  *
72  * This PRNG is suitable for non-cryptographic use such as in games
73  * (shuffling a card deck, generating levels), generating data for a
74  * test suite, etc. If you need random data for cryptographic
75  * purposes, it is recommended to use platform-specific APIs such as
76  * <literal>/dev/random</literal> on Unix, or CryptGenRandom() on
77  * Windows.
78  *
79  * GRand uses the Mersenne Twister PRNG, which was originally
80  * developed by Makoto Matsumoto and Takuji Nishimura. Further
81  * information can be found at <ulink
82  * url="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html">
83  * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</ulink>.
84  *
85  * If you just need a random number, you simply call the g_random_*
86  * functions, which will create a globally used #GRand and use the
87  * according g_rand_* functions internally. Whenever you need a
88  * stream of reproducible random numbers, you better create a
89  * #GRand yourself and use the g_rand_* functions directly, which
90  * will also be slightly faster. Initializing a #GRand with a
91  * certain seed will produce exactly the same series of random
92  * numbers on all platforms. This can thus be used as a seed for
93  * e.g. games.
94  *
95  * The g_rand*_range functions will return high quality equally
96  * distributed random numbers, whereas for example the
97  * <literal>(g_random_int()&percnt;max)</literal> approach often
98  * doesn't yield equally distributed numbers.
99  *
100  * GLib changed the seeding algorithm for the pseudo-random number
101  * generator Mersenne Twister, as used by #GRand. This was necessary,
102  * because some seeds would yield very bad pseudo-random streams.
103  * Also the pseudo-random integers generated by g_rand*_int_range()
104  * will have a slightly better equal distribution with the new
105  * version of GLib.
106  *
107  * The original seeding and generation algorithms, as found in
108  * GLib 2.0.x, can be used instead of the new ones by setting the
109  * environment variable `G_RANDOM_VERSION` to the value of '2.0'.
110  * Use the GLib-2.0 algorithms only if you have sequences of numbers
111  * generated with Glib-2.0 that you need to reproduce exactly.
112  */
113
114 /**
115  * GRand:
116  *
117  * The GRand struct is an opaque data structure. It should only be
118  * accessed through the g_rand_* functions.
119  **/
120
121 G_LOCK_DEFINE_STATIC (global_random);
122
123 /* Period parameters */  
124 #define N 624
125 #define M 397
126 #define MATRIX_A 0x9908b0df   /* constant vector a */
127 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
128 #define LOWER_MASK 0x7fffffff /* least significant r bits */
129
130 /* Tempering parameters */   
131 #define TEMPERING_MASK_B 0x9d2c5680
132 #define TEMPERING_MASK_C 0xefc60000
133 #define TEMPERING_SHIFT_U(y)  (y >> 11)
134 #define TEMPERING_SHIFT_S(y)  (y << 7)
135 #define TEMPERING_SHIFT_T(y)  (y << 15)
136 #define TEMPERING_SHIFT_L(y)  (y >> 18)
137
138 static guint
139 get_random_version (void)
140 {
141   static gsize initialized = FALSE;
142   static guint random_version;
143
144   if (g_once_init_enter (&initialized))
145     {
146       const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
147       if (!version_string || version_string[0] == '\000' || 
148           strcmp (version_string, "2.2") == 0)
149         random_version = 22;
150       else if (strcmp (version_string, "2.0") == 0)
151         random_version = 20;
152       else
153         {
154           g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
155                      version_string);
156           random_version = 22;
157         }
158       g_once_init_leave (&initialized, TRUE);
159     }
160   
161   return random_version;
162 }
163
164 struct _GRand
165 {
166   guint32 mt[N]; /* the array for the state vector  */
167   guint mti; 
168 };
169
170 /**
171  * g_rand_new_with_seed:
172  * @seed: a value to initialize the random number generator
173  * 
174  * Creates a new random number generator initialized with @seed.
175  * 
176  * Return value: the new #GRand
177  **/
178 GRand*
179 g_rand_new_with_seed (guint32 seed)
180 {
181   GRand *rand = g_new0 (GRand, 1);
182   g_rand_set_seed (rand, seed);
183   return rand;
184 }
185
186 /**
187  * g_rand_new_with_seed_array:
188  * @seed: an array of seeds to initialize the random number generator
189  * @seed_length: an array of seeds to initialize the random number
190  *     generator
191  * 
192  * Creates a new random number generator initialized with @seed.
193  * 
194  * Return value: the new #GRand
195  *
196  * Since: 2.4
197  */
198 GRand*
199 g_rand_new_with_seed_array (const guint32 *seed,
200                             guint          seed_length)
201 {
202   GRand *rand = g_new0 (GRand, 1);
203   g_rand_set_seed_array (rand, seed, seed_length);
204   return rand;
205 }
206
207 /**
208  * g_rand_new:
209  * 
210  * Creates a new random number generator initialized with a seed taken
211  * either from <filename>/dev/urandom</filename> (if existing) or from 
212  * the current time (as a fallback).
213  *
214  * On Windows, the seed is taken from rand_s().
215  * 
216  * Return value: the new #GRand
217  */
218 GRand* 
219 g_rand_new (void)
220 {
221   guint32 seed[4];
222 #ifdef G_OS_UNIX
223   static gboolean dev_urandom_exists = TRUE;
224   GTimeVal now;
225
226   if (dev_urandom_exists)
227     {
228       FILE* dev_urandom;
229
230       do
231         {
232           dev_urandom = fopen("/dev/urandom", "rb");
233         }
234       while G_UNLIKELY (dev_urandom == NULL && errno == EINTR);
235
236       if (dev_urandom)
237         {
238           int r;
239
240           setvbuf (dev_urandom, NULL, _IONBF, 0);
241           do
242             {
243               errno = 0;
244               r = fread (seed, sizeof (seed), 1, dev_urandom);
245             }
246           while G_UNLIKELY (errno == EINTR);
247
248           if (r != 1)
249             dev_urandom_exists = FALSE;
250
251           fclose (dev_urandom);
252         }       
253       else
254         dev_urandom_exists = FALSE;
255     }
256
257   if (!dev_urandom_exists)
258     {  
259       g_get_current_time (&now);
260       seed[0] = now.tv_sec;
261       seed[1] = now.tv_usec;
262       seed[2] = getpid ();
263       seed[3] = getppid ();
264     }
265 #else /* G_OS_WIN32 */
266   gint i;
267
268   for (i = 0; i < G_N_ELEMENTS (seed); i++)
269     rand_s (&seed[i]);
270 #endif
271
272   return g_rand_new_with_seed_array (seed, 4);
273 }
274
275 /**
276  * g_rand_free:
277  * @rand_: a #GRand
278  *
279  * Frees the memory allocated for the #GRand.
280  */
281 void
282 g_rand_free (GRand *rand)
283 {
284   g_return_if_fail (rand != NULL);
285
286   g_free (rand);
287 }
288
289 /**
290  * g_rand_copy:
291  * @rand_: a #GRand
292  *
293  * Copies a #GRand into a new one with the same exact state as before.
294  * This way you can take a snapshot of the random number generator for
295  * replaying later.
296  *
297  * Return value: the new #GRand
298  *
299  * Since: 2.4
300  */
301 GRand*
302 g_rand_copy (GRand *rand)
303 {
304   GRand* new_rand;
305
306   g_return_val_if_fail (rand != NULL, NULL);
307
308   new_rand = g_new0 (GRand, 1);
309   memcpy (new_rand, rand, sizeof (GRand));
310
311   return new_rand;
312 }
313
314 /**
315  * g_rand_set_seed:
316  * @rand_: a #GRand
317  * @seed: a value to reinitialize the random number generator
318  *
319  * Sets the seed for the random number generator #GRand to @seed.
320  */
321 void
322 g_rand_set_seed (GRand   *rand,
323                  guint32  seed)
324 {
325   g_return_if_fail (rand != NULL);
326
327   switch (get_random_version ())
328     {
329     case 20:
330       /* setting initial seeds to mt[N] using         */
331       /* the generator Line 25 of Table 1 in          */
332       /* [KNUTH 1981, The Art of Computer Programming */
333       /*    Vol. 2 (2nd Ed.), pp102]                  */
334       
335       if (seed == 0) /* This would make the PRNG produce only zeros */
336         seed = 0x6b842128; /* Just set it to another number */
337       
338       rand->mt[0]= seed;
339       for (rand->mti=1; rand->mti<N; rand->mti++)
340         rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
341       
342       break;
343     case 22:
344       /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
345       /* In the previous version (see above), MSBs of the    */
346       /* seed affect only MSBs of the array mt[].            */
347       
348       rand->mt[0]= seed;
349       for (rand->mti=1; rand->mti<N; rand->mti++)
350         rand->mt[rand->mti] = 1812433253UL * 
351           (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti; 
352       break;
353     default:
354       g_assert_not_reached ();
355     }
356 }
357
358 /**
359  * g_rand_set_seed_array:
360  * @rand_: a #GRand
361  * @seed: array to initialize with
362  * @seed_length: length of array
363  *
364  * Initializes the random number generator by an array of longs.
365  * Array can be of arbitrary size, though only the first 624 values
366  * are taken.  This function is useful if you have many low entropy
367  * seeds, or if you require more then 32 bits of actual entropy for
368  * your application.
369  *
370  * Since: 2.4
371  */
372 void
373 g_rand_set_seed_array (GRand         *rand,
374                        const guint32 *seed,
375                        guint          seed_length)
376 {
377   int i, j, k;
378
379   g_return_if_fail (rand != NULL);
380   g_return_if_fail (seed_length >= 1);
381
382   g_rand_set_seed (rand, 19650218UL);
383
384   i=1; j=0;
385   k = (N>seed_length ? N : seed_length);
386   for (; k; k--)
387     {
388       rand->mt[i] = (rand->mt[i] ^
389                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
390               + seed[j] + j; /* non linear */
391       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
392       i++; j++;
393       if (i>=N)
394         {
395           rand->mt[0] = rand->mt[N-1];
396           i=1;
397         }
398       if (j>=seed_length)
399         j=0;
400     }
401   for (k=N-1; k; k--)
402     {
403       rand->mt[i] = (rand->mt[i] ^
404                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
405               - i; /* non linear */
406       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
407       i++;
408       if (i>=N)
409         {
410           rand->mt[0] = rand->mt[N-1];
411           i=1;
412         }
413     }
414
415   rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
416 }
417
418 /**
419  * g_rand_boolean:
420  * @rand_: a #GRand
421  *
422  * Returns a random #gboolean from @rand_.
423  * This corresponds to a unbiased coin toss.
424  *
425  * Returns: a random #gboolean
426  */
427 /**
428  * g_rand_int:
429  * @rand_: a #GRand
430  *
431  * Returns the next random #guint32 from @rand_ equally distributed over
432  * the range [0..2^32-1].
433  *
434  * Return value: a random number
435  */
436 guint32
437 g_rand_int (GRand *rand)
438 {
439   guint32 y;
440   static const guint32 mag01[2]={0x0, MATRIX_A};
441   /* mag01[x] = x * MATRIX_A  for x=0,1 */
442
443   g_return_val_if_fail (rand != NULL, 0);
444
445   if (rand->mti >= N) { /* generate N words at one time */
446     int kk;
447     
448     for (kk = 0; kk < N - M; kk++) {
449       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
450       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
451     }
452     for (; kk < N - 1; kk++) {
453       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
454       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
455     }
456     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
457     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
458     
459     rand->mti = 0;
460   }
461   
462   y = rand->mt[rand->mti++];
463   y ^= TEMPERING_SHIFT_U(y);
464   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
465   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
466   y ^= TEMPERING_SHIFT_L(y);
467   
468   return y; 
469 }
470
471 /* transform [0..2^32] -> [0..1] */
472 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
473
474 /**
475  * g_rand_int_range:
476  * @rand_: a #GRand
477  * @begin: lower closed bound of the interval
478  * @end: upper open bound of the interval
479  *
480  * Returns the next random #gint32 from @rand_ equally distributed over
481  * the range [@begin..@end-1].
482  *
483  * Return value: a random number
484  */
485 gint32 
486 g_rand_int_range (GRand  *rand,
487                   gint32  begin,
488                   gint32  end)
489 {
490   guint32 dist = end - begin;
491   guint32 random;
492
493   g_return_val_if_fail (rand != NULL, begin);
494   g_return_val_if_fail (end > begin, begin);
495
496   switch (get_random_version ())
497     {
498     case 20:
499       if (dist <= 0x10000L) /* 2^16 */
500         {
501           /* This method, which only calls g_rand_int once is only good
502            * for (end - begin) <= 2^16, because we only have 32 bits set
503            * from the one call to g_rand_int ().
504            *
505            * We are using (trans + trans * trans), because g_rand_int only
506            * covers [0..2^32-1] and thus g_rand_int * trans only covers
507            * [0..1-2^-32], but the biggest double < 1 is 1-2^-52. 
508            */
509           
510           gdouble double_rand = g_rand_int (rand) * 
511             (G_RAND_DOUBLE_TRANSFORM +
512              G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
513           
514           random = (gint32) (double_rand * dist);
515         }
516       else
517         {
518           /* Now we use g_rand_double_range (), which will set 52 bits
519            * for us, so that it is safe to round and still get a decent
520            * distribution
521            */
522           random = (gint32) g_rand_double_range (rand, 0, dist);
523         }
524       break;
525     case 22:
526       if (dist == 0)
527         random = 0;
528       else 
529         {
530           /* maxvalue is set to the predecessor of the greatest
531            * multiple of dist less or equal 2^32.
532            */
533           guint32 maxvalue;
534           if (dist <= 0x80000000u) /* 2^31 */
535             {
536               /* maxvalue = 2^32 - 1 - (2^32 % dist) */
537               guint32 leftover = (0x80000000u % dist) * 2;
538               if (leftover >= dist) leftover -= dist;
539               maxvalue = 0xffffffffu - leftover;
540             }
541           else
542             maxvalue = dist - 1;
543           
544           do
545             random = g_rand_int (rand);
546           while (random > maxvalue);
547           
548           random %= dist;
549         }
550       break;
551     default:
552       random = 0;               /* Quiet GCC */
553       g_assert_not_reached ();
554     }      
555  
556   return begin + random;
557 }
558
559 /**
560  * g_rand_double:
561  * @rand_: a #GRand
562  *
563  * Returns the next random #gdouble from @rand_ equally distributed over
564  * the range [0..1).
565  *
566  * Return value: a random number
567  */
568 gdouble 
569 g_rand_double (GRand *rand)
570 {    
571   /* We set all 52 bits after the point for this, not only the first
572      32. Thats why we need two calls to g_rand_int */
573   gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
574   retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
575
576   /* The following might happen due to very bad rounding luck, but
577    * actually this should be more than rare, we just try again then */
578   if (retval >= 1.0) 
579     return g_rand_double (rand);
580
581   return retval;
582 }
583
584 /**
585  * g_rand_double_range:
586  * @rand_: a #GRand
587  * @begin: lower closed bound of the interval
588  * @end: upper open bound of the interval
589  *
590  * Returns the next random #gdouble from @rand_ equally distributed over
591  * the range [@begin..@end).
592  *
593  * Return value: a random number
594  */
595 gdouble 
596 g_rand_double_range (GRand   *rand,
597                      gdouble  begin,
598                      gdouble  end)
599 {
600   gdouble r;
601
602   r = g_rand_double (rand);
603
604   return r * end - (r - 1) * begin;
605 }
606
607 static GRand *
608 get_global_random (void)
609 {
610   static GRand *global_random;
611
612   /* called while locked */
613   if (!global_random)
614     global_random = g_rand_new ();
615
616   return global_random;
617 }
618
619 /**
620  * g_random_boolean:
621  *
622  * Returns a random #gboolean.
623  * This corresponds to a unbiased coin toss.
624  *
625  * Returns: a random #gboolean
626  */
627 /**
628  * g_random_int:
629  *
630  * Return a random #guint32 equally distributed over the range
631  * [0..2^32-1].
632  *
633  * Return value: a random number
634  */
635 guint32
636 g_random_int (void)
637 {
638   guint32 result;
639   G_LOCK (global_random);
640   result = g_rand_int (get_global_random ());
641   G_UNLOCK (global_random);
642   return result;
643 }
644
645 /**
646  * g_random_int_range:
647  * @begin: lower closed bound of the interval
648  * @end: upper open bound of the interval
649  *
650  * Returns a random #gint32 equally distributed over the range
651  * [@begin..@end-1].
652  *
653  * Return value: a random number
654  */
655 gint32 
656 g_random_int_range (gint32 begin,
657                     gint32 end)
658 {
659   gint32 result;
660   G_LOCK (global_random);
661   result = g_rand_int_range (get_global_random (), begin, end);
662   G_UNLOCK (global_random);
663   return result;
664 }
665
666 /**
667  * g_random_double:
668  *
669  * Returns a random #gdouble equally distributed over the range [0..1).
670  *
671  * Return value: a random number
672  */
673 gdouble 
674 g_random_double (void)
675 {
676   double result;
677   G_LOCK (global_random);
678   result = g_rand_double (get_global_random ());
679   G_UNLOCK (global_random);
680   return result;
681 }
682
683 /**
684  * g_random_double_range:
685  * @begin: lower closed bound of the interval
686  * @end: upper open bound of the interval
687  *
688  * Returns a random #gdouble equally distributed over the range
689  * [@begin..@end).
690  *
691  * Return value: a random number
692  */
693 gdouble 
694 g_random_double_range (gdouble begin,
695                        gdouble end)
696 {
697   double result;
698   G_LOCK (global_random);
699   result = g_rand_double_range (get_global_random (), begin, end);
700   G_UNLOCK (global_random);
701   return result;
702 }
703
704 /**
705  * g_random_set_seed:
706  * @seed: a value to reinitialize the global random number generator
707  * 
708  * Sets the seed for the global random number generator, which is used
709  * by the g_random_* functions, to @seed.
710  */
711 void
712 g_random_set_seed (guint32 seed)
713 {
714   G_LOCK (global_random);
715   g_rand_set_seed (get_global_random (), seed);
716   G_UNLOCK (global_random);
717 }