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