Docs: don't use the structname 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, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /* Originally developed and coded by Makoto Matsumoto and Takuji
21  * Nishimura.  Please mail <matumoto@math.keio.ac.jp>, if you're using
22  * code from this file in your own programs or libraries.
23  * Further information on the Mersenne Twister can be found at
24  * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
25  * This code was adapted to glib by Sebastian Wilhelmi.
26  */
27
28 /*
29  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
30  * file for a list of people on the GLib Team.  See the ChangeLog
31  * files for a list of changes.  These files are distributed with
32  * GLib at ftp://ftp.gtk.org/pub/gtk/.
33  */
34
35 /*
36  * MT safe
37  */
38
39 #include "config.h"
40 #define _CRT_RAND_S
41
42 #include <math.h>
43 #include <errno.h>
44 #include <stdio.h>
45 #include <string.h>
46 #include <sys/types.h>
47 #include "grand.h"
48
49 #include "genviron.h"
50 #include "gmain.h"
51 #include "gmem.h"
52 #include "gtestutils.h"
53 #include "gthread.h"
54
55 #ifdef G_OS_UNIX
56 #include <unistd.h>
57 #endif
58
59 #ifdef G_OS_WIN32
60 #include <stdlib.h>
61 #endif
62
63 /**
64  * SECTION:random_numbers
65  * @title: Random Numbers
66  * @short_description: pseudo-random number generator
67  *
68  * The following functions allow you to use a portable, fast and good
69  * pseudo-random number generator (PRNG).
70  * 
71  * <warning><para>Do not use this API for cryptographic purposes such as key
72  * generation, nonces, salts or one-time pads.</para></warning>
73  *
74  * This PRNG is suitable for non-cryptographic use such as in games
75  * (shuffling a card deck, generating levels), generating data for a
76  * test suite, etc. If you need random data for cryptographic
77  * purposes, it is recommended to use platform-specific APIs such as
78  * <literal>/dev/random</literal> on Unix, or CryptGenRandom() on
79  * Windows.
80  *
81  * GRand uses the Mersenne Twister PRNG, which was originally
82  * developed by Makoto Matsumoto and Takuji Nishimura. Further
83  * information can be found at <ulink
84  * url="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html">
85  * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</ulink>.
86  *
87  * If you just need a random number, you simply call the
88  * <function>g_random_*</function> functions, which will create a
89  * globally used #GRand and use the according
90  * <function>g_rand_*</function> functions internally. Whenever you
91  * need a stream of reproducible random numbers, you better create a
92  * #GRand yourself and use the <function>g_rand_*</function> functions
93  * directly, which will also be slightly faster. Initializing a #GRand
94  * with a certain seed will produce exactly the same series of random
95  * numbers on all platforms. This can thus be used as a seed for e.g.
96  * games.
97  *
98  * The <function>g_rand*_range</function> functions will return high
99  * quality equally distributed random numbers, whereas for example the
100  * <literal>(g_random_int()&percnt;max)</literal> approach often
101  * doesn't yield equally distributed numbers.
102  *
103  * GLib changed the seeding algorithm for the pseudo-random number
104  * generator Mersenne Twister, as used by #GRand and #GRandom.
105  * This was necessary, because some seeds would yield very bad
106  * pseudo-random streams. Also the pseudo-random integers generated by
107  * <function>g_rand*_int_range()</function> will have a slightly better
108  * equal distribution with the new version of GLib.
109  *
110  * The original seeding and generation algorithms, as found in GLib
111  * 2.0.x, can be used instead of the new ones by setting the
112  * environment variable <envar>G_RANDOM_VERSION</envar> to the value of
113  * '2.0'. Use the GLib-2.0 algorithms only if you have sequences of
114  * numbers generated with Glib-2.0 that you need to reproduce exactly.
115  **/
116
117 /**
118  * GRand:
119  *
120  * The #GRand struct is an opaque data structure. It should only be
121  * accessed through the <function>g_rand_*</function> functions.
122  **/
123
124 G_LOCK_DEFINE_STATIC (global_random);
125
126 /* Period parameters */  
127 #define N 624
128 #define M 397
129 #define MATRIX_A 0x9908b0df   /* constant vector a */
130 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
131 #define LOWER_MASK 0x7fffffff /* least significant r bits */
132
133 /* Tempering parameters */   
134 #define TEMPERING_MASK_B 0x9d2c5680
135 #define TEMPERING_MASK_C 0xefc60000
136 #define TEMPERING_SHIFT_U(y)  (y >> 11)
137 #define TEMPERING_SHIFT_S(y)  (y << 7)
138 #define TEMPERING_SHIFT_T(y)  (y << 15)
139 #define TEMPERING_SHIFT_L(y)  (y >> 18)
140
141 static guint
142 get_random_version (void)
143 {
144   static gsize initialized = FALSE;
145   static guint random_version;
146
147   if (g_once_init_enter (&initialized))
148     {
149       const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
150       if (!version_string || version_string[0] == '\000' || 
151           strcmp (version_string, "2.2") == 0)
152         random_version = 22;
153       else if (strcmp (version_string, "2.0") == 0)
154         random_version = 20;
155       else
156         {
157           g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
158                      version_string);
159           random_version = 22;
160         }
161       g_once_init_leave (&initialized, TRUE);
162     }
163   
164   return random_version;
165 }
166
167 struct _GRand
168 {
169   guint32 mt[N]; /* the array for the state vector  */
170   guint mti; 
171 };
172
173 /**
174  * g_rand_new_with_seed:
175  * @seed: a value to initialize the random number generator.
176  * 
177  * Creates a new random number generator initialized with @seed.
178  * 
179  * Return value: the new #GRand.
180  **/
181 GRand*
182 g_rand_new_with_seed (guint32 seed)
183 {
184   GRand *rand = g_new0 (GRand, 1);
185   g_rand_set_seed (rand, seed);
186   return rand;
187 }
188
189 /**
190  * g_rand_new_with_seed_array:
191  * @seed: an array of seeds to initialize the random number generator.
192  * @seed_length: an array of seeds to initialize the random number generator.
193  * 
194  * Creates a new random number generator initialized with @seed.
195  * 
196  * Return value: the new #GRand.
197  *
198  * Since: 2.4
199  **/
200 GRand*
201 g_rand_new_with_seed_array (const guint32 *seed, 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).  On Windows, the seed is taken from
214  * 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, 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
364  * longs.  Array can be of arbitrary size, though only the
365  * first 624 values are taken.  This function is useful
366  * if you have many low entropy seeds, or if you require more then
367  * 32bits of actual entropy for your application.
368  *
369  * Since: 2.4
370  **/
371 void
372 g_rand_set_seed_array (GRand* rand, const guint32 *seed, guint seed_length)
373 {
374   int i, j, k;
375
376   g_return_if_fail (rand != NULL);
377   g_return_if_fail (seed_length >= 1);
378
379   g_rand_set_seed (rand, 19650218UL);
380
381   i=1; j=0;
382   k = (N>seed_length ? N : seed_length);
383   for (; k; k--)
384     {
385       rand->mt[i] = (rand->mt[i] ^
386                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
387               + seed[j] + j; /* non linear */
388       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
389       i++; j++;
390       if (i>=N)
391         {
392           rand->mt[0] = rand->mt[N-1];
393           i=1;
394         }
395       if (j>=seed_length)
396         j=0;
397     }
398   for (k=N-1; k; k--)
399     {
400       rand->mt[i] = (rand->mt[i] ^
401                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
402               - i; /* non linear */
403       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
404       i++;
405       if (i>=N)
406         {
407           rand->mt[0] = rand->mt[N-1];
408           i=1;
409         }
410     }
411
412   rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
413 }
414
415 /**
416  * g_rand_boolean:
417  * @rand_: a #GRand.
418  *
419  * Returns a random #gboolean from @rand_. This corresponds to a
420  * unbiased coin toss.
421  *
422  * Returns: a random #gboolean.
423  **/
424 /**
425  * g_rand_int:
426  * @rand_: a #GRand.
427  *
428  * Returns the next random #guint32 from @rand_ equally distributed over
429  * the range [0..2^32-1].
430  *
431  * Return value: A random number.
432  **/
433 guint32
434 g_rand_int (GRand* rand)
435 {
436   guint32 y;
437   static const guint32 mag01[2]={0x0, MATRIX_A};
438   /* mag01[x] = x * MATRIX_A  for x=0,1 */
439
440   g_return_val_if_fail (rand != NULL, 0);
441
442   if (rand->mti >= N) { /* generate N words at one time */
443     int kk;
444     
445     for (kk=0;kk<N-M;kk++) {
446       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
447       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
448     }
449     for (;kk<N-1;kk++) {
450       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
451       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
452     }
453     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
454     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
455     
456     rand->mti = 0;
457   }
458   
459   y = rand->mt[rand->mti++];
460   y ^= TEMPERING_SHIFT_U(y);
461   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
462   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
463   y ^= TEMPERING_SHIFT_L(y);
464   
465   return y; 
466 }
467
468 /* transform [0..2^32] -> [0..1] */
469 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
470
471 /**
472  * g_rand_int_range:
473  * @rand_: a #GRand.
474  * @begin: lower closed bound of the interval.
475  * @end: upper open bound of the interval.
476  *
477  * Returns the next random #gint32 from @rand_ equally distributed over
478  * the range [@begin..@end-1].
479  *
480  * Return value: A random number.
481  **/
482 gint32 
483 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
484 {
485   guint32 dist = end - begin;
486   guint32 random;
487
488   g_return_val_if_fail (rand != NULL, begin);
489   g_return_val_if_fail (end > begin, begin);
490
491   switch (get_random_version ())
492     {
493     case 20:
494       if (dist <= 0x10000L) /* 2^16 */
495         {
496           /* This method, which only calls g_rand_int once is only good
497            * for (end - begin) <= 2^16, because we only have 32 bits set
498            * from the one call to g_rand_int (). */
499           
500           /* we are using (trans + trans * trans), because g_rand_int only
501            * covers [0..2^32-1] and thus g_rand_int * trans only covers
502            * [0..1-2^-32], but the biggest double < 1 is 1-2^-52. 
503            */
504           
505           gdouble double_rand = g_rand_int (rand) * 
506             (G_RAND_DOUBLE_TRANSFORM +
507              G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
508           
509           random = (gint32) (double_rand * dist);
510         }
511       else
512         {
513           /* Now we use g_rand_double_range (), which will set 52 bits for
514              us, so that it is safe to round and still get a decent
515              distribution */
516           random = (gint32) g_rand_double_range (rand, 0, dist);
517         }
518       break;
519     case 22:
520       if (dist == 0)
521         random = 0;
522       else 
523         {
524           /* maxvalue is set to the predecessor of the greatest
525            * multiple of dist less or equal 2^32. */
526           guint32 maxvalue;
527           if (dist <= 0x80000000u) /* 2^31 */
528             {
529               /* maxvalue = 2^32 - 1 - (2^32 % dist) */
530               guint32 leftover = (0x80000000u % dist) * 2;
531               if (leftover >= dist) leftover -= dist;
532               maxvalue = 0xffffffffu - leftover;
533             }
534           else
535             maxvalue = dist - 1;
536           
537           do
538             random = g_rand_int (rand);
539           while (random > maxvalue);
540           
541           random %= dist;
542         }
543       break;
544     default:
545       random = 0;               /* Quiet GCC */
546       g_assert_not_reached ();
547     }      
548  
549   return begin + random;
550 }
551
552 /**
553  * g_rand_double:
554  * @rand_: a #GRand.
555  *
556  * Returns the next random #gdouble from @rand_ equally distributed over
557  * the range [0..1).
558  *
559  * Return value: A random number.
560  **/
561 gdouble 
562 g_rand_double (GRand* rand)
563 {    
564   /* We set all 52 bits after the point for this, not only the first
565      32. Thats why we need two calls to g_rand_int */
566   gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
567   retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
568
569   /* The following might happen due to very bad rounding luck, but
570    * actually this should be more than rare, we just try again then */
571   if (retval >= 1.0) 
572     return g_rand_double (rand);
573
574   return retval;
575 }
576
577 /**
578  * g_rand_double_range:
579  * @rand_: a #GRand.
580  * @begin: lower closed bound of the interval.
581  * @end: upper open bound of the interval.
582  *
583  * Returns the next random #gdouble from @rand_ equally distributed over
584  * the range [@begin..@end).
585  *
586  * Return value: A random number.
587  **/
588 gdouble 
589 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
590 {
591   gdouble r;
592
593   r = g_rand_double (rand);
594
595   return r * end - (r - 1) * begin;
596 }
597
598 static GRand *
599 get_global_random (void)
600 {
601   static GRand *global_random;
602
603   /* called while locked */
604   if (!global_random)
605     global_random = g_rand_new ();
606
607   return global_random;
608 }
609
610 /**
611  * g_random_boolean:
612  *
613  * Returns a random #gboolean. This corresponds to a unbiased coin toss.
614  *
615  * Returns: a random #gboolean.
616  **/
617 /**
618  * g_random_int:
619  *
620  * Return a random #guint32 equally distributed over the range
621  * [0..2^32-1].
622  *
623  * Return value: A random number.
624  **/
625 guint32
626 g_random_int (void)
627 {
628   guint32 result;
629   G_LOCK (global_random);
630   result = g_rand_int (get_global_random ());
631   G_UNLOCK (global_random);
632   return result;
633 }
634
635 /**
636  * g_random_int_range:
637  * @begin: lower closed bound of the interval.
638  * @end: upper open bound of the interval.
639  *
640  * Returns a random #gint32 equally distributed over the range
641  * [@begin..@end-1].
642  *
643  * Return value: A random number.
644  **/
645 gint32 
646 g_random_int_range (gint32 begin, gint32 end)
647 {
648   gint32 result;
649   G_LOCK (global_random);
650   result = g_rand_int_range (get_global_random (), begin, end);
651   G_UNLOCK (global_random);
652   return result;
653 }
654
655 /**
656  * g_random_double:
657  *
658  * Returns a random #gdouble equally distributed over the range [0..1).
659  *
660  * Return value: A random number.
661  **/
662 gdouble 
663 g_random_double (void)
664 {
665   double result;
666   G_LOCK (global_random);
667   result = g_rand_double (get_global_random ());
668   G_UNLOCK (global_random);
669   return result;
670 }
671
672 /**
673  * g_random_double_range:
674  * @begin: lower closed bound of the interval.
675  * @end: upper open bound of the interval.
676  *
677  * Returns a random #gdouble equally distributed over the range [@begin..@end).
678  *
679  * Return value: A random number.
680  **/
681 gdouble 
682 g_random_double_range (gdouble begin, gdouble end)
683 {
684   double result;
685   G_LOCK (global_random);
686   result = g_rand_double_range (get_global_random (), begin, end);
687   G_UNLOCK (global_random);
688   return result;
689 }
690
691 /**
692  * g_random_set_seed:
693  * @seed: a value to reinitialize the global random number generator.
694  * 
695  * Sets the seed for the global random number generator, which is used
696  * by the <function>g_random_*</function> functions, to @seed.
697  **/
698 void
699 g_random_set_seed (guint32 seed)
700 {
701   G_LOCK (global_random);
702   g_rand_set_seed (get_global_random (), seed);
703   G_UNLOCK (global_random);
704 }