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