2 * A tiny random number generator.
4 * Currently used for Math.random().
6 * http://www.woodmann.com/forum/archive/index.php/t-3100.html
9 #include "duk_internal.h"
11 #define DUK__UPDATE_RND(rnd) do { \
12 (rnd) += ((rnd) * (rnd)) | 0x05; \
13 (rnd) = ((rnd) & 0xffffffffU); /* if duk_uint32_t is exactly 32 bits, this is a NOP */ \
16 #define DUK__RND_BIT(rnd) ((rnd) >> 31) /* only use the highest bit */
18 DUK_INTERNAL duk_uint32_t
duk_util_tinyrandom_get_bits(duk_hthread
*thr
, duk_small_int_t n
) {
23 rnd
= thr
->heap
->rnd_state
;
25 for (i
= 0; i
< n
; i
++) {
28 res
+= DUK__RND_BIT(rnd
);
31 thr
->heap
->rnd_state
= rnd
;
36 DUK_INTERNAL duk_double_t
duk_util_tinyrandom_get_double(duk_hthread
*thr
) {
42 * XXX: could make this a lot faster if we create the double memory
43 * representation directly. Feasible easily (must be uniform random).
46 rnd
= thr
->heap
->rnd_state
;
48 n
= 53; /* enough to cover the whole mantissa */
53 t
+= DUK__RND_BIT(rnd
);
57 thr
->heap
->rnd_state
= rnd
;
59 DUK_ASSERT(t
>= (duk_double_t
) 0.0);
60 DUK_ASSERT(t
< (duk_double_t
) 1.0);