1 /**********************************************************************
6 created at: Fri Dec 24 16:39:21 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
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,
29 Redistribution and use in source and binary forms, with or without
30 modification, are permitted provided that the following conditions
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
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 */
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))
72 unsigned long state
[N
]; /* the array for the state vector */
77 #define genrand_initialized(mt) ((mt)->next != 0)
78 #define uninit_genrand(mt) ((mt)->next = 0)
80 /* initializes state[N] with a seed */
82 init_genrand(struct MT
*mt
, unsigned long s
)
85 mt
->state
[0] = s
& 0xffffffffUL
;
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 */
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 */
103 init_by_array(struct MT
*mt
, unsigned long init_key
[], int key_length
)
106 init_genrand(mt
, 19650218UL);
108 k
= (N
>key_length
? N
: key_length
);
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 */
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 */
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 */
129 next_state(struct MT
*mt
)
131 unsigned long *p
= mt
->state
;
134 /* if init_genrand() has not been called, */
135 /* a default initial seed is used */
136 if (!genrand_initialized(mt
)) init_genrand(mt
, 5489UL);
139 mt
->next
= mt
->state
;
141 for (j
=N
-M
+1; --j
; p
++)
142 *p
= p
[M
] ^ TWIST(p
[0], p
[1]);
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 */
152 genrand_int32(struct MT
*mt
)
156 if (--mt
->left
<= 0) next_state(mt
);
161 y
^= (y
<< 7) & 0x9d2c5680UL
;
162 y
^= (y
<< 15) & 0xefc60000UL
;
168 /* generates a random number on [0,1) with 53-bit resolution*/
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 */
180 /* These real versions are due to Isaku Wada, 2002/01/09 added */
182 #include "ruby/ruby.h"
188 #include <sys/types.h>
189 #include <sys/stat.h>
194 #define DEFAULT_SEED_CNT 4
198 unsigned long initial
[DEFAULT_SEED_CNT
];
203 struct RandSeed seed
;
206 static struct Random default_mt
;
209 rb_genrand_int32(void)
211 return genrand_int32(&default_mt
.mt
);
215 rb_genrand_real(void)
217 return genrand_real(&default_mt
.mt
);
221 rand_init(struct MT
*mt
, VALUE vseed
)
227 seed
= rb_to_int(vseed
);
228 switch (TYPE(seed
)) {
233 len
= RBIGNUM_LEN(seed
) * SIZEOF_BDIGITS
;
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;
247 buf
[1] = FIX2ULONG(seed
) >> 32;
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;
257 buf
[j
] |= RBIGNUM_DIGITS(seed
)[i
];
260 while (1 < len
&& buf
[len
-1] == 0) {
264 init_genrand(mt
, buf
[0]);
267 if (buf
[len
-1] == 1) /* remove leading-zero-guard */
269 init_by_array(mt
, buf
, len
);
275 #define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * sizeof(long))
278 fill_random_seed(unsigned long seed
[DEFAULT_SEED_CNT
])
285 memset(seed
, 0, DEFAULT_SEED_LEN
);
288 if ((fd
= open("/dev/urandom", O_RDONLY
299 if (fstat(fd
, &statbuf
) == 0 && S_ISCHR(statbuf
.st_mode
)) {
300 read(fd
, seed
, DEFAULT_SEED_LEN
);
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
;
314 make_seed_value(const void *ptr
)
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
);
335 unsigned long buf
[DEFAULT_SEED_CNT
];
336 fill_random_seed(buf
);
337 return make_seed_value(buf
);
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>.
355 rb_f_srand(int argc
, VALUE
*argv
, VALUE obj
)
361 seed
= random_seed();
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
);
373 make_mask(unsigned long x
)
387 limited_rand(struct MT
*mt
, unsigned long limit
)
389 unsigned long mask
= make_mask(limit
);
395 for (i
= SIZEOF_LONG
/4-1; 0 <= i
; i
--) {
396 if (mask
>> (i
* 32)) {
397 val
|= genrand_int32(mt
) << (i
* 32);
407 limited_big_rand(struct MT
*mt
, struct RBignum
*limit
)
409 unsigned long mask
, lim
, rnd
;
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) : \
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))
435 for (i
= len
-1; 0 <= i
; i
--) {
436 lim
= BIG_GET32(limit
, i
);
437 mask
= mask
? 0xffffffff : make_mask(lim
);
439 rnd
= genrand_int32(mt
) & mask
;
450 BIG_SET32(val
, i
, rnd
);
452 return rb_big_norm((VALUE
)val
);
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.
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]
476 rb_f_rand(int argc
, VALUE
*argv
, VALUE obj
)
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
)) {
488 if (RFLOAT_VALUE(vmax
) <= LONG_MAX
&& RFLOAT_VALUE(vmax
) >= LONG_MIN
) {
489 max
= (long)RFLOAT_VALUE(vmax
);
492 if (RFLOAT_VALUE(vmax
) < 0)
493 vmax
= rb_dbl2big(-RFLOAT_VALUE(vmax
));
495 vmax
= rb_dbl2big(RFLOAT_VALUE(vmax
));
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
);
517 vmax
= rb_Integer(vmax
);
518 if (TYPE(vmax
) == T_BIGNUM
) goto bignum
;
520 max
= FIX2LONG(vmax
);
525 return DOUBLE2NUM(genrand_real(mt
));
527 if (max
< 0) max
= -max
;
528 val
= limited_rand(mt
, max
-1);
529 return LONG2NUM(val
);
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
);
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
);
547 rb_reset_random_seed(void)
549 uninit_genrand(&default_mt
.mt
);
550 default_mt
.seed
.value
= INT2FIX(0);
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
);