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