blob: df149c5e8a054c143293084f34182fc3170d64d0 [file] [log] [blame]
Raymond Hettinger40f62172002-12-29 23:03:38 +00001/* Random objects */
2
3/* ------------------------------------------------------------------
4 The code in this module was based on a download from:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005 http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
Raymond Hettinger40f62172002-12-29 23:03:38 +00006
7 It was modified in 2002 by Raymond Hettinger as follows:
8
Benjamin Petersond8e5f2d2010-08-24 18:08:22 +00009 * the principal computational lines untouched.
Raymond Hettinger40f62172002-12-29 23:03:38 +000010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * renamed genrand_res53() to random_random() and wrapped
12 in python calling/return code.
Raymond Hettinger40f62172002-12-29 23:03:38 +000013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000014 * 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.
Raymond Hettinger40f62172002-12-29 23:03:38 +000018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019 * unused functions from the original were deleted.
20 new, original C python code was added to implement the
21 Random() interface.
Raymond Hettinger40f62172002-12-29 23:03:38 +000022
23 The following are the verbatim comments from the original code:
24
25 A C-program for MT19937, with initialization improved 2002/1/26.
26 Coded by Takuji Nishimura and Makoto Matsumoto.
27
28 Before using, initialize the state by using init_genrand(seed)
29 or init_by_array(init_key, key_length).
30
31 Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
32 All rights reserved.
33
34 Redistribution and use in source and binary forms, with or without
35 modification, are permitted provided that the following conditions
36 are met:
37
38 1. Redistributions of source code must retain the above copyright
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 notice, this list of conditions and the following disclaimer.
Raymond Hettinger40f62172002-12-29 23:03:38 +000040
41 2. Redistributions in binary form must reproduce the above copyright
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 notice, this list of conditions and the following disclaimer in the
43 documentation and/or other materials provided with the distribution.
Raymond Hettinger40f62172002-12-29 23:03:38 +000044
45 3. The names of its contributors may not be used to endorse or promote
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 products derived from this software without specific prior written
47 permission.
Raymond Hettinger40f62172002-12-29 23:03:38 +000048
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.
60
61
62 Any feedback is very welcome.
63 http://www.math.keio.ac.jp/matumoto/emt.html
64 email: matumoto@math.keio.ac.jp
65*/
66
67/* ---------------------------------------------------------------*/
68
69#include "Python.h"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070#include <time.h> /* for seeding to current time */
Raymond Hettinger40f62172002-12-29 23:03:38 +000071
Serhiy Storchakadce04052015-05-13 15:02:12 +030072#ifndef PY_UINT32_T
73# error "Failed to find an exact-width 32-bit integer type"
74#endif
75
Raymond Hettinger40f62172002-12-29 23:03:38 +000076/* Period parameters -- These are all magic. Don't change. */
77#define N 624
78#define M 397
Serhiy Storchakadce04052015-05-13 15:02:12 +030079#define MATRIX_A 0x9908b0dfU /* constant vector a */
80#define UPPER_MASK 0x80000000U /* most significant w-r bits */
81#define LOWER_MASK 0x7fffffffU /* least significant r bits */
Raymond Hettinger40f62172002-12-29 23:03:38 +000082
83typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 int index;
Serhiy Storchakadce04052015-05-13 15:02:12 +030086 PY_UINT32_T state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +000087} RandomObject;
88
89static PyTypeObject Random_Type;
90
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
Raymond Hettinger40f62172002-12-29 23:03:38 +000092
93
94/* Random methods */
95
96
97/* generates a random number on [0,0xffffffff]-interval */
Serhiy Storchakadce04052015-05-13 15:02:12 +030098static PY_UINT32_T
Raymond Hettinger40f62172002-12-29 23:03:38 +000099genrand_int32(RandomObject *self)
100{
Serhiy Storchakadce04052015-05-13 15:02:12 +0300101 PY_UINT32_T y;
102 static PY_UINT32_T mag01[2]={0x0U, MATRIX_A};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 /* mag01[x] = x * MATRIX_A for x=0,1 */
Serhiy Storchakadce04052015-05-13 15:02:12 +0300104 PY_UINT32_T *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 mt = self->state;
107 if (self->index >= N) { /* generate N words at one time */
108 int kk;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 for (kk=0;kk<N-M;kk++) {
111 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300112 mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 }
114 for (;kk<N-1;kk++) {
115 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300116 mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 }
118 y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300119 mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 self->index = 0;
122 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000123
124 y = mt[self->index++];
125 y ^= (y >> 11);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300126 y ^= (y << 7) & 0x9d2c5680U;
127 y ^= (y << 15) & 0xefc60000U;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000128 y ^= (y >> 18);
129 return y;
130}
131
132/* random_random is the function named genrand_res53 in the original code;
133 * generates a random number on [0,1) with 53-bit resolution; note that
134 * 9007199254740992 == 2**53; I assume they're spelling "/2**53" as
135 * multiply-by-reciprocal in the (likely vain) hope that the compiler will
136 * optimize the division away at compile-time. 67108864 is 2**26. In
137 * effect, a contains 27 random bits shifted left 26, and b fills in the
138 * lower 26 bits of the 53-bit numerator.
139 * The orginal code credited Isaku Wada for this algorithm, 2002/01/09.
140 */
141static PyObject *
142random_random(RandomObject *self)
143{
Serhiy Storchakadce04052015-05-13 15:02:12 +0300144 PY_UINT32_T a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
Raymond Hettinger40f62172002-12-29 23:03:38 +0000146}
147
148/* initializes mt[N] with a seed */
149static void
Serhiy Storchakadce04052015-05-13 15:02:12 +0300150init_genrand(RandomObject *self, PY_UINT32_T s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 int mti;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300153 PY_UINT32_T *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300156 mt[0]= s;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 for (mti=1; mti<N; mti++) {
158 mt[mti] =
Serhiy Storchakadce04052015-05-13 15:02:12 +0300159 (1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
161 /* In the previous versions, MSBs of the seed affect */
162 /* only MSBs of the array mt[]. */
163 /* 2002/01/09 modified by Makoto Matsumoto */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 }
165 self->index = mti;
166 return;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000167}
168
169/* initialize by an array with array-length */
170/* init_key is the array for initializing keys */
171/* key_length is its length */
172static PyObject *
Serhiy Storchakadce04052015-05-13 15:02:12 +0300173init_by_array(RandomObject *self, PY_UINT32_T init_key[], size_t key_length)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000174{
Mark Dickinson4cd60172012-12-21 21:52:49 +0000175 size_t i, j, k; /* was signed in the original code. RDH 12/16/2002 */
Serhiy Storchakadce04052015-05-13 15:02:12 +0300176 PY_UINT32_T *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300179 init_genrand(self, 19650218U);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 i=1; j=0;
181 k = (N>key_length ? N : key_length);
182 for (; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300183 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U))
184 + init_key[j] + (PY_UINT32_T)j; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 i++; j++;
186 if (i>=N) { mt[0] = mt[N-1]; i=1; }
187 if (j>=key_length) j=0;
188 }
189 for (k=N-1; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300190 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))
191 - (PY_UINT32_T)i; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 i++;
193 if (i>=N) { mt[0] = mt[N-1]; i=1; }
194 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000195
Serhiy Storchakadce04052015-05-13 15:02:12 +0300196 mt[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000197 Py_INCREF(Py_None);
198 return Py_None;
199}
200
201/*
202 * The rest is Python-specific code, neither part of, nor derived from, the
203 * Twister download.
204 */
205
206static PyObject *
207random_seed(RandomObject *self, PyObject *args)
208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 PyObject *n = NULL;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300211 PY_UINT32_T *key = NULL;
212 size_t bits, keyused;
Mark Dickinson4cd60172012-12-21 21:52:49 +0000213 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 PyObject *arg = NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
217 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 if (arg == NULL || arg == Py_None) {
220 time_t now;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 time(&now);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300223 init_genrand(self, (PY_UINT32_T)now);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 Py_INCREF(Py_None);
225 return Py_None;
226 }
Larry Hastingsd60cd422012-06-24 02:52:21 -0700227 /* This algorithm relies on the number being unsigned.
228 * So: if the arg is a PyLong, use its absolute value.
229 * Otherwise use its hash value, cast to unsigned.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 */
231 if (PyLong_Check(arg))
232 n = PyNumber_Absolute(arg);
233 else {
Larry Hastingsd60cd422012-06-24 02:52:21 -0700234 Py_hash_t hash = PyObject_Hash(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (hash == -1)
236 goto Done;
Larry Hastingsd60cd422012-06-24 02:52:21 -0700237 n = PyLong_FromSize_t((size_t)hash);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 }
239 if (n == NULL)
240 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000241
Mark Dickinson4cd60172012-12-21 21:52:49 +0000242 /* Now split n into 32-bit chunks, from the right. */
243 bits = _PyLong_NumBits(n);
244 if (bits == (size_t)-1 && PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000246
Mark Dickinson4cd60172012-12-21 21:52:49 +0000247 /* Figure out how many 32-bit chunks this gives us. */
248 keyused = bits == 0 ? 1 : (bits - 1) / 32 + 1;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000249
Mark Dickinson4cd60172012-12-21 21:52:49 +0000250 /* Convert seed to byte sequence. */
Serhiy Storchakadce04052015-05-13 15:02:12 +0300251 key = (PY_UINT32_T *)PyMem_Malloc((size_t)4 * keyused);
252 if (key == NULL) {
Victor Stinnera4ced862013-07-15 20:00:36 +0200253 PyErr_NoMemory();
Mark Dickinson4cd60172012-12-21 21:52:49 +0000254 goto Done;
Victor Stinnera4ced862013-07-15 20:00:36 +0200255 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000256 res = _PyLong_AsByteArray((PyLongObject *)n,
Serhiy Storchakadce04052015-05-13 15:02:12 +0300257 (unsigned char *)key, keyused * 4,
258 PY_LITTLE_ENDIAN,
Mark Dickinson4cd60172012-12-21 21:52:49 +0000259 0); /* unsigned */
260 if (res == -1) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300261 PyMem_Free(key);
Mark Dickinson4cd60172012-12-21 21:52:49 +0000262 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000264
Serhiy Storchakadce04052015-05-13 15:02:12 +0300265#if PY_BIG_ENDIAN
266 {
267 size_t i, j;
268 /* Reverse an array. */
Zachary Warec15ea4c2015-05-17 23:46:22 -0500269 for (i = 0, j = keyused - 1; i < j; i++, j--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300270 PY_UINT32_T tmp = key[i];
271 key[i] = key[j];
272 key[j] = tmp;
273 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000274 }
Serhiy Storchakadce04052015-05-13 15:02:12 +0300275#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 result = init_by_array(self, key, keyused);
Raymond Hettinger40f62172002-12-29 23:03:38 +0000277Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 Py_XDECREF(n);
279 PyMem_Free(key);
280 return result;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000281}
282
283static PyObject *
284random_getstate(RandomObject *self)
285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 PyObject *state;
287 PyObject *element;
288 int i;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 state = PyTuple_New(N+1);
291 if (state == NULL)
292 return NULL;
293 for (i=0; i<N ; i++) {
294 element = PyLong_FromUnsignedLong(self->state[i]);
295 if (element == NULL)
296 goto Fail;
297 PyTuple_SET_ITEM(state, i, element);
298 }
299 element = PyLong_FromLong((long)(self->index));
300 if (element == NULL)
301 goto Fail;
302 PyTuple_SET_ITEM(state, i, element);
303 return state;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000304
305Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 Py_DECREF(state);
307 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000308}
309
310static PyObject *
311random_setstate(RandomObject *self, PyObject *state)
312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 int i;
314 unsigned long element;
315 long index;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 if (!PyTuple_Check(state)) {
318 PyErr_SetString(PyExc_TypeError,
319 "state vector must be a tuple");
320 return NULL;
321 }
322 if (PyTuple_Size(state) != N+1) {
323 PyErr_SetString(PyExc_ValueError,
324 "state vector is the wrong size");
325 return NULL;
326 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 for (i=0; i<N ; i++) {
329 element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
330 if (element == (unsigned long)-1 && PyErr_Occurred())
331 return NULL;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300332 self->state[i] = (PY_UINT32_T)element;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
336 if (index == -1 && PyErr_Occurred())
337 return NULL;
338 self->index = (int)index;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 Py_INCREF(Py_None);
341 return Py_None;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000342}
343
Raymond Hettinger40f62172002-12-29 23:03:38 +0000344static PyObject *
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000345random_getrandbits(RandomObject *self, PyObject *args)
346{
Serhiy Storchakadce04052015-05-13 15:02:12 +0300347 int k, i, words;
348 PY_UINT32_T r;
349 PY_UINT32_T *wordarray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 PyObject *result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
353 return NULL;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (k <= 0) {
356 PyErr_SetString(PyExc_ValueError,
357 "number of bits must be greater than zero");
358 return NULL;
359 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000360
Serhiy Storchakad8a0bac2013-01-04 12:18:35 +0200361 if (k <= 32) /* Fast path */
362 return PyLong_FromUnsignedLong(genrand_int32(self) >> (32 - k));
363
Serhiy Storchakadce04052015-05-13 15:02:12 +0300364 words = (k - 1) / 32 + 1;
365 wordarray = (PY_UINT32_T *)PyMem_Malloc(words * 4);
366 if (wordarray == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyErr_NoMemory();
368 return NULL;
369 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000370
Serhiy Storchakadce04052015-05-13 15:02:12 +0300371 /* Fill-out bits of long integer, by 32-bit words, from least significant
372 to most significant. */
373#if PY_LITTLE_ENDIAN
374 for (i = 0; i < words; i++, k -= 32)
375#else
376 for (i = words - 1; i >= 0; i--, k -= 32)
377#endif
378 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 r = genrand_int32(self);
380 if (k < 32)
Serhiy Storchakadce04052015-05-13 15:02:12 +0300381 r >>= (32 - k); /* Drop least significant bits */
382 wordarray[i] = r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000384
Serhiy Storchakadce04052015-05-13 15:02:12 +0300385 result = _PyLong_FromByteArray((unsigned char *)wordarray, words * 4,
386 PY_LITTLE_ENDIAN, 0 /* unsigned */);
387 PyMem_Free(wordarray);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 return result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000389}
390
391static PyObject *
Raymond Hettinger40f62172002-12-29 23:03:38 +0000392random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 RandomObject *self;
395 PyObject *tmp;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
398 return NULL;
Georg Brandl02c42872005-08-26 06:42:30 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 self = (RandomObject *)type->tp_alloc(type, 0);
401 if (self == NULL)
402 return NULL;
403 tmp = random_seed(self, args);
404 if (tmp == NULL) {
405 Py_DECREF(self);
406 return NULL;
407 }
408 Py_DECREF(tmp);
409 return (PyObject *)self;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000410}
411
412static PyMethodDef random_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 {"random", (PyCFunction)random_random, METH_NOARGS,
414 PyDoc_STR("random() -> x in the interval [0, 1).")},
415 {"seed", (PyCFunction)random_seed, METH_VARARGS,
416 PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
417 {"getstate", (PyCFunction)random_getstate, METH_NOARGS,
418 PyDoc_STR("getstate() -> tuple containing the current state.")},
419 {"setstate", (PyCFunction)random_setstate, METH_O,
420 PyDoc_STR("setstate(state) -> None. Restores generator state.")},
421 {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
Serhiy Storchaka95949422013-08-27 19:40:23 +0300422 PyDoc_STR("getrandbits(k) -> x. Generates an int with "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 "k random bits.")},
424 {NULL, NULL} /* sentinel */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000425};
426
427PyDoc_STRVAR(random_doc,
428"Random() -> create a random number generator with its own internal state.");
429
430static PyTypeObject Random_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyVarObject_HEAD_INIT(NULL, 0)
432 "_random.Random", /*tp_name*/
433 sizeof(RandomObject), /*tp_basicsize*/
434 0, /*tp_itemsize*/
435 /* methods */
436 0, /*tp_dealloc*/
437 0, /*tp_print*/
438 0, /*tp_getattr*/
439 0, /*tp_setattr*/
440 0, /*tp_reserved*/
441 0, /*tp_repr*/
442 0, /*tp_as_number*/
443 0, /*tp_as_sequence*/
444 0, /*tp_as_mapping*/
445 0, /*tp_hash*/
446 0, /*tp_call*/
447 0, /*tp_str*/
448 PyObject_GenericGetAttr, /*tp_getattro*/
449 0, /*tp_setattro*/
450 0, /*tp_as_buffer*/
451 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
452 random_doc, /*tp_doc*/
453 0, /*tp_traverse*/
454 0, /*tp_clear*/
455 0, /*tp_richcompare*/
456 0, /*tp_weaklistoffset*/
457 0, /*tp_iter*/
458 0, /*tp_iternext*/
459 random_methods, /*tp_methods*/
460 0, /*tp_members*/
461 0, /*tp_getset*/
462 0, /*tp_base*/
463 0, /*tp_dict*/
464 0, /*tp_descr_get*/
465 0, /*tp_descr_set*/
466 0, /*tp_dictoffset*/
467 0, /*tp_init*/
468 0, /*tp_alloc*/
469 random_new, /*tp_new*/
470 PyObject_Free, /*tp_free*/
471 0, /*tp_is_gc*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000472};
473
474PyDoc_STRVAR(module_doc,
475"Module implements the Mersenne Twister random number generator.");
476
Martin v. Löwis1a214512008-06-11 05:26:20 +0000477
478static struct PyModuleDef _randommodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyModuleDef_HEAD_INIT,
480 "_random",
481 module_doc,
482 -1,
483 NULL,
484 NULL,
485 NULL,
486 NULL,
487 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000488};
489
Raymond Hettinger40f62172002-12-29 23:03:38 +0000490PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000491PyInit__random(void)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyObject *m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (PyType_Ready(&Random_Type) < 0)
496 return NULL;
497 m = PyModule_Create(&_randommodule);
498 if (m == NULL)
499 return NULL;
500 Py_INCREF(&Random_Type);
501 PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
502 return m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000503}