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