fix typo (#if->#ifdef) so it compiles again.
[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 #ifdef G_OS_UNIX
98   static gboolean dev_urandom_exists = TRUE;
99
100   if (dev_urandom_exists)
101     {
102       FILE* dev_urandom = fopen("/dev/urandom", "rb");
103       if (dev_urandom)
104         {
105           if (fread (&seed, sizeof (seed), 1, dev_urandom) != 1)
106             dev_urandom_exists = FALSE;
107           fclose (dev_urandom);
108         }       
109       else
110         dev_urandom_exists = FALSE;
111     }
112 #else
113   static gboolean dev_urandom_exists = FALSE;
114 #endif
115
116   if (!dev_urandom_exists)
117     {  
118       g_get_current_time (&now);
119       seed = now.tv_sec ^ now.tv_usec;
120     }
121
122   return g_rand_new_with_seed (seed);
123 }
124
125 /**
126  * g_rand_free:
127  * @rand: a #GRand.
128  *
129  * Frees the memory allocated for the #GRand.
130  **/
131 void
132 g_rand_free (GRand* rand)
133 {
134   g_return_if_fail (rand != NULL);
135
136   g_free (rand);
137 }
138
139 /**
140  * g_rand_set_seed:
141  * @rand: a #GRand.
142  * @seed: a value to reinitialize the random number generator.
143  *
144  * Sets the seed for the random number generator #GRand to @seed.
145  **/
146 void
147 g_rand_set_seed (GRand* rand, guint32 seed)
148 {
149   g_return_if_fail (rand != NULL);
150
151   /* setting initial seeds to mt[N] using         */
152   /* the generator Line 25 of Table 1 in          */
153   /* [KNUTH 1981, The Art of Computer Programming */
154   /*    Vol. 2 (2nd Ed.), pp102]                  */
155   
156   if (seed == 0) /* This would make the PRNG procude only zeros */
157     seed = 0x6b842128; /* Just set it to another number */
158
159   rand->mt[0]= seed & 0xffffffff;
160   for (rand->mti=1; rand->mti<N; rand->mti++)
161     rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]) & 0xffffffff;
162 }
163
164 /**
165  * g_rand_int:
166  * @rand: a #GRand.
167  *
168  * Return the next random #guint32 from @rand equaly distributed over
169  * the range [0..2^32-1].
170  *
171  * Return value: A random number.
172  **/
173 guint32
174 g_rand_int (GRand* rand)
175 {
176   guint32 y;
177   static const guint32 mag01[2]={0x0, MATRIX_A};
178   /* mag01[x] = x * MATRIX_A  for x=0,1 */
179
180   g_return_val_if_fail (rand != NULL, 0);
181
182   if (rand->mti >= N) { /* generate N words at one time */
183     int kk;
184     
185     for (kk=0;kk<N-M;kk++) {
186       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
187       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
188     }
189     for (;kk<N-1;kk++) {
190       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
191       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
192     }
193     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
194     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
195     
196     rand->mti = 0;
197   }
198   
199   y = rand->mt[rand->mti++];
200   y ^= TEMPERING_SHIFT_U(y);
201   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
202   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
203   y ^= TEMPERING_SHIFT_L(y);
204   
205   return y; 
206 }
207
208 /* transform [0..2^32] -> [0..1] */
209 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
210
211 /**
212  * g_rand_int_range:
213  * @rand: a #GRand.
214  * @begin: lower closed bound of the interval.
215  * @end: upper open bound of the interval.
216  *
217  * Return the next random #gint32 from @rand equaly distributed over
218  * the range [@begin..@end-1].
219  *
220  * Return value: A random number.
221  **/
222 gint32 
223 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
224 {
225   guint32 dist = end - begin;
226   guint32 random;
227
228   g_return_val_if_fail (rand != NULL, begin);
229   g_return_val_if_fail (end > begin, begin);
230
231   /* All tricks doing modulo calculations do not have a perfect
232    * distribution -> We must use the slower way through gdouble for
233    * maximal quality. */
234    
235   if (dist <= 0x10000L) /* 2^16 */
236     {
237       /* This method, which only calls g_rand_int once is only good
238        * for (end - begin) <= 2^16, because we only have 32 bits set
239        * from the one call to g_rand_int (). */
240
241       /* we are using (trans + trans * trans), because g_rand_int only
242        * covers [0..2^32-1] and thus g_rand_int * trans only covers
243        * [0..1-2^-32], but the biggest double < 1 is 1-2^-52. 
244        */
245
246       gdouble double_rand = g_rand_int (rand) * 
247         (G_RAND_DOUBLE_TRANSFORM +
248          G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
249       
250       random = (gint32) (double_rand * dist);
251     }
252   else
253     {
254       /* Now we use g_rand_double_range (), which will set 52 bits for
255          us, so that it is safe to round and still get a decent
256          distribution */
257        random = (gint32) g_rand_double_range (rand, 0, dist);
258     }
259  
260   return begin + random;
261 }
262
263 /**
264  * g_rand_double:
265  * @rand: a #GRand.
266  *
267  * Return the next random #gdouble from @rand equaly distributed over
268  * the range [0..1).
269  *
270  * Return value: A random number.
271  **/
272 gdouble 
273 g_rand_double (GRand* rand)
274 {    
275   /* We set all 52 bits after the point for this, not only the first
276      32. Thats why we need two calls to g_rand_int */
277   gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
278   retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
279
280   /* The following might happen due to very bad rounding luck, but
281    * actually this should be more than rare, we just try again then */
282   if (retval >= 1.0) 
283     return g_rand_double (rand);
284
285   return retval;
286 }
287
288 /**
289  * g_rand_double_range:
290  * @rand: a #GRand.
291  * @begin: lower closed bound of the interval.
292  * @end: upper open bound of the interval.
293  *
294  * Return the next random #gdouble from @rand equaly distributed over
295  * the range [@begin..@end).
296  *
297  * Return value: A random number.
298  **/
299 gdouble 
300 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
301 {
302   return g_rand_double (rand) * (end - begin) + begin;
303 }
304
305 /**
306  * g_random_int:
307  *
308  * Return a random #guint32 equaly distributed over the range
309  * [0..2^32-1].
310  *
311  * Return value: A random number.
312  **/
313 guint32
314 g_random_int (void)
315 {
316   guint32 result;
317   G_LOCK (global_random);
318   if (!global_random)
319     global_random = g_rand_new ();
320   
321   result = g_rand_int (global_random);
322   G_UNLOCK (global_random);
323   return result;
324 }
325
326 /**
327  * g_random_int_range:
328  * @begin: lower closed bound of the interval.
329  * @end: upper open bound of the interval.
330  *
331  * Return a random #gint32 equaly distributed over the range
332  * [@begin..@end-1].
333  *
334  * Return value: A random number.
335  **/
336 gint32 
337 g_random_int_range (gint32 begin, gint32 end)
338 {
339   gint32 result;
340   G_LOCK (global_random);
341   if (!global_random)
342     global_random = g_rand_new ();
343   
344   result = g_rand_int_range (global_random, begin, end);
345   G_UNLOCK (global_random);
346   return result;
347 }
348
349 /**
350  * g_random_double:
351  *
352  * Return a random #gdouble equaly distributed over the range [0..1).
353  *
354  * Return value: A random number.
355  **/
356 gdouble 
357 g_random_double (void)
358 {
359   double result;
360   G_LOCK (global_random);
361   if (!global_random)
362     global_random = g_rand_new ();
363   
364   result = g_rand_double (global_random);
365   G_UNLOCK (global_random);
366   return result;
367 }
368
369 /**
370  * g_random_double_range:
371  * @begin: lower closed bound of the interval.
372  * @end: upper open bound of the interval.
373  *
374  * Return a random #gdouble equaly distributed over the range [@begin..@end).
375  *
376  * Return value: A random number.
377  **/
378 gdouble 
379 g_random_double_range (gdouble begin, gdouble end)
380 {
381   double result;
382   G_LOCK (global_random);
383   if (!global_random)
384     global_random = g_rand_new ();
385  
386   result = g_rand_double_range (global_random, begin, end);
387   G_UNLOCK (global_random);
388   return result;
389 }
390
391 /**
392  * g_random_set_seed:
393  * @seed: a value to reinitialize the global random number generator.
394  * 
395  * Sets the seed for the global random number generator, which is used
396  * by te g_random_* functions, to @seed.
397  **/
398 void
399 g_random_set_seed (guint32 seed)
400 {
401   G_LOCK (global_random);
402   if (!global_random)
403     global_random = g_rand_new_with_seed (seed);
404   else
405     g_rand_set_seed (global_random, seed);
406   G_UNLOCK (global_random);
407 }
408