New files to implement the Mersenne Twister Pseudo Random Number
[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  */
26
27 /*
28  * Modified by the GLib Team and others 1997-1999.  See the AUTHORS
29  * file for a list of people on the GLib Team.  See the ChangeLog
30  * files for a list of changes.  These files are distributed with
31  * GLib at ftp://ftp.gtk.org/pub/gtk/.  
32  */
33
34 #include <glib.h>
35 #include <math.h>
36 #include <stdio.h>
37
38 G_LOCK_DEFINE_STATIC (global_random);
39 static GRand* global_random = NULL;
40
41 /* Period parameters */  
42 #define N 624
43 #define M 397
44 #define MATRIX_A 0x9908b0df   /* constant vector a */
45 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
46 #define LOWER_MASK 0x7fffffff /* least significant r bits */
47
48 /* Tempering parameters */   
49 #define TEMPERING_MASK_B 0x9d2c5680
50 #define TEMPERING_MASK_C 0xefc60000
51 #define TEMPERING_SHIFT_U(y)  (y >> 11)
52 #define TEMPERING_SHIFT_S(y)  (y << 7)
53 #define TEMPERING_SHIFT_T(y)  (y << 15)
54 #define TEMPERING_SHIFT_L(y)  (y >> 18)
55
56 struct _GRand
57 {
58   guint32 mt[N]; /* the array for the state vector  */
59   guint mti; 
60   gboolean have_next_normal;
61   gdouble next_normal;
62 };
63
64 GRand*
65 g_rand_new_with_seed (guint32 seed)
66 {
67   GRand *rand = g_new0 (GRand, 1);
68   g_rand_set_seed (rand, seed);
69   return rand;
70 }
71
72 GRand* 
73 g_rand_new ()
74 {
75   guint32 seed = 0;
76   GTimeVal now;
77   FILE* dev_random = fopen("/dev/random", "rb");
78
79   if (dev_random)
80     {
81       if (fread (&seed, sizeof (seed), 1, dev_random) != 1)
82         seed = 0;
83       fclose (dev_random);
84     }
85
86   /* Using /dev/random alone makes the seed computable for the
87      outside. This might pose security problems somewhere. This should
88      yield better values */
89
90   g_get_current_time (&now);
91   seed ^= now.tv_sec ^ now.tv_usec;
92
93   return g_rand_new_with_seed (seed);
94 }
95
96 void
97 g_rand_free (GRand* rand)
98 {
99   g_return_if_fail (rand);
100
101   g_free (rand);
102 }
103
104 void
105 g_rand_set_seed (GRand* rand, guint32 seed)
106 {
107   g_return_if_fail (rand);
108
109   /* setting initial seeds to mt[N] using         */
110   /* the generator Line 25 of Table 1 in          */
111   /* [KNUTH 1981, The Art of Computer Programming */
112   /*    Vol. 2 (2nd Ed.), pp102]                  */
113   rand->mt[0]= seed & 0xffffffff;
114   for (rand->mti=1; rand->mti<N; rand->mti++)
115     rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]) & 0xffffffff;
116
117   rand->have_next_normal = FALSE;
118 }
119
120 guint32
121 g_rand_int (GRand* rand)
122 {
123   guint32 y;
124   static const guint32 mag01[2]={0x0, MATRIX_A};
125   /* mag01[x] = x * MATRIX_A  for x=0,1 */
126
127   g_return_val_if_fail (rand, 0);
128
129   if (rand->mti >= N) { /* generate N words at one time */
130     int kk;
131     
132     for (kk=0;kk<N-M;kk++) {
133       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
134       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
135     }
136     for (;kk<N-1;kk++) {
137       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
138       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
139     }
140     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
141     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
142     
143     rand->mti = 0;
144   }
145   
146   y = rand->mt[rand->mti++];
147   y ^= TEMPERING_SHIFT_U(y);
148   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
149   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
150   y ^= TEMPERING_SHIFT_L(y);
151   
152   return y; 
153 }
154
155 gint32 
156 g_rand_int_range (GRand* rand, gint32 min, gint32 max)
157 {
158   guint32 dist = max - min;
159   guint32 random;
160
161   g_return_val_if_fail (rand, min);
162   g_return_val_if_fail (max > min, min);
163
164   if (dist <= 0x10000L) /* 2^16 */
165     {
166       /* All tricks doing modulo calculations do not have a good
167          distribution -> We must use this slower method for maximal
168          quality, but this method is only good for (max - min) <= 2^16 */
169       
170       random = (gint32) g_rand_double_range (rand, 0, dist);
171       /* we'd rather use the following, if -lm is allowed later on:
172          random = (gint32) floor (g_rand_double_range (rand, 0, dist));  */
173     }
174   else
175     {
176       /* Now it's harder to make it right. We calculate the smallest m,
177          such that dist < 2 ^ m, then we calculate a random number in
178          [1..2^32-1] and rightshift it by 32 - m. Then we test, if it
179          is smaller than dist and if not, get a new number and so
180          forth until we get a number smaller than dist. We just return
181          this. */
182       guint32 border = 0x20000L; /* 2^17 */
183       guint right_shift = 15; /* 32 - 17 */
184
185       if (dist >= 0x80000000) /* in the case of dist > 2^31 our loop
186                                 below will be infinite */
187         {
188           right_shift = 0;
189         }
190       else
191         {
192           while (dist >= border) 
193             {
194               border <<= 1;
195               right_shift--;
196             }
197         }
198       do 
199         { 
200           random = g_rand_int (rand) >> right_shift; 
201         } while (random >= dist);
202     }
203   return min + random;
204 }
205
206 /* transform [0..2^32-1] -> [0..1) */
207 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386963e-10
208
209 gdouble 
210 g_rand_double (GRand* rand)
211 {                            
212   return g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
213 }
214
215 gdouble 
216 g_rand_double_range (GRand* rand, gdouble min, gdouble max)
217 {
218   return g_rand_int (rand) * ((max - min) * G_RAND_DOUBLE_TRANSFORM)  + min;
219 }
220
221
222 #if WE_REALLY_WANT_HAVE_MATH_LIB_LINKED
223 gdouble
224 g_rand_normal (GRand* rand, gdouble mean, gdouble standard_deviation)
225 {
226   /* For a description of the used algorithm see Knuth: "The Art of
227      Computer Programming", Vol.2, Second Edition, Page 117: Polar
228      method for normal deviates due to Box, Muller, Marsaglia */
229   gdouble normal;
230   g_return_val_if_fail (rand, 0);
231
232   if (rand->have_next_normal) 
233     {
234       rand->have_next_normal = FALSE;
235       normal = rand->next_normal;
236     }
237   else
238     {
239       gdouble u1;
240       gdouble u2 = g_rand_double_range (rand, -1, 1); 
241       gdouble s, f;
242       do 
243         { 
244           u1 = u2;
245           u2 = g_rand_double_range (rand, -1, 1);
246           s = u1 * u1 + u2 * u2;
247         } while (s >= 1.0);
248       f = sqrt (-2 * log (s) / s);
249       normal = u1 * f;
250       rand->next_normal = u2 * f;
251       rand->have_next_normal = TRUE;
252     }
253   return mean + normal * standard_deviation;
254 }
255 #endif
256
257 guint32
258 g_random_int (void)
259 {
260   guint32 result;
261   G_LOCK (global_random);
262   if (!global_random)
263     global_random = g_rand_new ();
264   
265   result = g_rand_int (global_random);
266   G_UNLOCK (global_random);
267   return result;
268 }
269
270 gint32 
271 g_random_int_range (gint32 min, gint32 max)
272 {
273   gint32 result;
274   G_LOCK (global_random);
275   if (!global_random)
276     global_random = g_rand_new ();
277   
278   result = g_rand_int_range (global_random, min, max);
279   G_UNLOCK (global_random);
280   return result;
281 }
282
283 gdouble 
284 g_random_double (void)
285 {
286   double result;
287   G_LOCK (global_random);
288   if (!global_random)
289     global_random = g_rand_new ();
290   
291   result = g_rand_double (global_random);
292   G_UNLOCK (global_random);
293   return result;
294 }
295
296 gdouble 
297 g_random_double_range (gdouble min, gdouble max)
298 {
299   double result;
300   G_LOCK (global_random);
301   if (!global_random)
302     global_random = g_rand_new ();
303  
304   result = g_rand_double_range (global_random, min, max);
305   G_UNLOCK (global_random);
306   return result;
307 }
308
309 #if WE_REALLY_WANT_HAVE_MATH_LIB_LINKED
310 gdouble
311 g_random_normal (gdouble mean, gdouble standard_deviation)
312 {
313   double result;
314   G_LOCK (global_random);
315   if (!global_random)
316     global_random = g_rand_new ();
317  
318   result = g_rand_normal (global_random, mean, standard_deviation);
319   G_UNLOCK (global_random);
320   return result;
321 }
322 #endif
323
324 void
325 g_random_set_seed (guint32 seed)
326 {
327   G_LOCK (global_random);
328   if (!global_random)
329     global_random = g_rand_new_with_seed (seed);
330   else
331     g_rand_set_seed (global_random, seed);
332   G_UNLOCK (global_random);
333 }
334