Use /dev/urandom, as it doesn't block, which /dev/random might do. Do not
[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 Library 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  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library 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-1999.  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 GRand*
68 g_rand_new_with_seed (guint32 seed)
69 {
70   GRand *rand = g_new0 (GRand, 1);
71   g_rand_set_seed (rand, seed);
72   return rand;
73 }
74
75 GRand* 
76 g_rand_new (void)
77 {
78   guint32 seed;
79   GTimeVal now;
80   static gboolean dev_urandom_exists = TRUE;
81   
82   if (dev_urandom_exists)
83     {
84       FILE* dev_urandom = fopen("/dev/urandom", "rb");
85       if (dev_urandom)
86         {
87           if (fread (&seed, sizeof (seed), 1, dev_urandom) != 1)
88             seed = 0;
89           else
90             dev_urandom_exists = FALSE;
91           fclose (dev_urandom);
92         }       
93       else
94         dev_urandom_exists = FALSE;
95     }
96   if (!dev_urandom_exists)
97     {  
98       g_get_current_time (&now);
99       seed = now.tv_sec ^ now.tv_usec;
100     }
101
102   return g_rand_new_with_seed (seed);
103 }
104
105 void
106 g_rand_free (GRand* rand)
107 {
108   g_return_if_fail (rand != NULL);
109
110   g_free (rand);
111 }
112
113 void
114 g_rand_set_seed (GRand* rand, guint32 seed)
115 {
116   g_return_if_fail (rand != NULL);
117
118   /* setting initial seeds to mt[N] using         */
119   /* the generator Line 25 of Table 1 in          */
120   /* [KNUTH 1981, The Art of Computer Programming */
121   /*    Vol. 2 (2nd Ed.), pp102]                  */
122   
123   if (seed == 0) /* This would make the PRNG procude only zeros */
124     seed = 0x6b842128; /* Just set it to another number */
125
126   rand->mt[0]= seed & 0xffffffff;
127   for (rand->mti=1; rand->mti<N; rand->mti++)
128     rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]) & 0xffffffff;
129 }
130
131 guint32
132 g_rand_int (GRand* rand)
133 {
134   guint32 y;
135   static const guint32 mag01[2]={0x0, MATRIX_A};
136   /* mag01[x] = x * MATRIX_A  for x=0,1 */
137
138   g_return_val_if_fail (rand != NULL, 0);
139
140   if (rand->mti >= N) { /* generate N words at one time */
141     int kk;
142     
143     for (kk=0;kk<N-M;kk++) {
144       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
145       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
146     }
147     for (;kk<N-1;kk++) {
148       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
149       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
150     }
151     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
152     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
153     
154     rand->mti = 0;
155   }
156   
157   y = rand->mt[rand->mti++];
158   y ^= TEMPERING_SHIFT_U(y);
159   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
160   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
161   y ^= TEMPERING_SHIFT_L(y);
162   
163   return y; 
164 }
165
166 gint32 
167 g_rand_int_range (GRand* rand, gint32 min, gint32 max)
168 {
169   guint32 dist = max - min;
170   guint32 random;
171
172   g_return_val_if_fail (rand != NULL, min);
173   g_return_val_if_fail (max > min, min);
174
175   if (dist <= 0x10000L) /* 2^16 */
176     {
177       /* All tricks doing modulo calculations do not have a good
178          distribution -> We must use this slower method for maximal
179          quality, but this method is only good for (max - min) <= 2^16 */
180       
181       random = (gint32) g_rand_double_range (rand, 0, dist);
182       /* we'd rather use the following, if -lm is allowed later on:
183          random = (gint32) floor (g_rand_double_range (rand, 0, dist));  */
184     }
185   else
186     {
187       /* Now it's harder to make it right. We calculate the smallest m,
188          such that dist < 2 ^ m, then we calculate a random number in
189          [1..2^32-1] and rightshift it by 32 - m. Then we test, if it
190          is smaller than dist and if not, get a new number and so
191          forth until we get a number smaller than dist. We just return
192          this. */
193       guint32 border = 0x20000L; /* 2^17 */
194       guint right_shift = 15; /* 32 - 17 */
195
196       if (dist >= 0x80000000) /* in the case of dist > 2^31 our loop
197                                 below will be infinite */
198         {
199           right_shift = 0;
200         }
201       else
202         {
203           while (dist >= border) 
204             {
205               border <<= 1;
206               right_shift--;
207             }
208         }
209       do 
210         { 
211           random = g_rand_int (rand) >> right_shift; 
212         } while (random >= dist);
213     }
214   return min + random;
215 }
216
217 /* transform [0..2^32-1] -> [0..1) */
218 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386963e-10
219
220 gdouble 
221 g_rand_double (GRand* rand)
222 {                            
223   return g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
224 }
225
226 gdouble 
227 g_rand_double_range (GRand* rand, gdouble min, gdouble max)
228 {
229   return g_rand_int (rand) * ((max - min) * G_RAND_DOUBLE_TRANSFORM)  + min;
230 }
231
232 guint32
233 g_random_int (void)
234 {
235   guint32 result;
236   G_LOCK (global_random);
237   if (!global_random)
238     global_random = g_rand_new ();
239   
240   result = g_rand_int (global_random);
241   G_UNLOCK (global_random);
242   return result;
243 }
244
245 gint32 
246 g_random_int_range (gint32 min, gint32 max)
247 {
248   gint32 result;
249   G_LOCK (global_random);
250   if (!global_random)
251     global_random = g_rand_new ();
252   
253   result = g_rand_int_range (global_random, min, max);
254   G_UNLOCK (global_random);
255   return result;
256 }
257
258 gdouble 
259 g_random_double (void)
260 {
261   double result;
262   G_LOCK (global_random);
263   if (!global_random)
264     global_random = g_rand_new ();
265   
266   result = g_rand_double (global_random);
267   G_UNLOCK (global_random);
268   return result;
269 }
270
271 gdouble 
272 g_random_double_range (gdouble min, gdouble max)
273 {
274   double result;
275   G_LOCK (global_random);
276   if (!global_random)
277     global_random = g_rand_new ();
278  
279   result = g_rand_double_range (global_random, min, max);
280   G_UNLOCK (global_random);
281   return result;
282 }
283
284 void
285 g_random_set_seed (guint32 seed)
286 {
287   G_LOCK (global_random);
288   if (!global_random)
289     global_random = g_rand_new_with_seed (seed);
290   else
291     g_rand_set_seed (global_random, seed);
292   G_UNLOCK (global_random);
293 }
294