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