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