Improved the seeding algorithm. Old behaviour can be achived by setting
[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.keio.ac.jp/~matumoto/emt.html
25  * This code was adapted to glib by Sebastian Wilhelmi <wilhelmi@ira.uka.de>.
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 <glib.h>
40 #include <math.h>
41 #include <stdio.h>
42
43 G_LOCK_DEFINE_STATIC (global_random);
44 static GRand* global_random = NULL;
45
46 /* Period parameters */  
47 #define N 624
48 #define M 397
49 #define MATRIX_A 0x9908b0df   /* constant vector a */
50 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
51 #define LOWER_MASK 0x7fffffff /* least significant r bits */
52
53 /* Tempering parameters */   
54 #define TEMPERING_MASK_B 0x9d2c5680
55 #define TEMPERING_MASK_C 0xefc60000
56 #define TEMPERING_SHIFT_U(y)  (y >> 11)
57 #define TEMPERING_SHIFT_S(y)  (y << 7)
58 #define TEMPERING_SHIFT_T(y)  (y << 15)
59 #define TEMPERING_SHIFT_L(y)  (y >> 18)
60
61 static guint
62 get_random_version (void)
63 {
64   static gboolean initialized = FALSE;
65   static guint random_version;
66   
67   if (!initialized)
68     {
69       const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
70       if (!version_string || version_string[0] == '\000' || 
71           strcmp (version_string, "2.2") == 0)
72         random_version = 22;
73       else if (strcmp (version_string, "2.0") == 0)
74         random_version = 20;
75       else
76         {
77           g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
78                      version_string);
79           random_version = 22;
80         }
81       initialized = TRUE;
82     }
83   
84   return random_version;
85 }
86
87 /* This is called from g_thread_init(). It's used to
88  * initialize some static data in a threadsafe way.
89  */
90 void 
91 g_rand_init (void)
92 {
93   (void)get_random_version ();
94 }
95
96 struct _GRand
97 {
98   guint32 mt[N]; /* the array for the state vector  */
99   guint mti; 
100 };
101
102 /**
103  * g_rand_new_with_seed:
104  * @seed: a value to initialize the random number generator.
105  * 
106  * Creates a new random number generator initialized with @seed.
107  * 
108  * Return value: the new #GRand.
109  **/
110 GRand*
111 g_rand_new_with_seed (guint32 seed)
112 {
113   GRand *rand = g_new0 (GRand, 1);
114   g_rand_set_seed (rand, seed);
115   return rand;
116 }
117
118 /**
119  * g_rand_new:
120  * 
121  * Creates a new random number generator initialized with a seed taken
122  * either from <filename>/dev/urandom</filename> (if existing) or from 
123  * the current time (as a fallback).
124  * 
125  * Return value: the new #GRand.
126  **/
127 GRand* 
128 g_rand_new (void)
129 {
130   guint32 seed;
131   GTimeVal now;
132 #ifdef G_OS_UNIX
133   static gboolean dev_urandom_exists = TRUE;
134
135   if (dev_urandom_exists)
136     {
137       FILE* dev_urandom = fopen("/dev/urandom", "rb");
138       if (dev_urandom)
139         {
140           if (fread (&seed, sizeof (seed), 1, dev_urandom) != 1)
141             dev_urandom_exists = FALSE;
142           fclose (dev_urandom);
143         }       
144       else
145         dev_urandom_exists = FALSE;
146     }
147 #else
148   static gboolean dev_urandom_exists = FALSE;
149 #endif
150
151   if (!dev_urandom_exists)
152     {  
153       g_get_current_time (&now);
154       seed = now.tv_sec ^ now.tv_usec;
155     }
156
157   return g_rand_new_with_seed (seed);
158 }
159
160 /**
161  * g_rand_free:
162  * @rand_: a #GRand.
163  *
164  * Frees the memory allocated for the #GRand.
165  **/
166 void
167 g_rand_free (GRand* rand)
168 {
169   g_return_if_fail (rand != NULL);
170
171   g_free (rand);
172 }
173
174 /**
175  * g_rand_set_seed:
176  * @rand_: a #GRand.
177  * @seed: a value to reinitialize the random number generator.
178  *
179  * Sets the seed for the random number generator #GRand to @seed.
180  **/
181 void
182 g_rand_set_seed (GRand* rand, guint32 seed)
183 {
184   g_return_if_fail (rand != NULL);
185
186   switch (get_random_version ())
187     {
188     case 20:
189       /* setting initial seeds to mt[N] using         */
190       /* the generator Line 25 of Table 1 in          */
191       /* [KNUTH 1981, The Art of Computer Programming */
192       /*    Vol. 2 (2nd Ed.), pp102]                  */
193       
194       if (seed == 0) /* This would make the PRNG procude only zeros */
195         seed = 0x6b842128; /* Just set it to another number */
196       
197       rand->mt[0]= seed;
198       for (rand->mti=1; rand->mti<N; rand->mti++)
199         rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
200       
201       break;
202     case 22:
203       /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
204       /* In the previous version (see above), MSBs of the    */
205       /* seed affect only MSBs of the array mt[].            */
206       
207       rand->mt[0]= seed;
208       for (rand->mti=1; rand->mti<N; rand->mti++)
209         rand->mt[rand->mti] = 1812433253UL * 
210           (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti; 
211       break;
212     default:
213       g_assert_not_reached ();
214     }
215 }
216
217 /**
218  * g_rand_int:
219  * @rand_: a #GRand.
220  *
221  * Returns the next random #guint32 from @rand_ equally distributed over
222  * the range [0..2^32-1].
223  *
224  * Return value: A random number.
225  **/
226 guint32
227 g_rand_int (GRand* rand)
228 {
229   guint32 y;
230   static const guint32 mag01[2]={0x0, MATRIX_A};
231   /* mag01[x] = x * MATRIX_A  for x=0,1 */
232
233   g_return_val_if_fail (rand != NULL, 0);
234
235   if (rand->mti >= N) { /* generate N words at one time */
236     int kk;
237     
238     for (kk=0;kk<N-M;kk++) {
239       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
240       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
241     }
242     for (;kk<N-1;kk++) {
243       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
244       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
245     }
246     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
247     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
248     
249     rand->mti = 0;
250   }
251   
252   y = rand->mt[rand->mti++];
253   y ^= TEMPERING_SHIFT_U(y);
254   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
255   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
256   y ^= TEMPERING_SHIFT_L(y);
257   
258   return y; 
259 }
260
261 /* transform [0..2^32] -> [0..1] */
262 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
263
264 /**
265  * g_rand_int_range:
266  * @rand_: a #GRand.
267  * @begin: lower closed bound of the interval.
268  * @end: upper open bound of the interval.
269  *
270  * Returns the next random #gint32 from @rand_ equally distributed over
271  * the range [@begin..@end-1].
272  *
273  * Return value: A random number.
274  **/
275 gint32 
276 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
277 {
278   guint32 dist = end - begin;
279   guint32 random;
280
281   g_return_val_if_fail (rand != NULL, begin);
282   g_return_val_if_fail (end > begin, begin);
283
284   /* All tricks doing modulo calculations do not have a perfect
285    * distribution -> We must use the slower way through gdouble for
286    * maximal quality. */
287    
288   if (dist <= 0x10000L) /* 2^16 */
289     {
290       /* This method, which only calls g_rand_int once is only good
291        * for (end - begin) <= 2^16, because we only have 32 bits set
292        * from the one call to g_rand_int (). */
293
294       /* we are using (trans + trans * trans), because g_rand_int only
295        * covers [0..2^32-1] and thus g_rand_int * trans only covers
296        * [0..1-2^-32], but the biggest double < 1 is 1-2^-52. 
297        */
298
299       gdouble double_rand = g_rand_int (rand) * 
300         (G_RAND_DOUBLE_TRANSFORM +
301          G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
302       
303       random = (gint32) (double_rand * dist);
304     }
305   else
306     {
307       /* Now we use g_rand_double_range (), which will set 52 bits for
308          us, so that it is safe to round and still get a decent
309          distribution */
310        random = (gint32) g_rand_double_range (rand, 0, dist);
311     }
312  
313   return begin + random;
314 }
315
316 /**
317  * g_rand_double:
318  * @rand_: a #GRand.
319  *
320  * Returns the next random #gdouble from @rand_ equally distributed over
321  * the range [0..1).
322  *
323  * Return value: A random number.
324  **/
325 gdouble 
326 g_rand_double (GRand* rand)
327 {    
328   /* We set all 52 bits after the point for this, not only the first
329      32. Thats why we need two calls to g_rand_int */
330   gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
331   retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
332
333   /* The following might happen due to very bad rounding luck, but
334    * actually this should be more than rare, we just try again then */
335   if (retval >= 1.0) 
336     return g_rand_double (rand);
337
338   return retval;
339 }
340
341 /**
342  * g_rand_double_range:
343  * @rand_: a #GRand.
344  * @begin: lower closed bound of the interval.
345  * @end: upper open bound of the interval.
346  *
347  * Returns the next random #gdouble from @rand_ equally distributed over
348  * the range [@begin..@end).
349  *
350  * Return value: A random number.
351  **/
352 gdouble 
353 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
354 {
355   return g_rand_double (rand) * (end - begin) + begin;
356 }
357
358 /**
359  * g_random_int:
360  *
361  * Return a random #guint32 equally distributed over the range
362  * [0..2^32-1].
363  *
364  * Return value: A random number.
365  **/
366 guint32
367 g_random_int (void)
368 {
369   guint32 result;
370   G_LOCK (global_random);
371   if (!global_random)
372     global_random = g_rand_new ();
373   
374   result = g_rand_int (global_random);
375   G_UNLOCK (global_random);
376   return result;
377 }
378
379 /**
380  * g_random_int_range:
381  * @begin: lower closed bound of the interval.
382  * @end: upper open bound of the interval.
383  *
384  * Returns a random #gint32 equally distributed over the range
385  * [@begin..@end-1].
386  *
387  * Return value: A random number.
388  **/
389 gint32 
390 g_random_int_range (gint32 begin, gint32 end)
391 {
392   gint32 result;
393   G_LOCK (global_random);
394   if (!global_random)
395     global_random = g_rand_new ();
396   
397   result = g_rand_int_range (global_random, begin, end);
398   G_UNLOCK (global_random);
399   return result;
400 }
401
402 /**
403  * g_random_double:
404  *
405  * Returns a random #gdouble equally distributed over the range [0..1).
406  *
407  * Return value: A random number.
408  **/
409 gdouble 
410 g_random_double (void)
411 {
412   double result;
413   G_LOCK (global_random);
414   if (!global_random)
415     global_random = g_rand_new ();
416   
417   result = g_rand_double (global_random);
418   G_UNLOCK (global_random);
419   return result;
420 }
421
422 /**
423  * g_random_double_range:
424  * @begin: lower closed bound of the interval.
425  * @end: upper open bound of the interval.
426  *
427  * Returns a random #gdouble equally distributed over the range [@begin..@end).
428  *
429  * Return value: A random number.
430  **/
431 gdouble 
432 g_random_double_range (gdouble begin, gdouble end)
433 {
434   double result;
435   G_LOCK (global_random);
436   if (!global_random)
437     global_random = g_rand_new ();
438  
439   result = g_rand_double_range (global_random, begin, end);
440   G_UNLOCK (global_random);
441   return result;
442 }
443
444 /**
445  * g_random_set_seed:
446  * @seed: a value to reinitialize the global random number generator.
447  * 
448  * Sets the seed for the global random number generator, which is used
449  * by the <function>g_random_*</function> functions, to @seed.
450  **/
451 void
452 g_random_set_seed (guint32 seed)
453 {
454   G_LOCK (global_random);
455   if (!global_random)
456     global_random = g_rand_new_with_seed (seed);
457   else
458     g_rand_set_seed (global_random, seed);
459   G_UNLOCK (global_random);
460 }
461