Added inline documentation.
[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 struct _GRand
62 {
63   guint32 mt[N]; /* the array for the state vector  */
64   guint mti; 
65 };
66
67 /**
68  * g_rand_new_with_seed:
69  * @seed: a value to initialize the random number generator.
70  * 
71  * Creates a new random number generator initialized with @seed.
72  * 
73  * Return value: the new #GRand.
74  **/
75 GRand*
76 g_rand_new_with_seed (guint32 seed)
77 {
78   GRand *rand = g_new0 (GRand, 1);
79   g_rand_set_seed (rand, seed);
80   return rand;
81 }
82
83 /**
84  * g_rand_new:
85  * 
86  * Creates a new random number generator initialized with a seed taken
87  * either from /dev/urandom (if existing) or from the current time (as
88  * a fallback).
89  * 
90  * Return value: the new #GRand.
91  **/
92 GRand* 
93 g_rand_new (void)
94 {
95   guint32 seed;
96   GTimeVal now;
97   static gboolean dev_urandom_exists = TRUE;
98   
99   if (dev_urandom_exists)
100     {
101       FILE* dev_urandom = fopen("/dev/urandom", "rb");
102       if (dev_urandom)
103         {
104           if (fread (&seed, sizeof (seed), 1, dev_urandom) != 1)
105             dev_urandom_exists = FALSE;
106           fclose (dev_urandom);
107         }       
108       else
109         dev_urandom_exists = FALSE;
110     }
111   if (!dev_urandom_exists)
112     {  
113       g_get_current_time (&now);
114       seed = now.tv_sec ^ now.tv_usec;
115     }
116
117   return g_rand_new_with_seed (seed);
118 }
119
120 /**
121  * g_rand_free:
122  * @rand: a #GRand.
123  *
124  * Frees the memory allocated for the #GRand.
125  **/
126 void
127 g_rand_free (GRand* rand)
128 {
129   g_return_if_fail (rand != NULL);
130
131   g_free (rand);
132 }
133
134 /**
135  * g_rand_set_seed:
136  * @rand: a #GRand.
137  * @seed: a value to reinitialize the random number generator.
138  *
139  * Sets the seed for the random number generator #GRand to @seed.
140  **/
141 void
142 g_rand_set_seed (GRand* rand, guint32 seed)
143 {
144   g_return_if_fail (rand != NULL);
145
146   /* setting initial seeds to mt[N] using         */
147   /* the generator Line 25 of Table 1 in          */
148   /* [KNUTH 1981, The Art of Computer Programming */
149   /*    Vol. 2 (2nd Ed.), pp102]                  */
150   
151   if (seed == 0) /* This would make the PRNG procude only zeros */
152     seed = 0x6b842128; /* Just set it to another number */
153
154   rand->mt[0]= seed & 0xffffffff;
155   for (rand->mti=1; rand->mti<N; rand->mti++)
156     rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]) & 0xffffffff;
157 }
158
159 /**
160  * g_rand_int:
161  * @rand: a #GRand.
162  *
163  * Return the next random #guint32 from @rand equaly distributed over
164  * the range [0..2^32-1].
165  *
166  * Return value: A random number.
167  **/
168 guint32
169 g_rand_int (GRand* rand)
170 {
171   guint32 y;
172   static const guint32 mag01[2]={0x0, MATRIX_A};
173   /* mag01[x] = x * MATRIX_A  for x=0,1 */
174
175   g_return_val_if_fail (rand != NULL, 0);
176
177   if (rand->mti >= N) { /* generate N words at one time */
178     int kk;
179     
180     for (kk=0;kk<N-M;kk++) {
181       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
182       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
183     }
184     for (;kk<N-1;kk++) {
185       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
186       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
187     }
188     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
189     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
190     
191     rand->mti = 0;
192   }
193   
194   y = rand->mt[rand->mti++];
195   y ^= TEMPERING_SHIFT_U(y);
196   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
197   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
198   y ^= TEMPERING_SHIFT_L(y);
199   
200   return y; 
201 }
202
203 /**
204  * g_rand_int_range:
205  * @rand: a #GRand.
206  * @min: lower closed bound of the interval.
207  * @max: upper open bound of the interval.
208  *
209  * Return the next random #gint32 from @rand equaly distributed over
210  * the range [@min..@max-1].
211  *
212  * Return value: A random number.
213  **/
214 gint32 
215 g_rand_int_range (GRand* rand, gint32 min, gint32 max)
216 {
217   guint32 dist = max - min;
218   guint32 random;
219
220   g_return_val_if_fail (rand != NULL, min);
221   g_return_val_if_fail (max > min, min);
222
223   if (dist <= 0x10000L) /* 2^16 */
224     {
225       /* All tricks doing modulo calculations do not have a good
226          distribution -> We must use this slower method for maximal
227          quality, but this method is only good for (max - min) <= 2^16 */
228       
229       random = (gint32) g_rand_double_range (rand, 0, dist);
230       /* we'd rather use the following, if -lm is allowed later on:
231          random = (gint32) floor (g_rand_double_range (rand, 0, dist));  */
232     }
233   else
234     {
235       /* Now it's harder to make it right. We calculate the smallest m,
236          such that dist < 2 ^ m, then we calculate a random number in
237          [1..2^32-1] and rightshift it by 32 - m. Then we test, if it
238          is smaller than dist and if not, get a new number and so
239          forth until we get a number smaller than dist. We just return
240          this. */
241       guint32 border = 0x20000L; /* 2^17 */
242       guint right_shift = 15; /* 32 - 17 */
243
244       if (dist >= 0x80000000) /* in the case of dist > 2^31 our loop
245                                 below will be infinite */
246         {
247           right_shift = 0;
248         }
249       else
250         {
251           while (dist >= border) 
252             {
253               border <<= 1;
254               right_shift--;
255             }
256         }
257       do 
258         { 
259           random = g_rand_int (rand) >> right_shift; 
260         } while (random >= dist);
261     }
262   return min + random;
263 }
264
265 /* transform [0..2^32-1] -> [0..1) */
266 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386963e-10
267
268 /**
269  * g_rand_double:
270  * @rand: a #GRand.
271  *
272  * Return the next random #gdouble from @rand equaly distributed over
273  * the range [0..1).
274  *
275  * Return value: A random number.
276  **/
277 gdouble 
278 g_rand_double (GRand* rand)
279 {                            
280   return g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
281 }
282
283 /**
284  * g_rand_double_range:
285  * @rand: a #GRand.
286  * @min: lower closed bound of the interval.
287  * @max: upper open bound of the interval.
288  *
289  * Return the next random #gdouble from @rand equaly distributed over
290  * the range [@min..@max).
291  *
292  * Return value: A random number.
293  **/
294 gdouble 
295 g_rand_double_range (GRand* rand, gdouble min, gdouble max)
296 {
297   return g_rand_int (rand) * ((max - min) * G_RAND_DOUBLE_TRANSFORM)  + min;
298 }
299
300 /**
301  * g_random_int:
302  *
303  * Return a random #guint32 equaly distributed over the range
304  * [0..2^32-1].
305  *
306  * Return value: A random number.
307  **/
308 guint32
309 g_random_int (void)
310 {
311   guint32 result;
312   G_LOCK (global_random);
313   if (!global_random)
314     global_random = g_rand_new ();
315   
316   result = g_rand_int (global_random);
317   G_UNLOCK (global_random);
318   return result;
319 }
320
321 /**
322  * g_random_int_range:
323  * @min: lower closed bound of the interval.
324  * @max: upper open bound of the interval.
325  *
326  * Return a random #gint32 equaly distributed over the range
327  * [@min..@max-1].
328  *
329  * Return value: A random number.
330  **/
331 gint32 
332 g_random_int_range (gint32 min, gint32 max)
333 {
334   gint32 result;
335   G_LOCK (global_random);
336   if (!global_random)
337     global_random = g_rand_new ();
338   
339   result = g_rand_int_range (global_random, min, max);
340   G_UNLOCK (global_random);
341   return result;
342 }
343
344 /**
345  * g_random_double:
346  *
347  * Return a random #gdouble equaly distributed over the range [0..1).
348  *
349  * Return value: A random number.
350  **/
351 gdouble 
352 g_random_double (void)
353 {
354   double result;
355   G_LOCK (global_random);
356   if (!global_random)
357     global_random = g_rand_new ();
358   
359   result = g_rand_double (global_random);
360   G_UNLOCK (global_random);
361   return result;
362 }
363
364 /**
365  * g_random_double_range:
366  * @min: lower closed bound of the interval.
367  * @max: upper open bound of the interval.
368  *
369  * Return a random #gdouble equaly distributed over the range [@min..@max).
370  *
371  * Return value: A random number.
372  **/
373 gdouble 
374 g_random_double_range (gdouble min, gdouble max)
375 {
376   double result;
377   G_LOCK (global_random);
378   if (!global_random)
379     global_random = g_rand_new ();
380  
381   result = g_rand_double_range (global_random, min, max);
382   G_UNLOCK (global_random);
383   return result;
384 }
385
386 /**
387  * g_random_set_seed:
388  * @seed: a value to reinitialize the global random number generator.
389  * 
390  * Sets the seed for the global random number generator, which is used
391  * by te g_random_* functions, to @seed.
392  **/
393 void
394 g_random_set_seed (guint32 seed)
395 {
396   G_LOCK (global_random);
397   if (!global_random)
398     global_random = g_rand_new_with_seed (seed);
399   else
400     g_rand_set_seed (global_random, seed);
401   G_UNLOCK (global_random);
402 }
403