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