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(seed)
24 or init_by_array(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))
71 static unsigned long state
[N
]; /* the array for the state vector */
74 static unsigned long *next
;
76 /* initializes state[N] with a seed */
78 init_genrand(unsigned long s
)
81 state
[0]= s
& 0xffffffffUL
;
83 state
[j
] = (1812433253UL * (state
[j
-1] ^ (state
[j
-1] >> 30)) + j
);
84 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
85 /* In the previous versions, MSBs of the seed affect */
86 /* only MSBs of the array state[]. */
87 /* 2002/01/09 modified by Makoto Matsumoto */
88 state
[j
] &= 0xffffffffUL
; /* for >32 bit machines */
93 /* initialize by an array with array-length */
94 /* init_key is the array for initializing keys */
95 /* key_length is its length */
96 /* slight change for C++, 2004/2/26 */
98 init_by_array(unsigned long init_key
[], int key_length
)
101 init_genrand(19650218UL);
103 k
= (N
>key_length
? N
: key_length
);
105 state
[i
] = (state
[i
] ^ ((state
[i
-1] ^ (state
[i
-1] >> 30)) * 1664525UL))
106 + init_key
[j
] + j
; /* non linear */
107 state
[i
] &= 0xffffffffUL
; /* for WORDSIZE > 32 machines */
109 if (i
>=N
) { state
[0] = state
[N
-1]; i
=1; }
110 if (j
>=key_length
) j
=0;
112 for (k
=N
-1; k
; k
--) {
113 state
[i
] = (state
[i
] ^ ((state
[i
-1] ^ (state
[i
-1] >> 30)) * 1566083941UL))
114 - i
; /* non linear */
115 state
[i
] &= 0xffffffffUL
; /* for WORDSIZE > 32 machines */
117 if (i
>=N
) { state
[0] = state
[N
-1]; i
=1; }
120 state
[0] = 0x80000000UL
; /* MSB is 1; assuring non-zero initial array */
127 unsigned long *p
=state
;
130 /* if init_genrand() has not been called, */
131 /* a default initial seed is used */
132 if (initf
==0) init_genrand(5489UL);
137 for (j
=N
-M
+1; --j
; p
++)
138 *p
= p
[M
] ^ TWIST(p
[0], p
[1]);
141 *p
= p
[M
-N
] ^ TWIST(p
[0], p
[1]);
143 *p
= p
[M
-N
] ^ TWIST(p
[0], state
[0]);
146 /* generates a random number on [0,0xffffffff]-interval */
152 if (--left
== 0) next_state();
157 y
^= (y
<< 7) & 0x9d2c5680UL
;
158 y
^= (y
<< 15) & 0xefc60000UL
;
164 /* generates a random number on [0,1) with 53-bit resolution*/
168 unsigned long a
=genrand_int32()>>5, b
=genrand_int32()>>6;
169 return(a
*67108864.0+b
)*(1.0/9007199254740992.0);
171 /* These real versions are due to Isaku Wada, 2002/01/09 added */
176 /* These real versions are due to Isaku Wada, 2002/01/09 added */
178 #include "ruby/ruby.h"
184 #include <sys/types.h>
185 #include <sys/stat.h>
191 rb_genrand_int32(void)
193 return genrand_int32();
197 rb_genrand_real(void)
199 return genrand_real();
202 static int seed_initialized
= 0;
203 static VALUE saved_seed
= INT2FIX(0);
206 rand_init(VALUE vseed
)
213 seed
= rb_to_int(vseed
);
214 switch (TYPE(seed
)) {
219 len
= RBIGNUM_LEN(seed
) * SIZEOF_BDIGITS
;
224 rb_raise(rb_eTypeError
, "failed to convert %s into Integer",
225 rb_obj_classname(vseed
));
227 len
= (len
+ 3) / 4; /* number of 32bit words */
228 buf
= ALLOC_N(unsigned long, len
); /* allocate longs for init_by_array */
229 memset(buf
, 0, len
* sizeof(long));
230 if (FIXNUM_P(seed
)) {
231 buf
[0] = FIX2ULONG(seed
) & 0xffffffff;
233 buf
[1] = FIX2ULONG(seed
) >> 32;
238 for (i
= RBIGNUM_LEN(seed
)-1; 0 <= i
; i
--) {
239 j
= i
* SIZEOF_BDIGITS
/ 4;
240 #if SIZEOF_BDIGITS < 4
241 buf
[j
] <<= SIZEOF_BDIGITS
* 8;
243 buf
[j
] |= RBIGNUM_DIGITS(seed
)[i
];
246 while (1 < len
&& buf
[len
-1] == 0) {
250 init_genrand(buf
[0]);
253 if (buf
[len
-1] == 1) /* remove leading-zero-guard */
255 init_by_array(buf
, len
);
263 #define DEFAULT_SEED_LEN (4 * sizeof(long))
266 fill_random_seed(char *ptr
)
273 char *buf
= (char*)ptr
;
275 seed
= (unsigned long *)buf
;
277 memset(buf
, 0, DEFAULT_SEED_LEN
);
280 if ((fd
= open("/dev/urandom", O_RDONLY
291 if (fstat(fd
, &statbuf
) == 0 && S_ISCHR(statbuf
.st_mode
)) {
292 read(fd
, seed
, DEFAULT_SEED_LEN
);
298 gettimeofday(&tv
, 0);
299 seed
[0] ^= tv
.tv_usec
;
300 seed
[1] ^= tv
.tv_sec
;
301 seed
[2] ^= getpid() ^ (n
++ << 16);
302 seed
[3] ^= (unsigned long)&seed
;
306 make_seed_value(char *ptr
)
309 NEWOBJ(big
, struct RBignum
);
310 OBJSETUP(big
, rb_cBignum
, T_BIGNUM
);
312 RBIGNUM_SET_SIGN(big
, 1);
313 rb_big_resize((VALUE
)big
, DEFAULT_SEED_LEN
/ SIZEOF_BDIGITS
+ 1);
314 digits
= RBIGNUM_DIGITS(big
);
316 MEMCPY((char *)RBIGNUM_DIGITS(big
), ptr
, char, DEFAULT_SEED_LEN
);
318 /* set leading-zero-guard if need. */
319 digits
[RBIGNUM_LEN(big
)-1] = digits
[RBIGNUM_LEN(big
)-2] <= 1 ? 1 : 0;
321 return rb_big_norm((VALUE
)big
);
327 char buf
[DEFAULT_SEED_LEN
];
328 fill_random_seed(buf
);
329 return make_seed_value(buf
);
334 * srand(number=0) => old_seed
336 * Seeds the pseudorandom number generator to the value of
337 * <i>number</i>.<code>to_i.abs</code>. If <i>number</i> is omitted
338 * or zero, seeds the generator using a combination of the time, the
339 * process id, and a sequence number. (This is also the behavior if
340 * <code>Kernel::rand</code> is called without previously calling
341 * <code>srand</code>, but without the sequence.) By setting the seed
342 * to a known value, scripts can be made deterministic during testing.
343 * The previous seed value is returned. Also see <code>Kernel::rand</code>.
347 rb_f_srand(int argc
, VALUE
*argv
, VALUE obj
)
353 seed
= random_seed();
356 rb_scan_args(argc
, argv
, "01", &seed
);
358 old
= rand_init(seed
);
364 make_mask(unsigned long x
)
378 limited_rand(unsigned long limit
)
380 unsigned long mask
= make_mask(limit
);
386 for (i
= SIZEOF_LONG
/4-1; 0 <= i
; i
--) {
387 if (mask
>> (i
* 32)) {
388 val
|= genrand_int32() << (i
* 32);
398 limited_big_rand(struct RBignum
*limit
)
400 unsigned long mask
, lim
, rnd
;
402 int i
, len
, boundary
;
404 len
= (RBIGNUM_LEN(limit
) * SIZEOF_BDIGITS
+ 3) / 4;
405 val
= (struct RBignum
*)rb_big_clone((VALUE
)limit
);
406 RBIGNUM_SET_SIGN(val
, 1);
407 #if SIZEOF_BDIGITS == 2
408 # define BIG_GET32(big,i) \
409 (RBIGNUM_DIGITS(big)[(i)*2] | \
410 ((i)*2+1 < RBIGNUM_LEN(big) ? \
411 (RBIGNUM_DIGITS(big)[(i)*2+1] << 16) : \
413 # define BIG_SET32(big,i,d) \
414 ((RBIGNUM_DIGITS(big)[(i)*2] = (d) & 0xffff), \
415 ((i)*2+1 < RBIGNUM_LEN(big) ? \
416 (RBIGNUM_DIGITS(big)[(i)*2+1] = (d) >> 16) : \
419 /* SIZEOF_BDIGITS == 4 */
420 # define BIG_GET32(big,i) (RBIGNUM_DIGITS(big)[i])
421 # define BIG_SET32(big,i,d) (RBIGNUM_DIGITS(big)[i] = (d))
426 for (i
= len
-1; 0 <= i
; i
--) {
427 lim
= BIG_GET32(limit
, i
);
428 mask
= mask
? 0xffffffff : make_mask(lim
);
430 rnd
= genrand_int32() & mask
;
441 BIG_SET32(val
, i
, rnd
);
443 return rb_big_norm((VALUE
)val
);
448 * rand(max=0) => number
450 * Converts <i>max</i> to an integer using max1 =
451 * max<code>.to_i.abs</code>. If the result is zero, returns a
452 * pseudorandom floating point number greater than or equal to 0.0 and
453 * less than 1.0. Otherwise, returns a pseudorandom integer greater
454 * than or equal to zero and less than max1. <code>Kernel::srand</code>
455 * may be used to ensure repeatable sequences of random numbers between
456 * different runs of the program. Ruby currently uses a modified
457 * Mersenne Twister with a period of 2**19937-1.
460 * [ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
461 * [ rand(10), rand(1000) ] #=> [6, 817]
462 * srand 1234 #=> 1234
463 * [ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
467 rb_f_rand(int argc
, VALUE
*argv
, VALUE obj
)
472 rb_scan_args(argc
, argv
, "01", &vmax
);
473 if (!seed_initialized
) {
474 rand_init(random_seed());
476 switch (TYPE(vmax
)) {
478 if (RFLOAT_VALUE(vmax
) <= LONG_MAX
&& RFLOAT_VALUE(vmax
) >= LONG_MIN
) {
479 max
= (long)RFLOAT_VALUE(vmax
);
482 if (RFLOAT_VALUE(vmax
) < 0)
483 vmax
= rb_dbl2big(-RFLOAT_VALUE(vmax
));
485 vmax
= rb_dbl2big(RFLOAT_VALUE(vmax
));
490 struct RBignum
*limit
= (struct RBignum
*)vmax
;
491 if (!RBIGNUM_SIGN(limit
)) {
492 limit
= (struct RBignum
*)rb_big_clone(vmax
);
493 RBIGNUM_SET_SIGN(limit
, 1);
495 limit
= (struct RBignum
*)rb_big_minus((VALUE
)limit
, INT2FIX(1));
496 if (FIXNUM_P((VALUE
)limit
)) {
497 if (FIX2LONG((VALUE
)limit
) == -1)
498 return DOUBLE2NUM(genrand_real());
499 return LONG2NUM(limited_rand(FIX2LONG((VALUE
)limit
)));
501 return limited_big_rand(limit
);
507 vmax
= rb_Integer(vmax
);
508 if (TYPE(vmax
) == T_BIGNUM
) goto bignum
;
510 max
= FIX2LONG(vmax
);
515 return DOUBLE2NUM(genrand_real());
517 if (max
< 0) max
= -max
;
518 val
= limited_rand(max
-1);
519 return LONG2NUM(val
);
522 static char initial_seed
[DEFAULT_SEED_LEN
];
525 Init_RandomSeed(void)
527 fill_random_seed(initial_seed
);
528 init_by_array((unsigned long*)initial_seed
, DEFAULT_SEED_LEN
/sizeof(unsigned long));
529 seed_initialized
= 1;
533 Init_RandomSeed2(void)
535 saved_seed
= make_seed_value(initial_seed
);
536 memset(initial_seed
, 0, DEFAULT_SEED_LEN
);
540 rb_reset_random_seed(void)
542 seed_initialized
= 0;
543 saved_seed
= INT2FIX(0);
550 rb_define_global_function("srand", rb_f_srand
, -1);
551 rb_define_global_function("rand", rb_f_rand
, -1);
552 rb_global_variable(&saved_seed
);