3 /* ------------------------------------------------------------------
4 The code in this module was based on a download from:
5 http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
7 It was modified in 2002 by Raymond Hettinger as follows:
9 * the principal computational lines untouched except for tabbing.
11 * renamed genrand_res53() to random_random() and wrapped
12 in python calling/return code.
14 * genrand_int32() and the helper functions, init_genrand()
15 and init_by_array(), were declared static, wrapped in
16 Python calling/return code. also, their global data
17 references were replaced with structure references.
19 * unused functions from the original were deleted.
20 new, original C python code was added to implement the
23 The following are the verbatim comments from the original code:
25 A C-program for MT19937, with initialization improved 2002/1/26.
26 Coded by Takuji Nishimura and Makoto Matsumoto.
28 Before using, initialize the state by using init_genrand(seed)
29 or init_by_array(init_key, key_length).
31 Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
34 Redistribution and use in source and binary forms, with or without
35 modification, are permitted provided that the following conditions
38 1. Redistributions of source code must retain the above copyright
39 notice, this list of conditions and the following disclaimer.
41 2. Redistributions in binary form must reproduce the above copyright
42 notice, this list of conditions and the following disclaimer in the
43 documentation and/or other materials provided with the distribution.
45 3. The names of its contributors may not be used to endorse or promote
46 products derived from this software without specific prior written
49 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
50 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
51 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
52 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
53 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
54 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
55 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
56 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
57 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
58 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
59 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62 Any feedback is very welcome.
63 http://www.math.keio.ac.jp/matumoto/emt.html
64 email: matumoto@math.keio.ac.jp
67 /* ---------------------------------------------------------------*/
70 #include <time.h> /* for seeding to current time */
72 /* Period parameters -- These are all magic. Don't change. */
75 #define MATRIX_A 0x9908b0dfUL /* constant vector a */
76 #define UPPER_MASK 0x80000000UL /* most significant w-r bits */
77 #define LOWER_MASK 0x7fffffffUL /* least significant r bits */
81 unsigned long state
[N
];
85 static PyTypeObject Random_Type
;
87 #define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
93 /* generates a random number on [0,0xffffffff]-interval */
95 genrand_int32(RandomObject
*self
)
98 static unsigned long mag01
[2]={0x0UL
, MATRIX_A
};
99 /* mag01[x] = x * MATRIX_A for x=0,1 */
103 if (self
->index
>= N
) { /* generate N words at one time */
106 for (kk
=0;kk
<N
-M
;kk
++) {
107 y
= (mt
[kk
]&UPPER_MASK
)|(mt
[kk
+1]&LOWER_MASK
);
108 mt
[kk
] = mt
[kk
+M
] ^ (y
>> 1) ^ mag01
[y
& 0x1UL
];
111 y
= (mt
[kk
]&UPPER_MASK
)|(mt
[kk
+1]&LOWER_MASK
);
112 mt
[kk
] = mt
[kk
+(M
-N
)] ^ (y
>> 1) ^ mag01
[y
& 0x1UL
];
114 y
= (mt
[N
-1]&UPPER_MASK
)|(mt
[0]&LOWER_MASK
);
115 mt
[N
-1] = mt
[M
-1] ^ (y
>> 1) ^ mag01
[y
& 0x1UL
];
120 y
= mt
[self
->index
++];
122 y
^= (y
<< 7) & 0x9d2c5680UL
;
123 y
^= (y
<< 15) & 0xefc60000UL
;
128 /* random_random is the function named genrand_res53 in the original code;
129 * generates a random number on [0,1) with 53-bit resolution; note that
130 * 9007199254740992 == 2**53; I assume they're spelling "/2**53" as
131 * multiply-by-reciprocal in the (likely vain) hope that the compiler will
132 * optimize the division away at compile-time. 67108864 is 2**26. In
133 * effect, a contains 27 random bits shifted left 26, and b fills in the
134 * lower 26 bits of the 53-bit numerator.
135 * The orginal code credited Isaku Wada for this algorithm, 2002/01/09.
138 random_random(RandomObject
*self
)
140 unsigned long a
=genrand_int32(self
)>>5, b
=genrand_int32(self
)>>6;
141 return PyFloat_FromDouble((a
*67108864.0+b
)*(1.0/9007199254740992.0));
144 /* initializes mt[N] with a seed */
146 init_genrand(RandomObject
*self
, unsigned long s
)
152 mt
[0]= s
& 0xffffffffUL
;
153 for (mti
=1; mti
<N
; mti
++) {
155 (1812433253UL * (mt
[mti
-1] ^ (mt
[mti
-1] >> 30)) + mti
);
156 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
157 /* In the previous versions, MSBs of the seed affect */
158 /* only MSBs of the array mt[]. */
159 /* 2002/01/09 modified by Makoto Matsumoto */
160 mt
[mti
] &= 0xffffffffUL
;
161 /* for >32 bit machines */
167 /* initialize by an array with array-length */
168 /* init_key is the array for initializing keys */
169 /* key_length is its length */
171 init_by_array(RandomObject
*self
, unsigned long init_key
[], unsigned long key_length
)
173 unsigned int i
, j
, k
; /* was signed in the original code. RDH 12/16/2002 */
177 init_genrand(self
, 19650218UL);
179 k
= (N
>key_length
? N
: key_length
);
181 mt
[i
] = (mt
[i
] ^ ((mt
[i
-1] ^ (mt
[i
-1] >> 30)) * 1664525UL))
182 + init_key
[j
] + j
; /* non linear */
183 mt
[i
] &= 0xffffffffUL
; /* for WORDSIZE > 32 machines */
185 if (i
>=N
) { mt
[0] = mt
[N
-1]; i
=1; }
186 if (j
>=key_length
) j
=0;
188 for (k
=N
-1; k
; k
--) {
189 mt
[i
] = (mt
[i
] ^ ((mt
[i
-1] ^ (mt
[i
-1] >> 30)) * 1566083941UL))
190 - i
; /* non linear */
191 mt
[i
] &= 0xffffffffUL
; /* for WORDSIZE > 32 machines */
193 if (i
>=N
) { mt
[0] = mt
[N
-1]; i
=1; }
196 mt
[0] = 0x80000000UL
; /* MSB is 1; assuring non-zero initial array */
202 * The rest is Python-specific code, neither part of, nor derived from, the
207 random_seed(RandomObject
*self
, PyObject
*args
)
209 PyObject
*result
= NULL
; /* guilty until proved innocent */
210 PyObject
*masklower
= NULL
;
211 PyObject
*thirtytwo
= NULL
;
213 unsigned long *key
= NULL
;
214 unsigned long keymax
; /* # of allocated slots in key */
215 unsigned long keyused
; /* # of used slots in key */
218 PyObject
*arg
= NULL
;
220 if (!PyArg_UnpackTuple(args
, "seed", 0, 1, &arg
))
223 if (arg
== NULL
|| arg
== Py_None
) {
227 init_genrand(self
, (unsigned long)now
);
231 /* If the arg is an int or long, use its absolute value; else use
232 * the absolute value of its hash code.
234 if (PyLong_Check(arg
))
235 n
= PyNumber_Absolute(arg
);
237 long hash
= PyObject_Hash(arg
);
240 n
= PyLong_FromUnsignedLong((unsigned long)hash
);
245 /* Now split n into 32-bit chunks, from the right. Each piece is
246 * stored into key, which has a capacity of keymax chunks, of which
247 * keyused are filled. Alas, the repeated shifting makes this a
248 * quadratic-time algorithm; we'd really like to use
249 * _PyLong_AsByteArray here, but then we'd have to break into the
250 * long representation to figure out how big an array was needed
253 keymax
= 8; /* arbitrary; grows later if needed */
255 key
= (unsigned long *)PyMem_Malloc(keymax
* sizeof(*key
));
259 masklower
= PyLong_FromUnsignedLong(0xffffffffU
);
260 if (masklower
== NULL
)
262 thirtytwo
= PyLong_FromLong(32L);
263 if (thirtytwo
== NULL
)
265 while ((err
=PyObject_IsTrue(n
))) {
272 pychunk
= PyNumber_And(n
, masklower
);
275 chunk
= PyLong_AsUnsignedLong(pychunk
);
277 if (chunk
== (unsigned long)-1 && PyErr_Occurred())
279 newn
= PyNumber_Rshift(n
, thirtytwo
);
284 if (keyused
>= keymax
) {
285 unsigned long bigger
= keymax
<< 1;
286 if ((bigger
>> 1) != keymax
) {
290 key
= (unsigned long *)PyMem_Realloc(key
,
291 bigger
* sizeof(*key
));
296 assert(keyused
< keymax
);
297 key
[keyused
++] = chunk
;
301 key
[keyused
++] = 0UL;
302 result
= init_by_array(self
, key
, keyused
);
304 Py_XDECREF(masklower
);
305 Py_XDECREF(thirtytwo
);
312 random_getstate(RandomObject
*self
)
318 state
= PyTuple_New(N
+1);
321 for (i
=0; i
<N
; i
++) {
322 element
= PyLong_FromUnsignedLong(self
->state
[i
]);
325 PyTuple_SET_ITEM(state
, i
, element
);
327 element
= PyLong_FromLong((long)(self
->index
));
330 PyTuple_SET_ITEM(state
, i
, element
);
339 random_setstate(RandomObject
*self
, PyObject
*state
)
342 unsigned long element
;
345 if (!PyTuple_Check(state
)) {
346 PyErr_SetString(PyExc_TypeError
,
347 "state vector must be a tuple");
350 if (PyTuple_Size(state
) != N
+1) {
351 PyErr_SetString(PyExc_ValueError
,
352 "state vector is the wrong size");
356 for (i
=0; i
<N
; i
++) {
357 element
= PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state
, i
));
358 if (element
== -1 && PyErr_Occurred())
360 self
->state
[i
] = element
& 0xffffffffUL
; /* Make sure we get sane state */
363 index
= PyLong_AsLong(PyTuple_GET_ITEM(state
, i
));
364 if (index
== -1 && PyErr_Occurred())
366 self
->index
= (int)index
;
373 random_getrandbits(RandomObject
*self
, PyObject
*args
)
377 unsigned char *bytearray
;
380 if (!PyArg_ParseTuple(args
, "i:getrandbits", &k
))
384 PyErr_SetString(PyExc_ValueError
,
385 "number of bits must be greater than zero");
389 bytes
= ((k
- 1) / 32 + 1) * 4;
390 bytearray
= (unsigned char *)PyMem_Malloc(bytes
);
391 if (bytearray
== NULL
) {
396 /* Fill-out whole words, byte-by-byte to avoid endianness issues */
397 for (i
=0 ; i
<bytes
; i
+=4, k
-=32) {
398 r
= genrand_int32(self
);
401 bytearray
[i
+0] = (unsigned char)r
;
402 bytearray
[i
+1] = (unsigned char)(r
>> 8);
403 bytearray
[i
+2] = (unsigned char)(r
>> 16);
404 bytearray
[i
+3] = (unsigned char)(r
>> 24);
407 /* little endian order to match bytearray assignment order */
408 result
= _PyLong_FromByteArray(bytearray
, bytes
, 1, 0);
409 PyMem_Free(bytearray
);
414 random_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
419 if (type
== &Random_Type
&& !_PyArg_NoKeywords("Random()", kwds
))
422 self
= (RandomObject
*)type
->tp_alloc(type
, 0);
425 tmp
= random_seed(self
, args
);
431 return (PyObject
*)self
;
434 static PyMethodDef random_methods
[] = {
435 {"random", (PyCFunction
)random_random
, METH_NOARGS
,
436 PyDoc_STR("random() -> x in the interval [0, 1).")},
437 {"seed", (PyCFunction
)random_seed
, METH_VARARGS
,
438 PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
439 {"getstate", (PyCFunction
)random_getstate
, METH_NOARGS
,
440 PyDoc_STR("getstate() -> tuple containing the current state.")},
441 {"setstate", (PyCFunction
)random_setstate
, METH_O
,
442 PyDoc_STR("setstate(state) -> None. Restores generator state.")},
443 {"getrandbits", (PyCFunction
)random_getrandbits
, METH_VARARGS
,
444 PyDoc_STR("getrandbits(k) -> x. Generates a long int with "
446 {NULL
, NULL
} /* sentinel */
449 PyDoc_STRVAR(random_doc
,
450 "Random() -> create a random number generator with its own internal state.");
452 static PyTypeObject Random_Type
= {
453 PyVarObject_HEAD_INIT(NULL
, 0)
454 "_random.Random", /*tp_name*/
455 sizeof(RandomObject
), /*tp_basicsize*/
465 0, /*tp_as_sequence*/
470 PyObject_GenericGetAttr
, /*tp_getattro*/
473 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
474 random_doc
, /*tp_doc*/
477 0, /*tp_richcompare*/
478 0, /*tp_weaklistoffset*/
481 random_methods
, /*tp_methods*/
491 random_new
, /*tp_new*/
492 PyObject_Free
, /*tp_free*/
496 PyDoc_STRVAR(module_doc
,
497 "Module implements the Mersenne Twister random number generator.");
504 if (PyType_Ready(&Random_Type
) < 0)
506 m
= Py_InitModule3("_random", NULL
, module_doc
);
509 Py_INCREF(&Random_Type
);
510 PyModule_AddObject(m
, "Random", (PyObject
*)&Random_Type
);