PageRenderTime 60ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/random.c

https://github.com/diabolo/ruby
C | 1239 lines | 938 code | 113 blank | 188 comment | 160 complexity | 4c99ea2beca5844c7d3d2a56760607ef MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause
  1. /**********************************************************************
  2. random.c -
  3. $Author$
  4. created at: Fri Dec 24 16:39:21 JST 1993
  5. Copyright (C) 1993-2007 Yukihiro Matsumoto
  6. **********************************************************************/
  7. /*
  8. This is based on trimmed version of MT19937. To get the original version,
  9. contact <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html>.
  10. The original copyright notice follows.
  11. A C-program for MT19937, with initialization improved 2002/2/10.
  12. Coded by Takuji Nishimura and Makoto Matsumoto.
  13. This is a faster version by taking Shawn Cokus's optimization,
  14. Matthe Bellew's simplification, Isaku Wada's real version.
  15. Before using, initialize the state by using init_genrand(mt, seed)
  16. or init_by_array(mt, init_key, key_length).
  17. Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  18. All rights reserved.
  19. Redistribution and use in source and binary forms, with or without
  20. modification, are permitted provided that the following conditions
  21. are met:
  22. 1. Redistributions of source code must retain the above copyright
  23. notice, this list of conditions and the following disclaimer.
  24. 2. Redistributions in binary form must reproduce the above copyright
  25. notice, this list of conditions and the following disclaimer in the
  26. documentation and/or other materials provided with the distribution.
  27. 3. The names of its contributors may not be used to endorse or promote
  28. products derived from this software without specific prior written
  29. permission.
  30. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  31. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  32. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  33. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  35. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  36. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  37. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  38. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  39. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  40. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41. Any feedback is very welcome.
  42. http://www.math.keio.ac.jp/matumoto/emt.html
  43. email: matumoto@math.keio.ac.jp
  44. */
  45. #include "ruby/ruby.h"
  46. #include <limits.h>
  47. #ifdef HAVE_UNISTD_H
  48. #include <unistd.h>
  49. #endif
  50. #include <time.h>
  51. #include <sys/types.h>
  52. #include <sys/stat.h>
  53. #ifdef HAVE_FCNTL_H
  54. #include <fcntl.h>
  55. #endif
  56. #include <math.h>
  57. #include <errno.h>
  58. #ifdef _WIN32
  59. # if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0400
  60. # undef _WIN32_WINNT
  61. # define _WIN32_WINNT 0x400
  62. # undef __WINCRYPT_H__
  63. # endif
  64. #include <wincrypt.h>
  65. #endif
  66. typedef int int_must_be_32bit_at_least[sizeof(int) * CHAR_BIT < 32 ? -1 : 1];
  67. /* Period parameters */
  68. #define N 624
  69. #define M 397
  70. #define MATRIX_A 0x9908b0dfU /* constant vector a */
  71. #define UMASK 0x80000000U /* most significant w-r bits */
  72. #define LMASK 0x7fffffffU /* least significant r bits */
  73. #define MIXBITS(u,v) ( ((u) & UMASK) | ((v) & LMASK) )
  74. #define TWIST(u,v) ((MIXBITS(u,v) >> 1) ^ ((v)&1U ? MATRIX_A : 0U))
  75. enum {MT_MAX_STATE = N};
  76. struct MT {
  77. /* assume int is enough to store 32bits */
  78. unsigned int state[N]; /* the array for the state vector */
  79. unsigned int *next;
  80. int left;
  81. };
  82. #define genrand_initialized(mt) ((mt)->next != 0)
  83. #define uninit_genrand(mt) ((mt)->next = 0)
  84. /* initializes state[N] with a seed */
  85. static void
  86. init_genrand(struct MT *mt, unsigned int s)
  87. {
  88. int j;
  89. mt->state[0] = s & 0xffffffffU;
  90. for (j=1; j<N; j++) {
  91. mt->state[j] = (1812433253U * (mt->state[j-1] ^ (mt->state[j-1] >> 30)) + j);
  92. /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  93. /* In the previous versions, MSBs of the seed affect */
  94. /* only MSBs of the array state[]. */
  95. /* 2002/01/09 modified by Makoto Matsumoto */
  96. mt->state[j] &= 0xffffffff; /* for >32 bit machines */
  97. }
  98. mt->left = 1;
  99. mt->next = mt->state + N;
  100. }
  101. /* initialize by an array with array-length */
  102. /* init_key is the array for initializing keys */
  103. /* key_length is its length */
  104. /* slight change for C++, 2004/2/26 */
  105. static void
  106. init_by_array(struct MT *mt, unsigned int init_key[], int key_length)
  107. {
  108. int i, j, k;
  109. init_genrand(mt, 19650218U);
  110. i=1; j=0;
  111. k = (N>key_length ? N : key_length);
  112. for (; k; k--) {
  113. mt->state[i] = (mt->state[i] ^ ((mt->state[i-1] ^ (mt->state[i-1] >> 30)) * 1664525U))
  114. + init_key[j] + j; /* non linear */
  115. mt->state[i] &= 0xffffffffU; /* for WORDSIZE > 32 machines */
  116. i++; j++;
  117. if (i>=N) { mt->state[0] = mt->state[N-1]; i=1; }
  118. if (j>=key_length) j=0;
  119. }
  120. for (k=N-1; k; k--) {
  121. mt->state[i] = (mt->state[i] ^ ((mt->state[i-1] ^ (mt->state[i-1] >> 30)) * 1566083941U))
  122. - i; /* non linear */
  123. mt->state[i] &= 0xffffffffU; /* for WORDSIZE > 32 machines */
  124. i++;
  125. if (i>=N) { mt->state[0] = mt->state[N-1]; i=1; }
  126. }
  127. mt->state[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
  128. }
  129. static void
  130. next_state(struct MT *mt)
  131. {
  132. unsigned int *p = mt->state;
  133. int j;
  134. mt->left = N;
  135. mt->next = mt->state;
  136. for (j=N-M+1; --j; p++)
  137. *p = p[M] ^ TWIST(p[0], p[1]);
  138. for (j=M; --j; p++)
  139. *p = p[M-N] ^ TWIST(p[0], p[1]);
  140. *p = p[M-N] ^ TWIST(p[0], mt->state[0]);
  141. }
  142. /* generates a random number on [0,0xffffffff]-interval */
  143. static unsigned int
  144. genrand_int32(struct MT *mt)
  145. {
  146. /* mt must be initialized */
  147. unsigned int y;
  148. if (--mt->left <= 0) next_state(mt);
  149. y = *mt->next++;
  150. /* Tempering */
  151. y ^= (y >> 11);
  152. y ^= (y << 7) & 0x9d2c5680;
  153. y ^= (y << 15) & 0xefc60000;
  154. y ^= (y >> 18);
  155. return y;
  156. }
  157. /* generates a random number on [0,1) with 53-bit resolution*/
  158. static double
  159. genrand_real(struct MT *mt)
  160. {
  161. /* mt must be initialized */
  162. unsigned int a = genrand_int32(mt)>>5, b = genrand_int32(mt)>>6;
  163. return(a*67108864.0+b)*(1.0/9007199254740992.0);
  164. }
  165. /* generates a random number on [0,1] with 53-bit resolution*/
  166. static double int_pair_to_real_inclusive(unsigned int a, unsigned int b);
  167. static double
  168. genrand_real2(struct MT *mt)
  169. {
  170. /* mt must be initialized */
  171. unsigned int a = genrand_int32(mt), b = genrand_int32(mt);
  172. return int_pair_to_real_inclusive(a, b);
  173. }
  174. /* These real versions are due to Isaku Wada, 2002/01/09 added */
  175. #undef N
  176. #undef M
  177. /* These real versions are due to Isaku Wada, 2002/01/09 added */
  178. typedef struct {
  179. VALUE seed;
  180. struct MT mt;
  181. } rb_random_t;
  182. #define DEFAULT_SEED_CNT 4
  183. static rb_random_t default_rand;
  184. static VALUE rand_init(struct MT *mt, VALUE vseed);
  185. static VALUE random_seed(void);
  186. static struct MT *
  187. default_mt(void)
  188. {
  189. rb_random_t *r = &default_rand;
  190. struct MT *mt = &r->mt;
  191. if (!genrand_initialized(mt)) {
  192. r->seed = rand_init(mt, random_seed());
  193. }
  194. return mt;
  195. }
  196. unsigned int
  197. rb_genrand_int32(void)
  198. {
  199. struct MT *mt = default_mt();
  200. return genrand_int32(mt);
  201. }
  202. double
  203. rb_genrand_real(void)
  204. {
  205. struct MT *mt = default_mt();
  206. return genrand_real(mt);
  207. }
  208. #define BDIGITS(x) (RBIGNUM_DIGITS(x))
  209. #define BITSPERDIG (SIZEOF_BDIGITS*CHAR_BIT)
  210. #define BIGRAD ((BDIGIT_DBL)1 << BITSPERDIG)
  211. #define DIGSPERINT (SIZEOF_INT/SIZEOF_BDIGITS)
  212. #define BIGUP(x) ((BDIGIT_DBL)(x) << BITSPERDIG)
  213. #define BIGDN(x) RSHIFT(x,BITSPERDIG)
  214. #define BIGLO(x) ((BDIGIT)((x) & (BIGRAD-1)))
  215. #define BDIGMAX ((BDIGIT)-1)
  216. #define roomof(n, m) (int)(((n)+(m)-1) / (m))
  217. #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
  218. #define SIZEOF_INT32 (31/CHAR_BIT + 1)
  219. static double
  220. int_pair_to_real_inclusive(unsigned int a, unsigned int b)
  221. {
  222. VALUE x = rb_big_new(roomof(64, BITSPERDIG), 1);
  223. VALUE m = rb_big_new(roomof(53, BITSPERDIG), 1);
  224. BDIGIT *xd = BDIGITS(x);
  225. int i = 0;
  226. double r;
  227. xd[i++] = (BDIGIT)b;
  228. #if BITSPERDIG < 32
  229. xd[i++] = (BDIGIT)(b >> BITSPERDIG);
  230. #endif
  231. xd[i++] = (BDIGIT)a;
  232. #if BITSPERDIG < 32
  233. xd[i++] = (BDIGIT)(a >> BITSPERDIG);
  234. #endif
  235. xd = BDIGITS(m);
  236. #if BITSPERDIG < 53
  237. MEMZERO(xd, BDIGIT, roomof(53, BITSPERDIG) - 1);
  238. #endif
  239. xd[53 / BITSPERDIG] = 1 << 53 % BITSPERDIG;
  240. xd[0] |= 1;
  241. x = rb_big_mul(x, m);
  242. if (FIXNUM_P(x)) {
  243. #if CHAR_BIT * SIZEOF_LONG > 64
  244. r = (double)(FIX2ULONG(x) >> 64);
  245. #else
  246. return 0.0;
  247. #endif
  248. }
  249. else {
  250. #if 64 % BITSPERDIG == 0
  251. long len = RBIGNUM_LEN(x);
  252. xd = BDIGITS(x);
  253. MEMMOVE(xd, xd + 64 / BITSPERDIG, BDIGIT, len - 64 / BITSPERDIG);
  254. MEMZERO(xd + len - 64 / BITSPERDIG, BDIGIT, 64 / BITSPERDIG);
  255. r = rb_big2dbl(x);
  256. #else
  257. x = rb_big_rshift(x, INT2FIX(64));
  258. if (FIXNUM_P(x)) {
  259. r = (double)FIX2ULONG(x);
  260. }
  261. else {
  262. r = rb_big2dbl(x);
  263. }
  264. #endif
  265. }
  266. return ldexp(r, -53);
  267. }
  268. VALUE rb_cRandom;
  269. #define id_minus '-'
  270. #define id_plus '+'
  271. /* :nodoc: */
  272. static void
  273. random_mark(void *ptr)
  274. {
  275. rb_gc_mark(((rb_random_t *)ptr)->seed);
  276. }
  277. #define random_free RUBY_TYPED_DEFAULT_FREE
  278. static size_t
  279. random_memsize(const void *ptr)
  280. {
  281. return ptr ? sizeof(rb_random_t) : 0;
  282. }
  283. static const rb_data_type_t random_data_type = {
  284. "random",
  285. random_mark,
  286. random_free,
  287. random_memsize,
  288. };
  289. static rb_random_t *
  290. get_rnd(VALUE obj)
  291. {
  292. rb_random_t *ptr;
  293. TypedData_Get_Struct(obj, rb_random_t, &random_data_type, ptr);
  294. return ptr;
  295. }
  296. /* :nodoc: */
  297. static VALUE
  298. random_alloc(VALUE klass)
  299. {
  300. rb_random_t *rnd;
  301. VALUE obj = TypedData_Make_Struct(klass, rb_random_t, &random_data_type, rnd);
  302. rnd->seed = INT2FIX(0);
  303. return obj;
  304. }
  305. static VALUE
  306. rand_init(struct MT *mt, VALUE vseed)
  307. {
  308. volatile VALUE seed;
  309. long blen = 0;
  310. long fixnum_seed;
  311. int i, j, len;
  312. unsigned int buf0[SIZEOF_LONG / SIZEOF_INT32 * 4], *buf = buf0;
  313. seed = rb_to_int(vseed);
  314. switch (TYPE(seed)) {
  315. case T_FIXNUM:
  316. len = 1;
  317. fixnum_seed = FIX2LONG(seed);
  318. if (fixnum_seed < 0)
  319. fixnum_seed = -fixnum_seed;
  320. buf[0] = (unsigned int)(fixnum_seed & 0xffffffff);
  321. #if SIZEOF_LONG > SIZEOF_INT32
  322. if ((long)(int)fixnum_seed != fixnum_seed) {
  323. if ((buf[1] = (unsigned int)(fixnum_seed >> 32)) != 0) ++len;
  324. }
  325. #endif
  326. break;
  327. case T_BIGNUM:
  328. blen = RBIGNUM_LEN(seed);
  329. if (blen == 0) {
  330. len = 1;
  331. }
  332. else {
  333. if (blen > MT_MAX_STATE * SIZEOF_INT32 / SIZEOF_BDIGITS)
  334. blen = (len = MT_MAX_STATE) * SIZEOF_INT32 / SIZEOF_BDIGITS;
  335. len = roomof((int)blen * SIZEOF_BDIGITS, SIZEOF_INT32);
  336. }
  337. /* allocate ints for init_by_array */
  338. if (len > numberof(buf0)) buf = ALLOC_N(unsigned int, len);
  339. memset(buf, 0, len * sizeof(*buf));
  340. len = 0;
  341. for (i = (int)(blen-1); 0 <= i; i--) {
  342. j = i * SIZEOF_BDIGITS / SIZEOF_INT32;
  343. #if SIZEOF_BDIGITS < SIZEOF_INT32
  344. buf[j] <<= BITSPERDIG;
  345. #endif
  346. buf[j] |= RBIGNUM_DIGITS(seed)[i];
  347. if (!len && buf[j]) len = j;
  348. }
  349. ++len;
  350. break;
  351. default:
  352. rb_raise(rb_eTypeError, "failed to convert %s into Integer",
  353. rb_obj_classname(vseed));
  354. }
  355. if (len <= 1) {
  356. init_genrand(mt, buf[0]);
  357. }
  358. else {
  359. if (buf[len-1] == 1) /* remove leading-zero-guard */
  360. len--;
  361. init_by_array(mt, buf, len);
  362. }
  363. if (buf != buf0) xfree(buf);
  364. return seed;
  365. }
  366. /*
  367. * call-seq: Random.new([seed]) -> prng
  368. *
  369. * Creates new Mersenne Twister based pseudorandom number generator with
  370. * seed. When the argument seed is omitted, the generator is initialized
  371. * with Random.new_seed.
  372. *
  373. * The argument seed is used to ensure repeatable sequences of random numbers
  374. * between different runs of the program.
  375. *
  376. * prng = Random.new(1234)
  377. * [ prng.rand, prng.rand ] #=> [0.191519450378892, 0.622108771039832]
  378. * [ prng.integer(10), prng.integer(1000) ] #=> [4, 664]
  379. * prng = Random.new(1234)
  380. * [ prng.rand, prng.rand ] #=> [0.191519450378892, 0.622108771039832]
  381. */
  382. static VALUE
  383. random_init(int argc, VALUE *argv, VALUE obj)
  384. {
  385. VALUE vseed;
  386. rb_random_t *rnd = get_rnd(obj);
  387. if (argc == 0) {
  388. vseed = random_seed();
  389. }
  390. else {
  391. rb_scan_args(argc, argv, "01", &vseed);
  392. }
  393. rnd->seed = rand_init(&rnd->mt, vseed);
  394. return obj;
  395. }
  396. #define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * sizeof(int))
  397. #if defined(S_ISCHR) && !defined(DOSISH)
  398. # define USE_DEV_URANDOM 1
  399. #else
  400. # define USE_DEV_URANDOM 0
  401. #endif
  402. static void
  403. fill_random_seed(unsigned int seed[DEFAULT_SEED_CNT])
  404. {
  405. static int n = 0;
  406. struct timeval tv;
  407. #if USE_DEV_URANDOM
  408. int fd;
  409. struct stat statbuf;
  410. #elif defined(_WIN32)
  411. HCRYPTPROV prov;
  412. #endif
  413. memset(seed, 0, DEFAULT_SEED_LEN);
  414. #if USE_DEV_URANDOM
  415. if ((fd = open("/dev/urandom", O_RDONLY
  416. #ifdef O_NONBLOCK
  417. |O_NONBLOCK
  418. #endif
  419. #ifdef O_NOCTTY
  420. |O_NOCTTY
  421. #endif
  422. )) >= 0) {
  423. if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
  424. if (read(fd, seed, DEFAULT_SEED_LEN) < DEFAULT_SEED_LEN) {
  425. /* abandon */;
  426. }
  427. }
  428. close(fd);
  429. }
  430. #elif defined(_WIN32)
  431. if (CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
  432. CryptGenRandom(prov, DEFAULT_SEED_LEN, (void *)seed);
  433. CryptReleaseContext(prov, 0);
  434. }
  435. #endif
  436. gettimeofday(&tv, 0);
  437. seed[0] ^= tv.tv_usec;
  438. seed[1] ^= (unsigned int)tv.tv_sec;
  439. #if SIZEOF_TIME_T > SIZEOF_INT
  440. seed[0] ^= (unsigned int)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
  441. #endif
  442. seed[2] ^= getpid() ^ (n++ << 16);
  443. seed[3] ^= (unsigned int)(VALUE)&seed;
  444. #if SIZEOF_VOIDP > SIZEOF_INT
  445. seed[2] ^= (unsigned int)((VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
  446. #endif
  447. }
  448. static VALUE
  449. make_seed_value(const void *ptr)
  450. {
  451. const long len = DEFAULT_SEED_LEN/SIZEOF_BDIGITS;
  452. BDIGIT *digits;
  453. NEWOBJ(big, struct RBignum);
  454. OBJSETUP(big, rb_cBignum, T_BIGNUM);
  455. RBIGNUM_SET_SIGN(big, 1);
  456. rb_big_resize((VALUE)big, len + 1);
  457. digits = RBIGNUM_DIGITS(big);
  458. MEMCPY(digits, ptr, char, DEFAULT_SEED_LEN);
  459. /* set leading-zero-guard if need. */
  460. digits[len] =
  461. #if SIZEOF_INT32 / SIZEOF_BDIGITS > 1
  462. digits[len-2] <= 1 && digits[len-1] == 0
  463. #else
  464. digits[len-1] <= 1
  465. #endif
  466. ? 1 : 0;
  467. return rb_big_norm((VALUE)big);
  468. }
  469. /*
  470. * call-seq: Random.new_seed -> integer
  471. *
  472. * Returns arbitrary value for seed.
  473. */
  474. static VALUE
  475. random_seed(void)
  476. {
  477. unsigned int buf[DEFAULT_SEED_CNT];
  478. fill_random_seed(buf);
  479. return make_seed_value(buf);
  480. }
  481. /*
  482. * call-seq: prng.seed -> integer
  483. *
  484. * Returns the seed of the generator.
  485. */
  486. static VALUE
  487. random_get_seed(VALUE obj)
  488. {
  489. return get_rnd(obj)->seed;
  490. }
  491. /* :nodoc: */
  492. static VALUE
  493. random_copy(VALUE obj, VALUE orig)
  494. {
  495. rb_random_t *rnd1 = get_rnd(obj);
  496. rb_random_t *rnd2 = get_rnd(orig);
  497. struct MT *mt = &rnd1->mt;
  498. *rnd1 = *rnd2;
  499. mt->next = mt->state + numberof(mt->state) - mt->left + 1;
  500. return obj;
  501. }
  502. static VALUE
  503. mt_state(const struct MT *mt)
  504. {
  505. VALUE bigo = rb_big_new(sizeof(mt->state) / sizeof(BDIGIT), 1);
  506. BDIGIT *d = RBIGNUM_DIGITS(bigo);
  507. int i;
  508. for (i = 0; i < numberof(mt->state); ++i) {
  509. unsigned int x = mt->state[i];
  510. #if SIZEOF_BDIGITS < SIZEOF_INT32
  511. int j;
  512. for (j = 0; j < SIZEOF_INT32 / SIZEOF_BDIGITS; ++j) {
  513. *d++ = BIGLO(x);
  514. x = BIGDN(x);
  515. }
  516. #else
  517. *d++ = (BDIGIT)x;
  518. #endif
  519. }
  520. return rb_big_norm(bigo);
  521. }
  522. /* :nodoc: */
  523. static VALUE
  524. random_state(VALUE obj)
  525. {
  526. rb_random_t *rnd = get_rnd(obj);
  527. return mt_state(&rnd->mt);
  528. }
  529. /* :nodoc: */
  530. static VALUE
  531. random_s_state(VALUE klass)
  532. {
  533. return mt_state(&default_rand.mt);
  534. }
  535. /* :nodoc: */
  536. static VALUE
  537. random_left(VALUE obj)
  538. {
  539. rb_random_t *rnd = get_rnd(obj);
  540. return INT2FIX(rnd->mt.left);
  541. }
  542. /* :nodoc: */
  543. static VALUE
  544. random_s_left(VALUE klass)
  545. {
  546. return INT2FIX(default_rand.mt.left);
  547. }
  548. /* :nodoc: */
  549. static VALUE
  550. random_dump(VALUE obj)
  551. {
  552. rb_random_t *rnd = get_rnd(obj);
  553. VALUE dump = rb_ary_new2(3);
  554. rb_ary_push(dump, mt_state(&rnd->mt));
  555. rb_ary_push(dump, INT2FIX(rnd->mt.left));
  556. rb_ary_push(dump, rnd->seed);
  557. return dump;
  558. }
  559. /* :nodoc: */
  560. static VALUE
  561. random_load(VALUE obj, VALUE dump)
  562. {
  563. rb_random_t *rnd = get_rnd(obj);
  564. struct MT *mt = &rnd->mt;
  565. VALUE state, left = INT2FIX(1), seed = INT2FIX(0);
  566. VALUE *ary;
  567. unsigned long x;
  568. Check_Type(dump, T_ARRAY);
  569. ary = RARRAY_PTR(dump);
  570. switch (RARRAY_LEN(dump)) {
  571. case 3:
  572. seed = ary[2];
  573. case 2:
  574. left = ary[1];
  575. case 1:
  576. state = ary[0];
  577. break;
  578. default:
  579. rb_raise(rb_eArgError, "wrong dump data");
  580. }
  581. memset(mt->state, 0, sizeof(mt->state));
  582. if (FIXNUM_P(state)) {
  583. x = FIX2ULONG(state);
  584. mt->state[0] = (unsigned int)x;
  585. #if SIZEOF_LONG / SIZEOF_INT >= 2
  586. mt->state[1] = (unsigned int)(x >> BITSPERDIG);
  587. #endif
  588. #if SIZEOF_LONG / SIZEOF_INT >= 3
  589. mt->state[2] = (unsigned int)(x >> 2 * BITSPERDIG);
  590. #endif
  591. #if SIZEOF_LONG / SIZEOF_INT >= 4
  592. mt->state[3] = (unsigned int)(x >> 3 * BITSPERDIG);
  593. #endif
  594. }
  595. else {
  596. BDIGIT *d;
  597. long len;
  598. Check_Type(state, T_BIGNUM);
  599. len = RBIGNUM_LEN(state);
  600. if (len > roomof(sizeof(mt->state), SIZEOF_BDIGITS)) {
  601. len = roomof(sizeof(mt->state), SIZEOF_BDIGITS);
  602. }
  603. #if SIZEOF_BDIGITS < SIZEOF_INT
  604. else if (len % DIGSPERINT) {
  605. d = RBIGNUM_DIGITS(state) + len;
  606. # if DIGSPERINT == 2
  607. --len;
  608. x = *--d;
  609. # else
  610. x = 0;
  611. do {
  612. x = (x << BITSPERDIG) | *--d;
  613. } while (--len % DIGSPERINT);
  614. # endif
  615. mt->state[len / DIGSPERINT] = (unsigned int)x;
  616. }
  617. #endif
  618. if (len > 0) {
  619. d = BDIGITS(state) + len;
  620. do {
  621. --len;
  622. x = *--d;
  623. # if DIGSPERINT == 2
  624. --len;
  625. x = (x << BITSPERDIG) | *--d;
  626. # elif SIZEOF_BDIGITS < SIZEOF_INT
  627. do {
  628. x = (x << BITSPERDIG) | *--d;
  629. } while (--len % DIGSPERINT);
  630. # endif
  631. mt->state[len / DIGSPERINT] = (unsigned int)x;
  632. } while (len > 0);
  633. }
  634. }
  635. x = NUM2ULONG(left);
  636. if (x > numberof(mt->state)) {
  637. rb_raise(rb_eArgError, "wrong value");
  638. }
  639. mt->left = (unsigned int)x;
  640. mt->next = mt->state + numberof(mt->state) - x + 1;
  641. rnd->seed = rb_to_int(seed);
  642. return obj;
  643. }
  644. /*
  645. * call-seq:
  646. * srand(number=0) -> old_seed
  647. *
  648. * Seeds the pseudorandom number generator to the value of
  649. * <i>number</i>. If <i>number</i> is omitted
  650. * or zero, seeds the generator using a combination of the time, the
  651. * process id, and a sequence number. (This is also the behavior if
  652. * <code>Kernel::rand</code> is called without previously calling
  653. * <code>srand</code>, but without the sequence.) By setting the seed
  654. * to a known value, scripts can be made deterministic during testing.
  655. * The previous seed value is returned. Also see <code>Kernel::rand</code>.
  656. */
  657. static VALUE
  658. rb_f_srand(int argc, VALUE *argv, VALUE obj)
  659. {
  660. VALUE seed, old;
  661. rb_random_t *r = &default_rand;
  662. rb_secure(4);
  663. if (argc == 0) {
  664. seed = random_seed();
  665. }
  666. else {
  667. rb_scan_args(argc, argv, "01", &seed);
  668. }
  669. old = r->seed;
  670. r->seed = rand_init(&r->mt, seed);
  671. return old;
  672. }
  673. static unsigned long
  674. make_mask(unsigned long x)
  675. {
  676. x = x | x >> 1;
  677. x = x | x >> 2;
  678. x = x | x >> 4;
  679. x = x | x >> 8;
  680. x = x | x >> 16;
  681. #if 4 < SIZEOF_LONG
  682. x = x | x >> 32;
  683. #endif
  684. return x;
  685. }
  686. static unsigned long
  687. limited_rand(struct MT *mt, unsigned long limit)
  688. {
  689. /* mt must be initialized */
  690. int i;
  691. unsigned long val, mask;
  692. if (!limit) return 0;
  693. mask = make_mask(limit);
  694. retry:
  695. val = 0;
  696. for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
  697. if ((mask >> (i * 32)) & 0xffffffff) {
  698. val |= (unsigned long)genrand_int32(mt) << (i * 32);
  699. val &= mask;
  700. if (limit < val)
  701. goto retry;
  702. }
  703. }
  704. return val;
  705. }
  706. static VALUE
  707. limited_big_rand(struct MT *mt, struct RBignum *limit)
  708. {
  709. /* mt must be initialized */
  710. unsigned long mask, lim, rnd;
  711. struct RBignum *val;
  712. long i, len;
  713. int boundary;
  714. len = (RBIGNUM_LEN(limit) * SIZEOF_BDIGITS + 3) / 4;
  715. val = (struct RBignum *)rb_big_clone((VALUE)limit);
  716. RBIGNUM_SET_SIGN(val, 1);
  717. #if SIZEOF_BDIGITS == 2
  718. # define BIG_GET32(big,i) \
  719. (RBIGNUM_DIGITS(big)[(i)*2] | \
  720. ((i)*2+1 < RBIGNUM_LEN(big) ? \
  721. (RBIGNUM_DIGITS(big)[(i)*2+1] << 16) : \
  722. 0))
  723. # define BIG_SET32(big,i,d) \
  724. ((RBIGNUM_DIGITS(big)[(i)*2] = (d) & 0xffff), \
  725. ((i)*2+1 < RBIGNUM_LEN(big) ? \
  726. (RBIGNUM_DIGITS(big)[(i)*2+1] = (d) >> 16) : \
  727. 0))
  728. #else
  729. /* SIZEOF_BDIGITS == 4 */
  730. # define BIG_GET32(big,i) (RBIGNUM_DIGITS(big)[i])
  731. # define BIG_SET32(big,i,d) (RBIGNUM_DIGITS(big)[i] = (d))
  732. #endif
  733. retry:
  734. mask = 0;
  735. boundary = 1;
  736. for (i = len-1; 0 <= i; i--) {
  737. lim = BIG_GET32(limit, i);
  738. mask = mask ? 0xffffffff : make_mask(lim);
  739. if (mask) {
  740. rnd = genrand_int32(mt) & mask;
  741. if (boundary) {
  742. if (lim < rnd)
  743. goto retry;
  744. if (rnd < lim)
  745. boundary = 0;
  746. }
  747. }
  748. else {
  749. rnd = 0;
  750. }
  751. BIG_SET32(val, i, (BDIGIT)rnd);
  752. }
  753. return rb_big_norm((VALUE)val);
  754. }
  755. unsigned long
  756. rb_rand_internal(unsigned long i)
  757. {
  758. struct MT *mt = default_mt();
  759. return limited_rand(mt, i);
  760. }
  761. unsigned int
  762. rb_random_int32(VALUE obj)
  763. {
  764. rb_random_t *rnd = get_rnd(obj);
  765. return genrand_int32(&rnd->mt);
  766. }
  767. double
  768. rb_random_real(VALUE obj)
  769. {
  770. rb_random_t *rnd = get_rnd(obj);
  771. return genrand_real(&rnd->mt);
  772. }
  773. /*
  774. * call-seq: prng.bytes(size) -> prng
  775. *
  776. * Returns a random binary string. The argument size specified the length of
  777. * the result string.
  778. */
  779. static VALUE
  780. random_bytes(VALUE obj, VALUE len)
  781. {
  782. return rb_random_bytes(obj, NUM2LONG(rb_to_int(len)));
  783. }
  784. VALUE
  785. rb_random_bytes(VALUE obj, long n)
  786. {
  787. rb_random_t *rnd = get_rnd(obj);
  788. VALUE bytes = rb_str_new(0, n);
  789. char *ptr = RSTRING_PTR(bytes);
  790. unsigned int r, i;
  791. for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
  792. r = genrand_int32(&rnd->mt);
  793. i = SIZEOF_INT32;
  794. do {
  795. *ptr++ = (char)r;
  796. r >>= CHAR_BIT;
  797. } while (--i);
  798. }
  799. if (n > 0) {
  800. r = genrand_int32(&rnd->mt);
  801. do {
  802. *ptr++ = (char)r;
  803. r >>= CHAR_BIT;
  804. } while (--n);
  805. }
  806. return bytes;
  807. }
  808. static VALUE
  809. range_values(VALUE vmax, VALUE *begp, int *exclp)
  810. {
  811. VALUE end, r;
  812. if (!rb_range_values(vmax, begp, &end, exclp)) return Qfalse;
  813. if (!rb_respond_to(end, id_minus)) return Qfalse;
  814. r = rb_funcall2(end, id_minus, 1, begp);
  815. if (NIL_P(r)) return Qfalse;
  816. return r;
  817. }
  818. static VALUE
  819. rand_int(struct MT *mt, VALUE vmax, int restrictive)
  820. {
  821. /* mt must be initialized */
  822. long max;
  823. unsigned long r;
  824. if (FIXNUM_P(vmax)) {
  825. max = FIX2LONG(vmax);
  826. if (!max) return Qnil;
  827. if (max < 0) {
  828. if (restrictive) return Qnil;
  829. max = -max;
  830. }
  831. r = limited_rand(mt, (unsigned long)max - 1);
  832. return ULONG2NUM(r);
  833. }
  834. else {
  835. VALUE ret;
  836. if (rb_bigzero_p(vmax)) return Qnil;
  837. if (!RBIGNUM_SIGN(vmax)) {
  838. if (restrictive) return Qnil;
  839. vmax = rb_big_clone(vmax);
  840. RBIGNUM_SET_SIGN(vmax, 1);
  841. }
  842. vmax = rb_big_minus(vmax, INT2FIX(1));
  843. if (FIXNUM_P(vmax)) {
  844. max = FIX2LONG(vmax);
  845. if (max == -1) return Qnil;
  846. r = limited_rand(mt, max);
  847. return LONG2NUM(r);
  848. }
  849. ret = limited_big_rand(mt, RBIGNUM(vmax));
  850. RB_GC_GUARD(vmax);
  851. return ret;
  852. }
  853. }
  854. static inline double
  855. float_value(VALUE v)
  856. {
  857. double x = RFLOAT_VALUE(v);
  858. if (isinf(x) || isnan(x)) {
  859. VALUE error = INT2FIX(EDOM);
  860. rb_exc_raise(rb_class_new_instance(1, &error, rb_eSystemCallError));
  861. }
  862. return x;
  863. }
  864. /*
  865. * call-seq:
  866. * prng.rand -> float
  867. * prng.rand(limit) -> number
  868. *
  869. * When the argument is an +Integer+ or a +Bignum+, it returns a
  870. * random integer greater than or equal to zero and less than the
  871. * argument. Unlike Random.rand, when the argument is a negative
  872. * integer or zero, it raises an ArgumentError.
  873. *
  874. * When the argument is a +Float+, it returns a random floating point
  875. * number between 0.0 and _max_, including 0.0 and excluding _max_.
  876. *
  877. * When the argument _limit_ is a +Range+, it returns a random
  878. * number where range.member?(number) == true.
  879. * prng.rand(5..9) #=> one of [5, 6, 7, 8, 9]
  880. * prng.rand(5...9) #=> one of [5, 6, 7, 8]
  881. * prng.rand(5.0..9.0) #=> between 5.0 and 9.0, including 9.0
  882. * prng.rand(5.0...9.0) #=> between 5.0 and 9.0, excluding 9.0
  883. *
  884. * +begin+/+end+ of the range have to have subtract and add methods.
  885. *
  886. * Otherwise, it raises an ArgumentError.
  887. */
  888. static VALUE
  889. random_rand(int argc, VALUE *argv, VALUE obj)
  890. {
  891. rb_random_t *rnd = get_rnd(obj);
  892. VALUE vmax, beg = Qundef, v;
  893. int excl = 0;
  894. if (argc == 0) {
  895. return rb_float_new(genrand_real(&rnd->mt));
  896. }
  897. else if (argc != 1) {
  898. rb_raise(rb_eArgError, "wrong number of arguments (%d for 0..1)", argc);
  899. }
  900. vmax = argv[0];
  901. if (NIL_P(vmax)) {
  902. v = Qnil;
  903. }
  904. else if (TYPE(vmax) != T_FLOAT && (v = rb_check_to_integer(vmax, "to_int"), !NIL_P(v))) {
  905. v = rand_int(&rnd->mt, vmax = v, 1);
  906. }
  907. else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
  908. double max = float_value(v);
  909. if (max > 0.0)
  910. v = rb_float_new(max * genrand_real(&rnd->mt));
  911. else
  912. v = Qnil;
  913. }
  914. else if ((v = range_values(vmax, &beg, &excl)) != Qfalse) {
  915. vmax = v;
  916. if (TYPE(vmax) != T_FLOAT && (v = rb_check_to_integer(vmax, "to_int"), !NIL_P(v))) {
  917. long max;
  918. vmax = v;
  919. v = Qnil;
  920. if (FIXNUM_P(vmax)) {
  921. fixnum:
  922. if ((max = FIX2LONG(vmax) - excl) >= 0) {
  923. unsigned long r = limited_rand(&rnd->mt, (unsigned long)max);
  924. v = ULONG2NUM(r);
  925. }
  926. }
  927. else if (BUILTIN_TYPE(vmax) == T_BIGNUM && RBIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) {
  928. vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax);
  929. if (FIXNUM_P(vmax)) {
  930. excl = 0;
  931. goto fixnum;
  932. }
  933. v = limited_big_rand(&rnd->mt, RBIGNUM(vmax));
  934. }
  935. }
  936. else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
  937. double max = float_value(v), r;
  938. v = Qnil;
  939. if (max > 0.0) {
  940. if (excl) {
  941. r = genrand_real(&rnd->mt);
  942. }
  943. else {
  944. r = genrand_real2(&rnd->mt);
  945. }
  946. v = rb_float_new(r * max);
  947. }
  948. else if (max == 0.0 && !excl) {
  949. v = rb_float_new(0.0);
  950. }
  951. }
  952. }
  953. else {
  954. v = Qnil;
  955. NUM2LONG(vmax);
  956. }
  957. if (NIL_P(v)) {
  958. VALUE mesg = rb_str_new_cstr("invalid argument - ");
  959. rb_str_append(mesg, rb_obj_as_string(argv[0]));
  960. rb_exc_raise(rb_exc_new3(rb_eArgError, mesg));
  961. }
  962. if (beg == Qundef) return v;
  963. if (FIXNUM_P(beg) && FIXNUM_P(v)) {
  964. long x = FIX2LONG(beg) + FIX2LONG(v);
  965. return LONG2NUM(x);
  966. }
  967. switch (TYPE(v)) {
  968. case T_BIGNUM:
  969. return rb_big_plus(v, beg);
  970. case T_FLOAT: {
  971. VALUE f = rb_check_to_float(beg);
  972. if (!NIL_P(f)) {
  973. RFLOAT_VALUE(v) += RFLOAT_VALUE(f);
  974. return v;
  975. }
  976. }
  977. default:
  978. return rb_funcall2(beg, id_plus, 1, &v);
  979. }
  980. }
  981. /*
  982. * call-seq:
  983. * prng1 == prng2 -> true or false
  984. *
  985. * Returns true if the generators' states equal.
  986. */
  987. static VALUE
  988. random_equal(VALUE self, VALUE other)
  989. {
  990. rb_random_t *r1, *r2;
  991. if (rb_obj_class(self) != rb_obj_class(other)) return Qfalse;
  992. r1 = get_rnd(self);
  993. r2 = get_rnd(other);
  994. if (!RTEST(rb_funcall2(r1->seed, rb_intern("=="), 1, &r2->seed))) return Qfalse;
  995. if (memcmp(r1->mt.state, r2->mt.state, sizeof(r1->mt.state))) return Qfalse;
  996. if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state)) return Qfalse;
  997. if (r1->mt.left != r2->mt.left) return Qfalse;
  998. return Qtrue;
  999. }
  1000. /*
  1001. * call-seq:
  1002. * rand(max=0) -> number
  1003. *
  1004. * Converts <i>max</i> to an integer using max1 =
  1005. * max<code>.to_i.abs</code>. If _max_ is +nil+ the result is zero, returns a
  1006. * pseudorandom floating point number greater than or equal to 0.0 and
  1007. * less than 1.0. Otherwise, returns a pseudorandom integer greater
  1008. * than or equal to zero and less than max1. <code>Kernel::srand</code>
  1009. * may be used to ensure repeatable sequences of random numbers between
  1010. * different runs of the program. Ruby currently uses a modified
  1011. * Mersenne Twister with a period of 2**19937-1.
  1012. *
  1013. * srand 1234 #=> 0
  1014. * [ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
  1015. * [ rand(10), rand(1000) ] #=> [6, 817]
  1016. * srand 1234 #=> 1234
  1017. * [ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
  1018. */
  1019. static VALUE
  1020. rb_f_rand(int argc, VALUE *argv, VALUE obj)
  1021. {
  1022. VALUE vmax, r;
  1023. struct MT *mt = default_mt();
  1024. if (argc == 0) goto zero_arg;
  1025. rb_scan_args(argc, argv, "01", &vmax);
  1026. if (NIL_P(vmax)) goto zero_arg;
  1027. vmax = rb_to_int(vmax);
  1028. if (vmax == INT2FIX(0) || NIL_P(r = rand_int(mt, vmax, 0))) {
  1029. zero_arg:
  1030. return DBL2NUM(genrand_real(mt));
  1031. }
  1032. return r;
  1033. }
  1034. static st_index_t hashseed;
  1035. static VALUE
  1036. init_randomseed(struct MT *mt, unsigned int initial[DEFAULT_SEED_CNT])
  1037. {
  1038. VALUE seed;
  1039. fill_random_seed(initial);
  1040. init_by_array(mt, initial, DEFAULT_SEED_CNT);
  1041. seed = make_seed_value(initial);
  1042. memset(initial, 0, DEFAULT_SEED_LEN);
  1043. return seed;
  1044. }
  1045. void
  1046. Init_RandomSeed(void)
  1047. {
  1048. rb_random_t *r = &default_rand;
  1049. unsigned int initial[DEFAULT_SEED_CNT];
  1050. struct MT *mt = &r->mt;
  1051. VALUE seed = init_randomseed(mt, initial);
  1052. hashseed = genrand_int32(mt);
  1053. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 4*8
  1054. hashseed <<= 32;
  1055. hashseed |= genrand_int32(mt);
  1056. #endif
  1057. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 8*8
  1058. hashseed <<= 32;
  1059. hashseed |= genrand_int32(mt);
  1060. #endif
  1061. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 12*8
  1062. hashseed <<= 32;
  1063. hashseed |= genrand_int32(mt);
  1064. #endif
  1065. rb_global_variable(&r->seed);
  1066. r->seed = seed;
  1067. }
  1068. st_index_t
  1069. rb_hash_start(st_index_t h)
  1070. {
  1071. return st_hash_start(hashseed + h);
  1072. }
  1073. static void
  1074. Init_RandomSeed2(void)
  1075. {
  1076. VALUE seed = default_rand.seed;
  1077. if (RB_TYPE_P(seed, T_BIGNUM)) {
  1078. RBASIC(seed)->klass = rb_cBignum;
  1079. }
  1080. }
  1081. void
  1082. rb_reset_random_seed(void)
  1083. {
  1084. rb_random_t *r = &default_rand;
  1085. uninit_genrand(&r->mt);
  1086. r->seed = INT2FIX(0);
  1087. }
  1088. void
  1089. Init_Random(void)
  1090. {
  1091. Init_RandomSeed2();
  1092. rb_define_global_function("srand", rb_f_srand, -1);
  1093. rb_define_global_function("rand", rb_f_rand, -1);
  1094. rb_cRandom = rb_define_class("Random", rb_cObject);
  1095. rb_define_alloc_func(rb_cRandom, random_alloc);
  1096. rb_define_method(rb_cRandom, "initialize", random_init, -1);
  1097. rb_define_method(rb_cRandom, "rand", random_rand, -1);
  1098. rb_define_method(rb_cRandom, "bytes", random_bytes, 1);
  1099. rb_define_method(rb_cRandom, "seed", random_get_seed, 0);
  1100. rb_define_method(rb_cRandom, "initialize_copy", random_copy, 1);
  1101. rb_define_method(rb_cRandom, "marshal_dump", random_dump, 0);
  1102. rb_define_method(rb_cRandom, "marshal_load", random_load, 1);
  1103. rb_define_private_method(rb_cRandom, "state", random_state, 0);
  1104. rb_define_private_method(rb_cRandom, "left", random_left, 0);
  1105. rb_define_method(rb_cRandom, "==", random_equal, 1);
  1106. rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1);
  1107. rb_define_singleton_method(rb_cRandom, "rand", rb_f_rand, -1);
  1108. rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0);
  1109. rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0);
  1110. rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0);
  1111. }