blob: 1cf57aea18d9d6a37c6d3fd860bfba919680c50d [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
72/* Period parameters -- These are all magic. Don't change. */
73#define N 624
74#define M 397
Serhiy Storchakadce04052015-05-13 15:02:12 +030075#define MATRIX_A 0x9908b0dfU /* constant vector a */
76#define UPPER_MASK 0x80000000U /* most significant w-r bits */
77#define LOWER_MASK 0x7fffffffU /* least significant r bits */
Raymond Hettinger40f62172002-12-29 23:03:38 +000078
79typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 int index;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -070082 uint32_t state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +000083} RandomObject;
84
85static PyTypeObject Random_Type;
86
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
Raymond Hettinger40f62172002-12-29 23:03:38 +000088
89
90/* Random methods */
91
92
93/* generates a random number on [0,0xffffffff]-interval */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -070094static uint32_t
Raymond Hettinger40f62172002-12-29 23:03:38 +000095genrand_int32(RandomObject *self)
96{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -070097 uint32_t y;
98 static const uint32_t mag01[2] = {0x0U, MATRIX_A};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 /* mag01[x] = x * MATRIX_A for x=0,1 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700100 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 mt = self->state;
103 if (self->index >= N) { /* generate N words at one time */
104 int kk;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 for (kk=0;kk<N-M;kk++) {
107 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300108 mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 }
110 for (;kk<N-1;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-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 }
114 y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300115 mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 self->index = 0;
118 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000119
120 y = mt[self->index++];
121 y ^= (y >> 11);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300122 y ^= (y << 7) & 0x9d2c5680U;
123 y ^= (y << 15) & 0xefc60000U;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000124 y ^= (y >> 18);
125 return y;
126}
127
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.
Berker Peksag0ac70c02016-04-29 16:54:10 +0300135 * The original code credited Isaku Wada for this algorithm, 2002/01/09.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000136 */
137static PyObject *
138random_random(RandomObject *self)
139{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700140 uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
Raymond Hettinger40f62172002-12-29 23:03:38 +0000142}
143
144/* initializes mt[N] with a seed */
145static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700146init_genrand(RandomObject *self, uint32_t s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 int mti;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700149 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300152 mt[0]= s;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 for (mti=1; mti<N; mti++) {
154 mt[mti] =
Serhiy Storchakadce04052015-05-13 15:02:12 +0300155 (1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 /* 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 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 }
161 self->index = mti;
162 return;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000163}
164
165/* initialize by an array with array-length */
166/* init_key is the array for initializing keys */
167/* key_length is its length */
Victor Stinnere66987e2016-09-06 16:33:52 -0700168static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700169init_by_array(RandomObject *self, uint32_t init_key[], size_t key_length)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000170{
Mark Dickinson4cd60172012-12-21 21:52:49 +0000171 size_t i, j, k; /* was signed in the original code. RDH 12/16/2002 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700172 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300175 init_genrand(self, 19650218U);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 i=1; j=0;
177 k = (N>key_length ? N : key_length);
178 for (; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300179 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700180 + init_key[j] + (uint32_t)j; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 i++; j++;
182 if (i>=N) { mt[0] = mt[N-1]; i=1; }
183 if (j>=key_length) j=0;
184 }
185 for (k=N-1; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300186 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700187 - (uint32_t)i; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 i++;
189 if (i>=N) { mt[0] = mt[N-1]; i=1; }
190 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000191
Serhiy Storchakadce04052015-05-13 15:02:12 +0300192 mt[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000193}
194
195/*
196 * The rest is Python-specific code, neither part of, nor derived from, the
197 * Twister download.
198 */
199
Victor Stinnere66987e2016-09-06 16:33:52 -0700200static int
201random_seed_urandom(RandomObject *self)
202{
203 PY_UINT32_T key[N];
204
205 if (_PyOS_URandomNonblock(key, sizeof(key)) < 0) {
206 return -1;
207 }
208 init_by_array(self, key, Py_ARRAY_LENGTH(key));
209 return 0;
210}
211
212static void
213random_seed_time_pid(RandomObject *self)
214{
215 _PyTime_t now;
216 uint32_t key[5];
217
218 now = _PyTime_GetSystemClock();
219 key[0] = (PY_UINT32_T)(now & 0xffffffffU);
220 key[1] = (PY_UINT32_T)(now >> 32);
221
222 key[2] = (PY_UINT32_T)getpid();
223
224 now = _PyTime_GetMonotonicClock();
225 key[3] = (PY_UINT32_T)(now & 0xffffffffU);
226 key[4] = (PY_UINT32_T)(now >> 32);
227
228 init_by_array(self, key, Py_ARRAY_LENGTH(key));
229}
230
Raymond Hettinger40f62172002-12-29 23:03:38 +0000231static PyObject *
232random_seed(RandomObject *self, PyObject *args)
233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyObject *n = NULL;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700236 uint32_t *key = NULL;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300237 size_t bits, keyused;
Mark Dickinson4cd60172012-12-21 21:52:49 +0000238 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 PyObject *arg = NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
242 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000243
Victor Stinnere66987e2016-09-06 16:33:52 -0700244 if (arg == NULL || arg == Py_None) {
245 if (random_seed_urandom(self) >= 0) {
246 PyErr_Clear();
Raymond Hettinger40f62172002-12-29 23:03:38 +0000247
Victor Stinnere66987e2016-09-06 16:33:52 -0700248 /* Reading system entropy failed, fall back on the worst entropy:
249 use the current time and process identifier. */
250 random_seed_time_pid(self);
251 }
252 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 }
Victor Stinnere66987e2016-09-06 16:33:52 -0700254
Larry Hastingsd60cd422012-06-24 02:52:21 -0700255 /* This algorithm relies on the number being unsigned.
256 * So: if the arg is a PyLong, use its absolute value.
257 * Otherwise use its hash value, cast to unsigned.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 */
259 if (PyLong_Check(arg))
260 n = PyNumber_Absolute(arg);
261 else {
Larry Hastingsd60cd422012-06-24 02:52:21 -0700262 Py_hash_t hash = PyObject_Hash(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 if (hash == -1)
264 goto Done;
Larry Hastingsd60cd422012-06-24 02:52:21 -0700265 n = PyLong_FromSize_t((size_t)hash);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 }
267 if (n == NULL)
268 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000269
Mark Dickinson4cd60172012-12-21 21:52:49 +0000270 /* Now split n into 32-bit chunks, from the right. */
271 bits = _PyLong_NumBits(n);
272 if (bits == (size_t)-1 && PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000274
Mark Dickinson4cd60172012-12-21 21:52:49 +0000275 /* Figure out how many 32-bit chunks this gives us. */
276 keyused = bits == 0 ? 1 : (bits - 1) / 32 + 1;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000277
Mark Dickinson4cd60172012-12-21 21:52:49 +0000278 /* Convert seed to byte sequence. */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700279 key = (uint32_t *)PyMem_Malloc((size_t)4 * keyused);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300280 if (key == NULL) {
Victor Stinnera4ced862013-07-15 20:00:36 +0200281 PyErr_NoMemory();
Mark Dickinson4cd60172012-12-21 21:52:49 +0000282 goto Done;
Victor Stinnera4ced862013-07-15 20:00:36 +0200283 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000284 res = _PyLong_AsByteArray((PyLongObject *)n,
Serhiy Storchakadce04052015-05-13 15:02:12 +0300285 (unsigned char *)key, keyused * 4,
286 PY_LITTLE_ENDIAN,
Mark Dickinson4cd60172012-12-21 21:52:49 +0000287 0); /* unsigned */
288 if (res == -1) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300289 PyMem_Free(key);
Mark Dickinson4cd60172012-12-21 21:52:49 +0000290 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000292
Serhiy Storchakadce04052015-05-13 15:02:12 +0300293#if PY_BIG_ENDIAN
294 {
295 size_t i, j;
296 /* Reverse an array. */
Zachary Warec15ea4c2015-05-17 23:46:22 -0500297 for (i = 0, j = keyused - 1; i < j; i++, j--) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700298 uint32_t tmp = key[i];
Serhiy Storchakadce04052015-05-13 15:02:12 +0300299 key[i] = key[j];
300 key[j] = tmp;
301 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000302 }
Serhiy Storchakadce04052015-05-13 15:02:12 +0300303#endif
Victor Stinnere66987e2016-09-06 16:33:52 -0700304 init_by_array(self, key, keyused);
305
306 Py_INCREF(Py_None);
307 result = Py_None;
308
Raymond Hettinger40f62172002-12-29 23:03:38 +0000309Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 Py_XDECREF(n);
311 PyMem_Free(key);
312 return result;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000313}
314
315static PyObject *
316random_getstate(RandomObject *self)
317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 PyObject *state;
319 PyObject *element;
320 int i;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 state = PyTuple_New(N+1);
323 if (state == NULL)
324 return NULL;
325 for (i=0; i<N ; i++) {
326 element = PyLong_FromUnsignedLong(self->state[i]);
327 if (element == NULL)
328 goto Fail;
329 PyTuple_SET_ITEM(state, i, element);
330 }
331 element = PyLong_FromLong((long)(self->index));
332 if (element == NULL)
333 goto Fail;
334 PyTuple_SET_ITEM(state, i, element);
335 return state;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000336
337Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 Py_DECREF(state);
339 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000340}
341
342static PyObject *
343random_setstate(RandomObject *self, PyObject *state)
344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 int i;
346 unsigned long element;
347 long index;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (!PyTuple_Check(state)) {
350 PyErr_SetString(PyExc_TypeError,
351 "state vector must be a tuple");
352 return NULL;
353 }
354 if (PyTuple_Size(state) != N+1) {
355 PyErr_SetString(PyExc_ValueError,
356 "state vector is the wrong size");
357 return NULL;
358 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 for (i=0; i<N ; i++) {
361 element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
362 if (element == (unsigned long)-1 && PyErr_Occurred())
363 return NULL;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700364 self->state[i] = (uint32_t)element;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
368 if (index == -1 && PyErr_Occurred())
369 return NULL;
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300370 if (index < 0 || index > N) {
371 PyErr_SetString(PyExc_ValueError, "invalid state");
372 return NULL;
373 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 self->index = (int)index;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_INCREF(Py_None);
377 return Py_None;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000378}
379
Raymond Hettinger40f62172002-12-29 23:03:38 +0000380static PyObject *
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000381random_getrandbits(RandomObject *self, PyObject *args)
382{
Serhiy Storchakadce04052015-05-13 15:02:12 +0300383 int k, i, words;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700384 uint32_t r;
385 uint32_t *wordarray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 PyObject *result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
389 return NULL;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (k <= 0) {
392 PyErr_SetString(PyExc_ValueError,
393 "number of bits must be greater than zero");
394 return NULL;
395 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000396
Serhiy Storchakad8a0bac2013-01-04 12:18:35 +0200397 if (k <= 32) /* Fast path */
398 return PyLong_FromUnsignedLong(genrand_int32(self) >> (32 - k));
399
Serhiy Storchakadce04052015-05-13 15:02:12 +0300400 words = (k - 1) / 32 + 1;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700401 wordarray = (uint32_t *)PyMem_Malloc(words * 4);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300402 if (wordarray == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyErr_NoMemory();
404 return NULL;
405 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000406
Serhiy Storchakadce04052015-05-13 15:02:12 +0300407 /* Fill-out bits of long integer, by 32-bit words, from least significant
408 to most significant. */
409#if PY_LITTLE_ENDIAN
410 for (i = 0; i < words; i++, k -= 32)
411#else
412 for (i = words - 1; i >= 0; i--, k -= 32)
413#endif
414 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 r = genrand_int32(self);
416 if (k < 32)
Serhiy Storchakadce04052015-05-13 15:02:12 +0300417 r >>= (32 - k); /* Drop least significant bits */
418 wordarray[i] = r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000420
Serhiy Storchakadce04052015-05-13 15:02:12 +0300421 result = _PyLong_FromByteArray((unsigned char *)wordarray, words * 4,
422 PY_LITTLE_ENDIAN, 0 /* unsigned */);
423 PyMem_Free(wordarray);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 return result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000425}
426
427static PyObject *
Raymond Hettinger40f62172002-12-29 23:03:38 +0000428random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 RandomObject *self;
431 PyObject *tmp;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
434 return NULL;
Georg Brandl02c42872005-08-26 06:42:30 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 self = (RandomObject *)type->tp_alloc(type, 0);
437 if (self == NULL)
438 return NULL;
439 tmp = random_seed(self, args);
440 if (tmp == NULL) {
441 Py_DECREF(self);
442 return NULL;
443 }
444 Py_DECREF(tmp);
445 return (PyObject *)self;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000446}
447
448static PyMethodDef random_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 {"random", (PyCFunction)random_random, METH_NOARGS,
450 PyDoc_STR("random() -> x in the interval [0, 1).")},
451 {"seed", (PyCFunction)random_seed, METH_VARARGS,
452 PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
453 {"getstate", (PyCFunction)random_getstate, METH_NOARGS,
454 PyDoc_STR("getstate() -> tuple containing the current state.")},
455 {"setstate", (PyCFunction)random_setstate, METH_O,
456 PyDoc_STR("setstate(state) -> None. Restores generator state.")},
457 {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
Serhiy Storchaka95949422013-08-27 19:40:23 +0300458 PyDoc_STR("getrandbits(k) -> x. Generates an int with "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 "k random bits.")},
460 {NULL, NULL} /* sentinel */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000461};
462
463PyDoc_STRVAR(random_doc,
464"Random() -> create a random number generator with its own internal state.");
465
466static PyTypeObject Random_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 PyVarObject_HEAD_INIT(NULL, 0)
468 "_random.Random", /*tp_name*/
469 sizeof(RandomObject), /*tp_basicsize*/
470 0, /*tp_itemsize*/
471 /* methods */
472 0, /*tp_dealloc*/
473 0, /*tp_print*/
474 0, /*tp_getattr*/
475 0, /*tp_setattr*/
476 0, /*tp_reserved*/
477 0, /*tp_repr*/
478 0, /*tp_as_number*/
479 0, /*tp_as_sequence*/
480 0, /*tp_as_mapping*/
481 0, /*tp_hash*/
482 0, /*tp_call*/
483 0, /*tp_str*/
484 PyObject_GenericGetAttr, /*tp_getattro*/
485 0, /*tp_setattro*/
486 0, /*tp_as_buffer*/
487 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
488 random_doc, /*tp_doc*/
489 0, /*tp_traverse*/
490 0, /*tp_clear*/
491 0, /*tp_richcompare*/
492 0, /*tp_weaklistoffset*/
493 0, /*tp_iter*/
494 0, /*tp_iternext*/
495 random_methods, /*tp_methods*/
496 0, /*tp_members*/
497 0, /*tp_getset*/
498 0, /*tp_base*/
499 0, /*tp_dict*/
500 0, /*tp_descr_get*/
501 0, /*tp_descr_set*/
502 0, /*tp_dictoffset*/
503 0, /*tp_init*/
504 0, /*tp_alloc*/
505 random_new, /*tp_new*/
506 PyObject_Free, /*tp_free*/
507 0, /*tp_is_gc*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000508};
509
510PyDoc_STRVAR(module_doc,
511"Module implements the Mersenne Twister random number generator.");
512
Martin v. Löwis1a214512008-06-11 05:26:20 +0000513
514static struct PyModuleDef _randommodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyModuleDef_HEAD_INIT,
516 "_random",
517 module_doc,
518 -1,
519 NULL,
520 NULL,
521 NULL,
522 NULL,
523 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000524};
525
Raymond Hettinger40f62172002-12-29 23:03:38 +0000526PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000527PyInit__random(void)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 PyObject *m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (PyType_Ready(&Random_Type) < 0)
532 return NULL;
533 m = PyModule_Create(&_randommodule);
534 if (m == NULL)
535 return NULL;
536 Py_INCREF(&Random_Type);
537 PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
538 return m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000539}