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