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