Updated FSF's address
[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  * <warning><para>Do not use this API for cryptographic purposes such as key
70  * generation, nonces, salts or one-time pads.</para></warning>
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
86  * <function>g_random_*</function> functions, which will create a
87  * globally used #GRand and use the according
88  * <function>g_rand_*</function> functions internally. Whenever you
89  * need a stream of reproducible random numbers, you better create a
90  * #GRand yourself and use the <function>g_rand_*</function> functions
91  * directly, which will also be slightly faster. Initializing a #GRand
92  * with a certain seed will produce exactly the same series of random
93  * numbers on all platforms. This can thus be used as a seed for e.g.
94  * games.
95  *
96  * The <function>g_rand*_range</function> functions will return high
97  * quality equally distributed random numbers, whereas for example the
98  * <literal>(g_random_int()&percnt;max)</literal> approach often
99  * doesn't yield equally distributed numbers.
100  *
101  * GLib changed the seeding algorithm for the pseudo-random number
102  * generator Mersenne Twister, as used by #GRand and #GRandom.
103  * This was necessary, because some seeds would yield very bad
104  * pseudo-random streams. Also the pseudo-random integers generated by
105  * <function>g_rand*_int_range()</function> will have a slightly better
106  * equal distribution with the new version of GLib.
107  *
108  * The original seeding and generation algorithms, as found in GLib
109  * 2.0.x, can be used instead of the new ones by setting the
110  * environment variable <envar>G_RANDOM_VERSION</envar> to the value of
111  * '2.0'. Use the GLib-2.0 algorithms only if you have sequences of
112  * numbers generated with Glib-2.0 that you need to reproduce exactly.
113  **/
114
115 /**
116  * GRand:
117  *
118  * The #GRand struct is an opaque data structure. It should only be
119  * accessed through the <function>g_rand_*</function> functions.
120  **/
121
122 G_LOCK_DEFINE_STATIC (global_random);
123
124 /* Period parameters */  
125 #define N 624
126 #define M 397
127 #define MATRIX_A 0x9908b0df   /* constant vector a */
128 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
129 #define LOWER_MASK 0x7fffffff /* least significant r bits */
130
131 /* Tempering parameters */   
132 #define TEMPERING_MASK_B 0x9d2c5680
133 #define TEMPERING_MASK_C 0xefc60000
134 #define TEMPERING_SHIFT_U(y)  (y >> 11)
135 #define TEMPERING_SHIFT_S(y)  (y << 7)
136 #define TEMPERING_SHIFT_T(y)  (y << 15)
137 #define TEMPERING_SHIFT_L(y)  (y >> 18)
138
139 static guint
140 get_random_version (void)
141 {
142   static gsize initialized = FALSE;
143   static guint random_version;
144
145   if (g_once_init_enter (&initialized))
146     {
147       const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
148       if (!version_string || version_string[0] == '\000' || 
149           strcmp (version_string, "2.2") == 0)
150         random_version = 22;
151       else if (strcmp (version_string, "2.0") == 0)
152         random_version = 20;
153       else
154         {
155           g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
156                      version_string);
157           random_version = 22;
158         }
159       g_once_init_leave (&initialized, TRUE);
160     }
161   
162   return random_version;
163 }
164
165 struct _GRand
166 {
167   guint32 mt[N]; /* the array for the state vector  */
168   guint mti; 
169 };
170
171 /**
172  * g_rand_new_with_seed:
173  * @seed: a value to initialize the random number generator.
174  * 
175  * Creates a new random number generator initialized with @seed.
176  * 
177  * Return value: the new #GRand.
178  **/
179 GRand*
180 g_rand_new_with_seed (guint32 seed)
181 {
182   GRand *rand = g_new0 (GRand, 1);
183   g_rand_set_seed (rand, seed);
184   return rand;
185 }
186
187 /**
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.
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, guint seed_length)
200 {
201   GRand *rand = g_new0 (GRand, 1);
202   g_rand_set_seed_array (rand, seed, seed_length);
203   return rand;
204 }
205
206 /**
207  * g_rand_new:
208  * 
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).  On Windows, the seed is taken from
212  * rand_s().
213  * 
214  * Return value: the new #GRand.
215  **/
216 GRand* 
217 g_rand_new (void)
218 {
219   guint32 seed[4];
220 #ifdef G_OS_UNIX
221   static gboolean dev_urandom_exists = TRUE;
222   GTimeVal now;
223
224   if (dev_urandom_exists)
225     {
226       FILE* dev_urandom;
227
228       do
229         {
230           dev_urandom = fopen("/dev/urandom", "rb");
231         }
232       while G_UNLIKELY (dev_urandom == NULL && errno == EINTR);
233
234       if (dev_urandom)
235         {
236           int r;
237
238           setvbuf (dev_urandom, NULL, _IONBF, 0);
239           do
240             {
241               errno = 0;
242               r = fread (seed, sizeof (seed), 1, dev_urandom);
243             }
244           while G_UNLIKELY (errno == EINTR);
245
246           if (r != 1)
247             dev_urandom_exists = FALSE;
248
249           fclose (dev_urandom);
250         }       
251       else
252         dev_urandom_exists = FALSE;
253     }
254
255   if (!dev_urandom_exists)
256     {  
257       g_get_current_time (&now);
258       seed[0] = now.tv_sec;
259       seed[1] = now.tv_usec;
260       seed[2] = getpid ();
261       seed[3] = getppid ();
262     }
263 #else /* G_OS_WIN32 */
264   gint i;
265
266   for (i = 0; i < G_N_ELEMENTS (seed); i++)
267     rand_s (&seed[i]);
268 #endif
269
270   return g_rand_new_with_seed_array (seed, 4);
271 }
272
273 /**
274  * g_rand_free:
275  * @rand_: a #GRand.
276  *
277  * Frees the memory allocated for the #GRand.
278  **/
279 void
280 g_rand_free (GRand* rand)
281 {
282   g_return_if_fail (rand != NULL);
283
284   g_free (rand);
285 }
286
287 /**
288  * g_rand_copy:
289  * @rand_: a #GRand.
290  *
291  * Copies a #GRand into a new one with the same exact state as before.
292  * This way you can take a snapshot of the random number generator for
293  * replaying later.
294  *
295  * Return value: the new #GRand.
296  *
297  * Since: 2.4
298  **/
299 GRand *
300 g_rand_copy (GRand* rand)
301 {
302   GRand* new_rand;
303
304   g_return_val_if_fail (rand != NULL, NULL);
305
306   new_rand = g_new0 (GRand, 1);
307   memcpy (new_rand, rand, sizeof (GRand));
308
309   return new_rand;
310 }
311
312 /**
313  * g_rand_set_seed:
314  * @rand_: a #GRand.
315  * @seed: a value to reinitialize the random number generator.
316  *
317  * Sets the seed for the random number generator #GRand to @seed.
318  **/
319 void
320 g_rand_set_seed (GRand* rand, guint32 seed)
321 {
322   g_return_if_fail (rand != NULL);
323
324   switch (get_random_version ())
325     {
326     case 20:
327       /* setting initial seeds to mt[N] using         */
328       /* the generator Line 25 of Table 1 in          */
329       /* [KNUTH 1981, The Art of Computer Programming */
330       /*    Vol. 2 (2nd Ed.), pp102]                  */
331       
332       if (seed == 0) /* This would make the PRNG produce only zeros */
333         seed = 0x6b842128; /* Just set it to another number */
334       
335       rand->mt[0]= seed;
336       for (rand->mti=1; rand->mti<N; rand->mti++)
337         rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
338       
339       break;
340     case 22:
341       /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
342       /* In the previous version (see above), MSBs of the    */
343       /* seed affect only MSBs of the array mt[].            */
344       
345       rand->mt[0]= seed;
346       for (rand->mti=1; rand->mti<N; rand->mti++)
347         rand->mt[rand->mti] = 1812433253UL * 
348           (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti; 
349       break;
350     default:
351       g_assert_not_reached ();
352     }
353 }
354
355 /**
356  * g_rand_set_seed_array:
357  * @rand_: a #GRand.
358  * @seed: array to initialize with
359  * @seed_length: length of array
360  *
361  * Initializes the random number generator by an array of
362  * longs.  Array can be of arbitrary size, though only the
363  * first 624 values are taken.  This function is useful
364  * if you have many low entropy seeds, or if you require more then
365  * 32bits of actual entropy for your application.
366  *
367  * Since: 2.4
368  **/
369 void
370 g_rand_set_seed_array (GRand* rand, const guint32 *seed, guint seed_length)
371 {
372   int i, j, k;
373
374   g_return_if_fail (rand != NULL);
375   g_return_if_fail (seed_length >= 1);
376
377   g_rand_set_seed (rand, 19650218UL);
378
379   i=1; j=0;
380   k = (N>seed_length ? N : seed_length);
381   for (; k; k--)
382     {
383       rand->mt[i] = (rand->mt[i] ^
384                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
385               + seed[j] + j; /* non linear */
386       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
387       i++; j++;
388       if (i>=N)
389         {
390           rand->mt[0] = rand->mt[N-1];
391           i=1;
392         }
393       if (j>=seed_length)
394         j=0;
395     }
396   for (k=N-1; k; k--)
397     {
398       rand->mt[i] = (rand->mt[i] ^
399                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
400               - i; /* non linear */
401       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
402       i++;
403       if (i>=N)
404         {
405           rand->mt[0] = rand->mt[N-1];
406           i=1;
407         }
408     }
409
410   rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
411 }
412
413 /**
414  * g_rand_boolean:
415  * @rand_: a #GRand.
416  *
417  * Returns a random #gboolean from @rand_. This corresponds to a
418  * unbiased coin toss.
419  *
420  * Returns: a random #gboolean.
421  **/
422 /**
423  * g_rand_int:
424  * @rand_: a #GRand.
425  *
426  * Returns the next random #guint32 from @rand_ equally distributed over
427  * the range [0..2^32-1].
428  *
429  * Return value: A random number.
430  **/
431 guint32
432 g_rand_int (GRand* rand)
433 {
434   guint32 y;
435   static const guint32 mag01[2]={0x0, MATRIX_A};
436   /* mag01[x] = x * MATRIX_A  for x=0,1 */
437
438   g_return_val_if_fail (rand != NULL, 0);
439
440   if (rand->mti >= N) { /* generate N words at one time */
441     int kk;
442     
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];
446     }
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];
450     }
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];
453     
454     rand->mti = 0;
455   }
456   
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);
462   
463   return y; 
464 }
465
466 /* transform [0..2^32] -> [0..1] */
467 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
468
469 /**
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.
474  *
475  * Returns the next random #gint32 from @rand_ equally distributed over
476  * the range [@begin..@end-1].
477  *
478  * Return value: A random number.
479  **/
480 gint32 
481 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
482 {
483   guint32 dist = end - begin;
484   guint32 random;
485
486   g_return_val_if_fail (rand != NULL, begin);
487   g_return_val_if_fail (end > begin, begin);
488
489   switch (get_random_version ())
490     {
491     case 20:
492       if (dist <= 0x10000L) /* 2^16 */
493         {
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 (). */
497           
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. 
501            */
502           
503           gdouble double_rand = g_rand_int (rand) * 
504             (G_RAND_DOUBLE_TRANSFORM +
505              G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
506           
507           random = (gint32) (double_rand * dist);
508         }
509       else
510         {
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);
515         }
516       break;
517     case 22:
518       if (dist == 0)
519         random = 0;
520       else 
521         {
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 */
526             {
527               /* maxvalue = 2^32 - 1 - (2^32 % dist) */
528               guint32 leftover = (0x80000000u % dist) * 2;
529               if (leftover >= dist) leftover -= dist;
530               maxvalue = 0xffffffffu - leftover;
531             }
532           else
533             maxvalue = dist - 1;
534           
535           do
536             random = g_rand_int (rand);
537           while (random > maxvalue);
538           
539           random %= dist;
540         }
541       break;
542     default:
543       random = 0;               /* Quiet GCC */
544       g_assert_not_reached ();
545     }      
546  
547   return begin + random;
548 }
549
550 /**
551  * g_rand_double:
552  * @rand_: a #GRand.
553  *
554  * Returns the next random #gdouble from @rand_ equally distributed over
555  * the range [0..1).
556  *
557  * Return value: A random number.
558  **/
559 gdouble 
560 g_rand_double (GRand* rand)
561 {    
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;
566
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);
571
572   return retval;
573 }
574
575 /**
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.
580  *
581  * Returns the next random #gdouble from @rand_ equally distributed over
582  * the range [@begin..@end).
583  *
584  * Return value: A random number.
585  **/
586 gdouble 
587 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
588 {
589   gdouble r;
590
591   r = g_rand_double (rand);
592
593   return r * end - (r - 1) * begin;
594 }
595
596 static GRand *
597 get_global_random (void)
598 {
599   static GRand *global_random;
600
601   /* called while locked */
602   if (!global_random)
603     global_random = g_rand_new ();
604
605   return global_random;
606 }
607
608 /**
609  * g_random_boolean:
610  *
611  * Returns a random #gboolean. This corresponds to a unbiased coin toss.
612  *
613  * Returns: a random #gboolean.
614  **/
615 /**
616  * g_random_int:
617  *
618  * Return a random #guint32 equally distributed over the range
619  * [0..2^32-1].
620  *
621  * Return value: A random number.
622  **/
623 guint32
624 g_random_int (void)
625 {
626   guint32 result;
627   G_LOCK (global_random);
628   result = g_rand_int (get_global_random ());
629   G_UNLOCK (global_random);
630   return result;
631 }
632
633 /**
634  * g_random_int_range:
635  * @begin: lower closed bound of the interval.
636  * @end: upper open bound of the interval.
637  *
638  * Returns a random #gint32 equally distributed over the range
639  * [@begin..@end-1].
640  *
641  * Return value: A random number.
642  **/
643 gint32 
644 g_random_int_range (gint32 begin, gint32 end)
645 {
646   gint32 result;
647   G_LOCK (global_random);
648   result = g_rand_int_range (get_global_random (), begin, end);
649   G_UNLOCK (global_random);
650   return result;
651 }
652
653 /**
654  * g_random_double:
655  *
656  * Returns a random #gdouble equally distributed over the range [0..1).
657  *
658  * Return value: A random number.
659  **/
660 gdouble 
661 g_random_double (void)
662 {
663   double result;
664   G_LOCK (global_random);
665   result = g_rand_double (get_global_random ());
666   G_UNLOCK (global_random);
667   return result;
668 }
669
670 /**
671  * g_random_double_range:
672  * @begin: lower closed bound of the interval.
673  * @end: upper open bound of the interval.
674  *
675  * Returns a random #gdouble equally distributed over the range [@begin..@end).
676  *
677  * Return value: A random number.
678  **/
679 gdouble 
680 g_random_double_range (gdouble begin, gdouble end)
681 {
682   double result;
683   G_LOCK (global_random);
684   result = g_rand_double_range (get_global_random (), begin, end);
685   G_UNLOCK (global_random);
686   return result;
687 }
688
689 /**
690  * g_random_set_seed:
691  * @seed: a value to reinitialize the global random number generator.
692  * 
693  * Sets the seed for the global random number generator, which is used
694  * by the <function>g_random_*</function> functions, to @seed.
695  **/
696 void
697 g_random_set_seed (guint32 seed)
698 {
699   G_LOCK (global_random);
700   g_rand_set_seed (get_global_random (), seed);
701   G_UNLOCK (global_random);
702 }