* io.c (id_encode): removed.
[ruby-svn.git] / random.c
blobf64084546a1eb3b43f3d3798913a612bf0dc13aa
1 /**********************************************************************
3 random.c -
5 $Author$
6 created at: Fri Dec 24 16:39:21 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 /*
13 This is based on trimmed version of MT19937. To get the original version,
14 contact <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html>.
16 The original copyright notice follows.
18 A C-program for MT19937, with initialization improved 2002/2/10.
19 Coded by Takuji Nishimura and Makoto Matsumoto.
20 This is a faster version by taking Shawn Cokus's optimization,
21 Matthe Bellew's simplification, Isaku Wada's real version.
23 Before using, initialize the state by using init_genrand(mt, seed)
24 or init_by_array(mt, init_key, key_length).
26 Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
27 All rights reserved.
29 Redistribution and use in source and binary forms, with or without
30 modification, are permitted provided that the following conditions
31 are met:
33 1. Redistributions of source code must retain the above copyright
34 notice, this list of conditions and the following disclaimer.
36 2. Redistributions in binary form must reproduce the above copyright
37 notice, this list of conditions and the following disclaimer in the
38 documentation and/or other materials provided with the distribution.
40 3. The names of its contributors may not be used to endorse or promote
41 products derived from this software without specific prior written
42 permission.
44 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
45 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
46 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
47 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
48 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
49 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
50 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
51 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
52 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
53 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
54 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
57 Any feedback is very welcome.
58 http://www.math.keio.ac.jp/matumoto/emt.html
59 email: matumoto@math.keio.ac.jp
62 /* Period parameters */
63 #define N 624
64 #define M 397
65 #define MATRIX_A 0x9908b0dfUL /* constant vector a */
66 #define UMASK 0x80000000UL /* most significant w-r bits */
67 #define LMASK 0x7fffffffUL /* least significant r bits */
68 #define MIXBITS(u,v) ( ((u) & UMASK) | ((v) & LMASK) )
69 #define TWIST(u,v) ((MIXBITS(u,v) >> 1) ^ ((v)&1UL ? MATRIX_A : 0UL))
71 struct MT {
72 unsigned long state[N]; /* the array for the state vector */
73 unsigned long *next;
74 int left;
77 #define genrand_initialized(mt) ((mt)->next != 0)
78 #define uninit_genrand(mt) ((mt)->next = 0)
80 /* initializes state[N] with a seed */
81 static void
82 init_genrand(struct MT *mt, unsigned long s)
84 int j;
85 mt->state[0] = s & 0xffffffffUL;
86 for (j=1; j<N; j++) {
87 mt->state[j] = (1812433253UL * (mt->state[j-1] ^ (mt->state[j-1] >> 30)) + j);
88 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
89 /* In the previous versions, MSBs of the seed affect */
90 /* only MSBs of the array state[]. */
91 /* 2002/01/09 modified by Makoto Matsumoto */
92 mt->state[j] &= 0xffffffffUL; /* for >32 bit machines */
94 mt->left = 1;
95 mt->next = mt->state + N - 1;
98 /* initialize by an array with array-length */
99 /* init_key is the array for initializing keys */
100 /* key_length is its length */
101 /* slight change for C++, 2004/2/26 */
102 static void
103 init_by_array(struct MT *mt, unsigned long init_key[], int key_length)
105 int i, j, k;
106 init_genrand(mt, 19650218UL);
107 i=1; j=0;
108 k = (N>key_length ? N : key_length);
109 for (; k; k--) {
110 mt->state[i] = (mt->state[i] ^ ((mt->state[i-1] ^ (mt->state[i-1] >> 30)) * 1664525UL))
111 + init_key[j] + j; /* non linear */
112 mt->state[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
113 i++; j++;
114 if (i>=N) { mt->state[0] = mt->state[N-1]; i=1; }
115 if (j>=key_length) j=0;
117 for (k=N-1; k; k--) {
118 mt->state[i] = (mt->state[i] ^ ((mt->state[i-1] ^ (mt->state[i-1] >> 30)) * 1566083941UL))
119 - i; /* non linear */
120 mt->state[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
121 i++;
122 if (i>=N) { mt->state[0] = mt->state[N-1]; i=1; }
125 mt->state[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
128 static void
129 next_state(struct MT *mt)
131 unsigned long *p = mt->state;
132 int j;
134 /* if init_genrand() has not been called, */
135 /* a default initial seed is used */
136 if (!genrand_initialized(mt)) init_genrand(mt, 5489UL);
138 mt->left = N;
139 mt->next = mt->state;
141 for (j=N-M+1; --j; p++)
142 *p = p[M] ^ TWIST(p[0], p[1]);
144 for (j=M; --j; p++)
145 *p = p[M-N] ^ TWIST(p[0], p[1]);
147 *p = p[M-N] ^ TWIST(p[0], mt->state[0]);
150 /* generates a random number on [0,0xffffffff]-interval */
151 static unsigned long
152 genrand_int32(struct MT *mt)
154 unsigned long y;
156 if (--mt->left <= 0) next_state(mt);
157 y = *mt->next++;
159 /* Tempering */
160 y ^= (y >> 11);
161 y ^= (y << 7) & 0x9d2c5680UL;
162 y ^= (y << 15) & 0xefc60000UL;
163 y ^= (y >> 18);
165 return y;
168 /* generates a random number on [0,1) with 53-bit resolution*/
169 static double
170 genrand_real(struct MT *mt)
172 unsigned long a=genrand_int32(mt)>>5, b=genrand_int32(mt)>>6;
173 return(a*67108864.0+b)*(1.0/9007199254740992.0);
175 /* These real versions are due to Isaku Wada, 2002/01/09 added */
177 #undef N
178 #undef M
180 /* These real versions are due to Isaku Wada, 2002/01/09 added */
182 #include "ruby/ruby.h"
184 #ifdef HAVE_UNISTD_H
185 #include <unistd.h>
186 #endif
187 #include <time.h>
188 #include <sys/types.h>
189 #include <sys/stat.h>
190 #ifdef HAVE_FCNTL_H
191 #include <fcntl.h>
192 #endif
194 #define DEFAULT_SEED_CNT 4
196 struct RandSeed {
197 VALUE value;
198 unsigned long initial[DEFAULT_SEED_CNT];
201 struct Random {
202 struct MT mt;
203 struct RandSeed seed;
206 static struct Random default_mt;
208 unsigned long
209 rb_genrand_int32(void)
211 return genrand_int32(&default_mt.mt);
214 double
215 rb_genrand_real(void)
217 return genrand_real(&default_mt.mt);
220 static VALUE
221 rand_init(struct MT *mt, VALUE vseed)
223 volatile VALUE seed;
224 long len;
225 unsigned long *buf;
227 seed = rb_to_int(vseed);
228 switch (TYPE(seed)) {
229 case T_FIXNUM:
230 len = sizeof(VALUE);
231 break;
232 case T_BIGNUM:
233 len = RBIGNUM_LEN(seed) * SIZEOF_BDIGITS;
234 if (len == 0)
235 len = 4;
236 break;
237 default:
238 rb_raise(rb_eTypeError, "failed to convert %s into Integer",
239 rb_obj_classname(vseed));
241 len = (len + 3) / 4; /* number of 32bit words */
242 buf = ALLOC_N(unsigned long, len); /* allocate longs for init_by_array */
243 memset(buf, 0, len * sizeof(long));
244 if (FIXNUM_P(seed)) {
245 buf[0] = FIX2ULONG(seed) & 0xffffffff;
246 #if SIZEOF_LONG > 4
247 buf[1] = FIX2ULONG(seed) >> 32;
248 #endif
250 else {
251 int i, j;
252 for (i = RBIGNUM_LEN(seed)-1; 0 <= i; i--) {
253 j = i * SIZEOF_BDIGITS / 4;
254 #if SIZEOF_BDIGITS < 4
255 buf[j] <<= SIZEOF_BDIGITS * 8;
256 #endif
257 buf[j] |= RBIGNUM_DIGITS(seed)[i];
260 while (1 < len && buf[len-1] == 0) {
261 len--;
263 if (len <= 1) {
264 init_genrand(mt, buf[0]);
266 else {
267 if (buf[len-1] == 1) /* remove leading-zero-guard */
268 len--;
269 init_by_array(mt, buf, len);
271 xfree(buf);
272 return seed;
275 #define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * sizeof(long))
277 static void
278 fill_random_seed(unsigned long seed[DEFAULT_SEED_CNT])
280 static int n = 0;
281 struct timeval tv;
282 int fd;
283 struct stat statbuf;
285 memset(seed, 0, DEFAULT_SEED_LEN);
287 #ifdef S_ISCHR
288 if ((fd = open("/dev/urandom", O_RDONLY
289 #ifdef O_NONBLOCK
290 |O_NONBLOCK
291 #endif
292 #ifdef O_NOCTTY
293 |O_NOCTTY
294 #endif
295 #ifdef O_NOFOLLOW
296 |O_NOFOLLOW
297 #endif
298 )) >= 0) {
299 if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
300 read(fd, seed, DEFAULT_SEED_LEN);
302 close(fd);
304 #endif
306 gettimeofday(&tv, 0);
307 seed[0] ^= tv.tv_usec;
308 seed[1] ^= tv.tv_sec;
309 seed[2] ^= getpid() ^ (n++ << 16);
310 seed[3] ^= (unsigned long)&seed;
313 static VALUE
314 make_seed_value(const void *ptr)
316 BDIGIT *digits;
317 NEWOBJ(big, struct RBignum);
318 OBJSETUP(big, rb_cBignum, T_BIGNUM);
320 RBIGNUM_SET_SIGN(big, 1);
321 rb_big_resize((VALUE)big, DEFAULT_SEED_LEN / SIZEOF_BDIGITS + 1);
322 digits = RBIGNUM_DIGITS(big);
324 MEMCPY((char *)RBIGNUM_DIGITS(big), ptr, char, DEFAULT_SEED_LEN);
326 /* set leading-zero-guard if need. */
327 digits[RBIGNUM_LEN(big)-1] = digits[RBIGNUM_LEN(big)-2] <= 1 ? 1 : 0;
329 return rb_big_norm((VALUE)big);
332 static VALUE
333 random_seed(void)
335 unsigned long buf[DEFAULT_SEED_CNT];
336 fill_random_seed(buf);
337 return make_seed_value(buf);
341 * call-seq:
342 * srand(number=0) => old_seed
344 * Seeds the pseudorandom number generator to the value of
345 * <i>number</i>.<code>to_i.abs</code>. If <i>number</i> is omitted
346 * or zero, seeds the generator using a combination of the time, the
347 * process id, and a sequence number. (This is also the behavior if
348 * <code>Kernel::rand</code> is called without previously calling
349 * <code>srand</code>, but without the sequence.) By setting the seed
350 * to a known value, scripts can be made deterministic during testing.
351 * The previous seed value is returned. Also see <code>Kernel::rand</code>.
354 static VALUE
355 rb_f_srand(int argc, VALUE *argv, VALUE obj)
357 VALUE seed, old;
359 rb_secure(4);
360 if (argc == 0) {
361 seed = random_seed();
363 else {
364 rb_scan_args(argc, argv, "01", &seed);
366 old = default_mt.seed.value;
367 default_mt.seed.value = rand_init(&default_mt.mt, seed);
369 return old;
372 static unsigned long
373 make_mask(unsigned long x)
375 x = x | x >> 1;
376 x = x | x >> 2;
377 x = x | x >> 4;
378 x = x | x >> 8;
379 x = x | x >> 16;
380 #if 4 < SIZEOF_LONG
381 x = x | x >> 32;
382 #endif
383 return x;
386 static unsigned long
387 limited_rand(struct MT *mt, unsigned long limit)
389 unsigned long mask = make_mask(limit);
390 int i;
391 unsigned long val;
393 retry:
394 val = 0;
395 for (i = SIZEOF_LONG/4-1; 0 <= i; i--) {
396 if (mask >> (i * 32)) {
397 val |= genrand_int32(mt) << (i * 32);
398 val &= mask;
399 if (limit < val)
400 goto retry;
403 return val;
406 static VALUE
407 limited_big_rand(struct MT *mt, struct RBignum *limit)
409 unsigned long mask, lim, rnd;
410 struct RBignum *val;
411 int i, len, boundary;
413 len = (RBIGNUM_LEN(limit) * SIZEOF_BDIGITS + 3) / 4;
414 val = (struct RBignum *)rb_big_clone((VALUE)limit);
415 RBIGNUM_SET_SIGN(val, 1);
416 #if SIZEOF_BDIGITS == 2
417 # define BIG_GET32(big,i) \
418 (RBIGNUM_DIGITS(big)[(i)*2] | \
419 ((i)*2+1 < RBIGNUM_LEN(big) ? \
420 (RBIGNUM_DIGITS(big)[(i)*2+1] << 16) : \
422 # define BIG_SET32(big,i,d) \
423 ((RBIGNUM_DIGITS(big)[(i)*2] = (d) & 0xffff), \
424 ((i)*2+1 < RBIGNUM_LEN(big) ? \
425 (RBIGNUM_DIGITS(big)[(i)*2+1] = (d) >> 16) : \
427 #else
428 /* SIZEOF_BDIGITS == 4 */
429 # define BIG_GET32(big,i) (RBIGNUM_DIGITS(big)[i])
430 # define BIG_SET32(big,i,d) (RBIGNUM_DIGITS(big)[i] = (d))
431 #endif
432 retry:
433 mask = 0;
434 boundary = 1;
435 for (i = len-1; 0 <= i; i--) {
436 lim = BIG_GET32(limit, i);
437 mask = mask ? 0xffffffff : make_mask(lim);
438 if (mask) {
439 rnd = genrand_int32(mt) & mask;
440 if (boundary) {
441 if (lim < rnd)
442 goto retry;
443 if (rnd < lim)
444 boundary = 0;
447 else {
448 rnd = 0;
450 BIG_SET32(val, i, rnd);
452 return rb_big_norm((VALUE)val);
456 * call-seq:
457 * rand(max=0) => number
459 * Converts <i>max</i> to an integer using max1 =
460 * max<code>.to_i.abs</code>. If the result is zero, returns a
461 * pseudorandom floating point number greater than or equal to 0.0 and
462 * less than 1.0. Otherwise, returns a pseudorandom integer greater
463 * than or equal to zero and less than max1. <code>Kernel::srand</code>
464 * may be used to ensure repeatable sequences of random numbers between
465 * different runs of the program. Ruby currently uses a modified
466 * Mersenne Twister with a period of 2**19937-1.
468 * srand 1234 #=> 0
469 * [ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
470 * [ rand(10), rand(1000) ] #=> [6, 817]
471 * srand 1234 #=> 1234
472 * [ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
475 static VALUE
476 rb_f_rand(int argc, VALUE *argv, VALUE obj)
478 VALUE vmax;
479 long val, max;
480 struct MT *mt = &default_mt.mt;
482 rb_scan_args(argc, argv, "01", &vmax);
483 if (!genrand_initialized(mt)) {
484 rand_init(mt, random_seed());
486 switch (TYPE(vmax)) {
487 case T_FLOAT:
488 if (RFLOAT_VALUE(vmax) <= LONG_MAX && RFLOAT_VALUE(vmax) >= LONG_MIN) {
489 max = (long)RFLOAT_VALUE(vmax);
490 break;
492 if (RFLOAT_VALUE(vmax) < 0)
493 vmax = rb_dbl2big(-RFLOAT_VALUE(vmax));
494 else
495 vmax = rb_dbl2big(RFLOAT_VALUE(vmax));
496 /* fall through */
497 case T_BIGNUM:
498 bignum:
500 struct RBignum *limit = (struct RBignum *)vmax;
501 if (!RBIGNUM_SIGN(limit)) {
502 limit = (struct RBignum *)rb_big_clone(vmax);
503 RBIGNUM_SET_SIGN(limit, 1);
505 limit = (struct RBignum *)rb_big_minus((VALUE)limit, INT2FIX(1));
506 if (FIXNUM_P((VALUE)limit)) {
507 if (FIX2LONG((VALUE)limit) == -1)
508 return DOUBLE2NUM(genrand_real(mt));
509 return LONG2NUM(limited_rand(mt, FIX2LONG((VALUE)limit)));
511 return limited_big_rand(mt, limit);
513 case T_NIL:
514 max = 0;
515 break;
516 default:
517 vmax = rb_Integer(vmax);
518 if (TYPE(vmax) == T_BIGNUM) goto bignum;
519 case T_FIXNUM:
520 max = FIX2LONG(vmax);
521 break;
524 if (max == 0) {
525 return DOUBLE2NUM(genrand_real(mt));
527 if (max < 0) max = -max;
528 val = limited_rand(mt, max-1);
529 return LONG2NUM(val);
532 void
533 Init_RandomSeed(void)
535 fill_random_seed(default_mt.seed.initial);
536 init_by_array(&default_mt.mt, default_mt.seed.initial, DEFAULT_SEED_CNT);
539 static void
540 Init_RandomSeed2(void)
542 default_mt.seed.value = make_seed_value(default_mt.seed.initial);
543 memset(default_mt.seed.initial, 0, DEFAULT_SEED_LEN);
546 void
547 rb_reset_random_seed(void)
549 uninit_genrand(&default_mt.mt);
550 default_mt.seed.value = INT2FIX(0);
553 void
554 Init_Random(void)
556 Init_RandomSeed2();
557 rb_define_global_function("srand", rb_f_srand, -1);
558 rb_define_global_function("rand", rb_f_rand, -1);
559 rb_global_variable(&default_mt.seed.value);