Add type_data_ref_U() and use it in g_type_class_ref()
[glib.git] / glib / grand.c
blob8edcca3991ba89d5cd9047433bd8b5ec446934fc
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
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.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
25 * This code was adapted to glib by Sebastian Wilhelmi.
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/.
35 /*
36 * MT safe
39 #include "config.h"
41 #include <math.h>
42 #include <errno.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <sys/types.h>
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
50 #include "glib.h"
51 #include "gthreadprivate.h"
52 #include "galias.h"
54 #ifdef G_OS_WIN32
55 #include <process.h> /* For getpid() */
56 #endif
58 G_LOCK_DEFINE_STATIC (global_random);
59 static GRand* global_random = NULL;
61 /* Period parameters */
62 #define N 624
63 #define M 397
64 #define MATRIX_A 0x9908b0df /* constant vector a */
65 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
66 #define LOWER_MASK 0x7fffffff /* least significant r bits */
68 /* Tempering parameters */
69 #define TEMPERING_MASK_B 0x9d2c5680
70 #define TEMPERING_MASK_C 0xefc60000
71 #define TEMPERING_SHIFT_U(y) (y >> 11)
72 #define TEMPERING_SHIFT_S(y) (y << 7)
73 #define TEMPERING_SHIFT_T(y) (y << 15)
74 #define TEMPERING_SHIFT_L(y) (y >> 18)
76 static guint
77 get_random_version (void)
79 static gboolean initialized = FALSE;
80 static guint random_version;
82 if (!initialized)
84 const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
85 if (!version_string || version_string[0] == '\000' ||
86 strcmp (version_string, "2.2") == 0)
87 random_version = 22;
88 else if (strcmp (version_string, "2.0") == 0)
89 random_version = 20;
90 else
92 g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
93 version_string);
94 random_version = 22;
96 initialized = TRUE;
99 return random_version;
102 /* This is called from g_thread_init(). It's used to
103 * initialize some static data in a threadsafe way.
105 void
106 _g_rand_thread_init (void)
108 (void)get_random_version ();
111 struct _GRand
113 guint32 mt[N]; /* the array for the state vector */
114 guint mti;
118 * g_rand_new_with_seed:
119 * @seed: a value to initialize the random number generator.
121 * Creates a new random number generator initialized with @seed.
123 * Return value: the new #GRand.
125 GRand*
126 g_rand_new_with_seed (guint32 seed)
128 GRand *rand = g_new0 (GRand, 1);
129 g_rand_set_seed (rand, seed);
130 return rand;
134 * g_rand_new_with_seed_array:
135 * @seed: an array of seeds to initialize the random number generator.
136 * @seed_length: an array of seeds to initialize the random number generator.
138 * Creates a new random number generator initialized with @seed.
140 * Return value: the new #GRand.
142 * Since: 2.4
144 GRand*
145 g_rand_new_with_seed_array (const guint32 *seed, guint seed_length)
147 GRand *rand = g_new0 (GRand, 1);
148 g_rand_set_seed_array (rand, seed, seed_length);
149 return rand;
153 * g_rand_new:
155 * Creates a new random number generator initialized with a seed taken
156 * either from <filename>/dev/urandom</filename> (if existing) or from
157 * the current time (as a fallback).
159 * Return value: the new #GRand.
161 GRand*
162 g_rand_new (void)
164 guint32 seed[4];
165 GTimeVal now;
166 #ifdef G_OS_UNIX
167 static gboolean dev_urandom_exists = TRUE;
169 if (dev_urandom_exists)
171 FILE* dev_urandom;
175 errno = 0;
176 dev_urandom = fopen("/dev/urandom", "rb");
178 while G_UNLIKELY (errno == EINTR);
180 if (dev_urandom)
182 int r;
184 setvbuf (dev_urandom, NULL, _IONBF, 0);
187 errno = 0;
188 r = fread (seed, sizeof (seed), 1, dev_urandom);
190 while G_UNLIKELY (errno == EINTR);
192 if (r != 1)
193 dev_urandom_exists = FALSE;
195 fclose (dev_urandom);
197 else
198 dev_urandom_exists = FALSE;
200 #else
201 static gboolean dev_urandom_exists = FALSE;
202 #endif
204 if (!dev_urandom_exists)
206 g_get_current_time (&now);
207 seed[0] = now.tv_sec;
208 seed[1] = now.tv_usec;
209 seed[2] = getpid ();
210 #ifdef G_OS_UNIX
211 seed[3] = getppid ();
212 #else
213 seed[3] = 0;
214 #endif
217 return g_rand_new_with_seed_array (seed, 4);
221 * g_rand_free:
222 * @rand_: a #GRand.
224 * Frees the memory allocated for the #GRand.
226 void
227 g_rand_free (GRand* rand)
229 g_return_if_fail (rand != NULL);
231 g_free (rand);
235 * g_rand_copy:
236 * @rand_: a #GRand.
238 * Copies a #GRand into a new one with the same exact state as before.
239 * This way you can take a snapshot of the random number generator for
240 * replaying later.
242 * Return value: the new #GRand.
244 * Since: 2.4
246 GRand *
247 g_rand_copy (GRand* rand)
249 GRand* new_rand;
251 g_return_val_if_fail (rand != NULL, NULL);
253 new_rand = g_new0 (GRand, 1);
254 memcpy (new_rand, rand, sizeof (GRand));
256 return new_rand;
260 * g_rand_set_seed:
261 * @rand_: a #GRand.
262 * @seed: a value to reinitialize the random number generator.
264 * Sets the seed for the random number generator #GRand to @seed.
266 void
267 g_rand_set_seed (GRand* rand, guint32 seed)
269 g_return_if_fail (rand != NULL);
271 switch (get_random_version ())
273 case 20:
274 /* setting initial seeds to mt[N] using */
275 /* the generator Line 25 of Table 1 in */
276 /* [KNUTH 1981, The Art of Computer Programming */
277 /* Vol. 2 (2nd Ed.), pp102] */
279 if (seed == 0) /* This would make the PRNG procude only zeros */
280 seed = 0x6b842128; /* Just set it to another number */
282 rand->mt[0]= seed;
283 for (rand->mti=1; rand->mti<N; rand->mti++)
284 rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
286 break;
287 case 22:
288 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
289 /* In the previous version (see above), MSBs of the */
290 /* seed affect only MSBs of the array mt[]. */
292 rand->mt[0]= seed;
293 for (rand->mti=1; rand->mti<N; rand->mti++)
294 rand->mt[rand->mti] = 1812433253UL *
295 (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti;
296 break;
297 default:
298 g_assert_not_reached ();
303 * g_rand_set_seed_array:
304 * @rand_: a #GRand.
305 * @seed: array to initialize with
306 * @seed_length: length of array
308 * Initializes the random number generator by an array of
309 * longs. Array can be of arbitrary size, though only the
310 * first 624 values are taken. This function is useful
311 * if you have many low entropy seeds, or if you require more then
312 * 32bits of actual entropy for your application.
314 * Since: 2.4
316 void
317 g_rand_set_seed_array (GRand* rand, const guint32 *seed, guint seed_length)
319 int i, j, k;
321 g_return_if_fail (rand != NULL);
322 g_return_if_fail (seed_length >= 1);
324 g_rand_set_seed (rand, 19650218UL);
326 i=1; j=0;
327 k = (N>seed_length ? N : seed_length);
328 for (; k; k--)
330 rand->mt[i] = (rand->mt[i] ^
331 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
332 + seed[j] + j; /* non linear */
333 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
334 i++; j++;
335 if (i>=N)
337 rand->mt[0] = rand->mt[N-1];
338 i=1;
340 if (j>=seed_length)
341 j=0;
343 for (k=N-1; k; k--)
345 rand->mt[i] = (rand->mt[i] ^
346 ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
347 - i; /* non linear */
348 rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
349 i++;
350 if (i>=N)
352 rand->mt[0] = rand->mt[N-1];
353 i=1;
357 rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
361 * g_rand_int:
362 * @rand_: a #GRand.
364 * Returns the next random #guint32 from @rand_ equally distributed over
365 * the range [0..2^32-1].
367 * Return value: A random number.
369 guint32
370 g_rand_int (GRand* rand)
372 guint32 y;
373 static const guint32 mag01[2]={0x0, MATRIX_A};
374 /* mag01[x] = x * MATRIX_A for x=0,1 */
376 g_return_val_if_fail (rand != NULL, 0);
378 if (rand->mti >= N) { /* generate N words at one time */
379 int kk;
381 for (kk=0;kk<N-M;kk++) {
382 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
383 rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
385 for (;kk<N-1;kk++) {
386 y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
387 rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
389 y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
390 rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
392 rand->mti = 0;
395 y = rand->mt[rand->mti++];
396 y ^= TEMPERING_SHIFT_U(y);
397 y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
398 y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
399 y ^= TEMPERING_SHIFT_L(y);
401 return y;
404 /* transform [0..2^32] -> [0..1] */
405 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
408 * g_rand_int_range:
409 * @rand_: a #GRand.
410 * @begin: lower closed bound of the interval.
411 * @end: upper open bound of the interval.
413 * Returns the next random #gint32 from @rand_ equally distributed over
414 * the range [@begin..@end-1].
416 * Return value: A random number.
418 gint32
419 g_rand_int_range (GRand* rand, gint32 begin, gint32 end)
421 guint32 dist = end - begin;
422 guint32 random;
424 g_return_val_if_fail (rand != NULL, begin);
425 g_return_val_if_fail (end > begin, begin);
427 switch (get_random_version ())
429 case 20:
430 if (dist <= 0x10000L) /* 2^16 */
432 /* This method, which only calls g_rand_int once is only good
433 * for (end - begin) <= 2^16, because we only have 32 bits set
434 * from the one call to g_rand_int (). */
436 /* we are using (trans + trans * trans), because g_rand_int only
437 * covers [0..2^32-1] and thus g_rand_int * trans only covers
438 * [0..1-2^-32], but the biggest double < 1 is 1-2^-52.
441 gdouble double_rand = g_rand_int (rand) *
442 (G_RAND_DOUBLE_TRANSFORM +
443 G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
445 random = (gint32) (double_rand * dist);
447 else
449 /* Now we use g_rand_double_range (), which will set 52 bits for
450 us, so that it is safe to round and still get a decent
451 distribution */
452 random = (gint32) g_rand_double_range (rand, 0, dist);
454 break;
455 case 22:
456 if (dist == 0)
457 random = 0;
458 else
460 /* maxvalue is set to the predecessor of the greatest
461 * multiple of dist less or equal 2^32. */
462 guint32 maxvalue;
463 if (dist <= 0x80000000u) /* 2^31 */
465 /* maxvalue = 2^32 - 1 - (2^32 % dist) */
466 guint32 leftover = (0x80000000u % dist) * 2;
467 if (leftover >= dist) leftover -= dist;
468 maxvalue = 0xffffffffu - leftover;
470 else
471 maxvalue = dist - 1;
474 random = g_rand_int (rand);
475 while (random > maxvalue);
477 random %= dist;
479 break;
480 default:
481 random = 0; /* Quiet GCC */
482 g_assert_not_reached ();
485 return begin + random;
489 * g_rand_double:
490 * @rand_: a #GRand.
492 * Returns the next random #gdouble from @rand_ equally distributed over
493 * the range [0..1).
495 * Return value: A random number.
497 gdouble
498 g_rand_double (GRand* rand)
500 /* We set all 52 bits after the point for this, not only the first
501 32. Thats why we need two calls to g_rand_int */
502 gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
503 retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
505 /* The following might happen due to very bad rounding luck, but
506 * actually this should be more than rare, we just try again then */
507 if (retval >= 1.0)
508 return g_rand_double (rand);
510 return retval;
514 * g_rand_double_range:
515 * @rand_: a #GRand.
516 * @begin: lower closed bound of the interval.
517 * @end: upper open bound of the interval.
519 * Returns the next random #gdouble from @rand_ equally distributed over
520 * the range [@begin..@end).
522 * Return value: A random number.
524 gdouble
525 g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
527 return g_rand_double (rand) * (end - begin) + begin;
531 * g_random_int:
533 * Return a random #guint32 equally distributed over the range
534 * [0..2^32-1].
536 * Return value: A random number.
538 guint32
539 g_random_int (void)
541 guint32 result;
542 G_LOCK (global_random);
543 if (!global_random)
544 global_random = g_rand_new ();
546 result = g_rand_int (global_random);
547 G_UNLOCK (global_random);
548 return result;
552 * g_random_int_range:
553 * @begin: lower closed bound of the interval.
554 * @end: upper open bound of the interval.
556 * Returns a random #gint32 equally distributed over the range
557 * [@begin..@end-1].
559 * Return value: A random number.
561 gint32
562 g_random_int_range (gint32 begin, gint32 end)
564 gint32 result;
565 G_LOCK (global_random);
566 if (!global_random)
567 global_random = g_rand_new ();
569 result = g_rand_int_range (global_random, begin, end);
570 G_UNLOCK (global_random);
571 return result;
575 * g_random_double:
577 * Returns a random #gdouble equally distributed over the range [0..1).
579 * Return value: A random number.
581 gdouble
582 g_random_double (void)
584 double result;
585 G_LOCK (global_random);
586 if (!global_random)
587 global_random = g_rand_new ();
589 result = g_rand_double (global_random);
590 G_UNLOCK (global_random);
591 return result;
595 * g_random_double_range:
596 * @begin: lower closed bound of the interval.
597 * @end: upper open bound of the interval.
599 * Returns a random #gdouble equally distributed over the range [@begin..@end).
601 * Return value: A random number.
603 gdouble
604 g_random_double_range (gdouble begin, gdouble end)
606 double result;
607 G_LOCK (global_random);
608 if (!global_random)
609 global_random = g_rand_new ();
611 result = g_rand_double_range (global_random, begin, end);
612 G_UNLOCK (global_random);
613 return result;
617 * g_random_set_seed:
618 * @seed: a value to reinitialize the global random number generator.
620 * Sets the seed for the global random number generator, which is used
621 * by the <function>g_random_*</function> functions, to @seed.
623 void
624 g_random_set_seed (guint32 seed)
626 G_LOCK (global_random);
627 if (!global_random)
628 global_random = g_rand_new_with_seed (seed);
629 else
630 g_rand_set_seed (global_random, seed);
631 G_UNLOCK (global_random);
635 #define __G_RAND_C__
636 #include "galiasdef.c"