blob: e5dd2c961663849cf0b7f01183388e94652f72d6 [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:
INADA Naoki7d5587e2017-02-15 18:59:47 +09005 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/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.
INADA Naoki7d5587e2017-02-15 18:59:47 +090063 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
64 email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
Raymond Hettinger40f62172002-12-29 23:03:38 +000065*/
66
67/* ---------------------------------------------------------------*/
68
69#include "Python.h"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070#include <time.h> /* for seeding to current time */
Victor Stinner9f2a9202016-09-06 17:03:03 -070071#ifdef HAVE_PROCESS_H
72# include <process.h> /* needed for getpid() */
73#endif
Raymond Hettinger40f62172002-12-29 23:03:38 +000074
75/* Period parameters -- These are all magic. Don't change. */
76#define N 624
77#define M 397
Serhiy Storchakadce04052015-05-13 15:02:12 +030078#define MATRIX_A 0x9908b0dfU /* constant vector a */
79#define UPPER_MASK 0x80000000U /* most significant w-r bits */
80#define LOWER_MASK 0x7fffffffU /* least significant r bits */
Raymond Hettinger40f62172002-12-29 23:03:38 +000081
82typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 int index;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -070085 uint32_t state[N];
Raymond Hettinger40f62172002-12-29 23:03:38 +000086} RandomObject;
87
88static PyTypeObject Random_Type;
89
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
Raymond Hettinger40f62172002-12-29 23:03:38 +000091
92
93/* Random methods */
94
95
96/* generates a random number on [0,0xffffffff]-interval */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -070097static uint32_t
Raymond Hettinger40f62172002-12-29 23:03:38 +000098genrand_int32(RandomObject *self)
99{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700100 uint32_t y;
101 static const uint32_t mag01[2] = {0x0U, MATRIX_A};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 /* mag01[x] = x * MATRIX_A for x=0,1 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700103 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 mt = self->state;
106 if (self->index >= N) { /* generate N words at one time */
107 int kk;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 for (kk=0;kk<N-M;kk++) {
110 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300111 mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 }
113 for (;kk<N-1;kk++) {
114 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300115 mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 }
117 y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300118 mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
Raymond Hettinger40f62172002-12-29 23:03:38 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 self->index = 0;
121 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000122
123 y = mt[self->index++];
124 y ^= (y >> 11);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300125 y ^= (y << 7) & 0x9d2c5680U;
126 y ^= (y << 15) & 0xefc60000U;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000127 y ^= (y >> 18);
128 return y;
129}
130
131/* random_random is the function named genrand_res53 in the original code;
132 * generates a random number on [0,1) with 53-bit resolution; note that
133 * 9007199254740992 == 2**53; I assume they're spelling "/2**53" as
134 * multiply-by-reciprocal in the (likely vain) hope that the compiler will
135 * optimize the division away at compile-time. 67108864 is 2**26. In
136 * effect, a contains 27 random bits shifted left 26, and b fills in the
137 * lower 26 bits of the 53-bit numerator.
Berker Peksag0ac70c02016-04-29 16:54:10 +0300138 * The original code credited Isaku Wada for this algorithm, 2002/01/09.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000139 */
140static PyObject *
141random_random(RandomObject *self)
142{
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700143 uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
Raymond Hettinger40f62172002-12-29 23:03:38 +0000145}
146
147/* initializes mt[N] with a seed */
148static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700149init_genrand(RandomObject *self, uint32_t s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 int mti;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700152 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300155 mt[0]= s;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 for (mti=1; mti<N; mti++) {
157 mt[mti] =
Serhiy Storchakadce04052015-05-13 15:02:12 +0300158 (1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
160 /* In the previous versions, MSBs of the seed affect */
161 /* only MSBs of the array mt[]. */
162 /* 2002/01/09 modified by Makoto Matsumoto */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
164 self->index = mti;
165 return;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000166}
167
168/* initialize by an array with array-length */
169/* init_key is the array for initializing keys */
170/* key_length is its length */
Victor Stinnere66987e2016-09-06 16:33:52 -0700171static void
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700172init_by_array(RandomObject *self, uint32_t init_key[], size_t key_length)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000173{
Mark Dickinson4cd60172012-12-21 21:52:49 +0000174 size_t i, j, k; /* was signed in the original code. RDH 12/16/2002 */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700175 uint32_t *mt;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 mt = self->state;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300178 init_genrand(self, 19650218U);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 i=1; j=0;
180 k = (N>key_length ? N : key_length);
181 for (; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300182 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700183 + init_key[j] + (uint32_t)j; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 i++; j++;
185 if (i>=N) { mt[0] = mt[N-1]; i=1; }
186 if (j>=key_length) j=0;
187 }
188 for (k=N-1; k; k--) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300189 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700190 - (uint32_t)i; /* non linear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 i++;
192 if (i>=N) { mt[0] = mt[N-1]; i=1; }
193 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000194
Serhiy Storchakadce04052015-05-13 15:02:12 +0300195 mt[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000196}
197
198/*
199 * The rest is Python-specific code, neither part of, nor derived from, the
200 * Twister download.
201 */
202
Victor Stinnere66987e2016-09-06 16:33:52 -0700203static int
204random_seed_urandom(RandomObject *self)
205{
206 PY_UINT32_T key[N];
207
208 if (_PyOS_URandomNonblock(key, sizeof(key)) < 0) {
209 return -1;
210 }
211 init_by_array(self, key, Py_ARRAY_LENGTH(key));
212 return 0;
213}
214
215static void
216random_seed_time_pid(RandomObject *self)
217{
218 _PyTime_t now;
219 uint32_t key[5];
220
221 now = _PyTime_GetSystemClock();
222 key[0] = (PY_UINT32_T)(now & 0xffffffffU);
223 key[1] = (PY_UINT32_T)(now >> 32);
224
225 key[2] = (PY_UINT32_T)getpid();
226
227 now = _PyTime_GetMonotonicClock();
228 key[3] = (PY_UINT32_T)(now & 0xffffffffU);
229 key[4] = (PY_UINT32_T)(now >> 32);
230
231 init_by_array(self, key, Py_ARRAY_LENGTH(key));
232}
233
Raymond Hettinger40f62172002-12-29 23:03:38 +0000234static PyObject *
235random_seed(RandomObject *self, PyObject *args)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 PyObject *n = NULL;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700239 uint32_t *key = NULL;
Serhiy Storchakadce04052015-05-13 15:02:12 +0300240 size_t bits, keyused;
Mark Dickinson4cd60172012-12-21 21:52:49 +0000241 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyObject *arg = NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
245 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000246
Victor Stinnere66987e2016-09-06 16:33:52 -0700247 if (arg == NULL || arg == Py_None) {
Benjamin Petersonacc2f742016-12-28 20:02:35 -0800248 if (random_seed_urandom(self) < 0) {
Victor Stinnere66987e2016-09-06 16:33:52 -0700249 PyErr_Clear();
Raymond Hettinger40f62172002-12-29 23:03:38 +0000250
Victor Stinnere66987e2016-09-06 16:33:52 -0700251 /* Reading system entropy failed, fall back on the worst entropy:
252 use the current time and process identifier. */
253 random_seed_time_pid(self);
254 }
255 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 }
Victor Stinnere66987e2016-09-06 16:33:52 -0700257
Larry Hastingsd60cd422012-06-24 02:52:21 -0700258 /* This algorithm relies on the number being unsigned.
259 * So: if the arg is a PyLong, use its absolute value.
260 * Otherwise use its hash value, cast to unsigned.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 */
262 if (PyLong_Check(arg))
263 n = PyNumber_Absolute(arg);
264 else {
Larry Hastingsd60cd422012-06-24 02:52:21 -0700265 Py_hash_t hash = PyObject_Hash(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (hash == -1)
267 goto Done;
Larry Hastingsd60cd422012-06-24 02:52:21 -0700268 n = PyLong_FromSize_t((size_t)hash);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 }
270 if (n == NULL)
271 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000272
Mark Dickinson4cd60172012-12-21 21:52:49 +0000273 /* Now split n into 32-bit chunks, from the right. */
274 bits = _PyLong_NumBits(n);
275 if (bits == (size_t)-1 && PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 goto Done;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000277
Mark Dickinson4cd60172012-12-21 21:52:49 +0000278 /* Figure out how many 32-bit chunks this gives us. */
279 keyused = bits == 0 ? 1 : (bits - 1) / 32 + 1;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000280
Mark Dickinson4cd60172012-12-21 21:52:49 +0000281 /* Convert seed to byte sequence. */
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700282 key = (uint32_t *)PyMem_Malloc((size_t)4 * keyused);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300283 if (key == NULL) {
Victor Stinnera4ced862013-07-15 20:00:36 +0200284 PyErr_NoMemory();
Mark Dickinson4cd60172012-12-21 21:52:49 +0000285 goto Done;
Victor Stinnera4ced862013-07-15 20:00:36 +0200286 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000287 res = _PyLong_AsByteArray((PyLongObject *)n,
Serhiy Storchakadce04052015-05-13 15:02:12 +0300288 (unsigned char *)key, keyused * 4,
289 PY_LITTLE_ENDIAN,
Mark Dickinson4cd60172012-12-21 21:52:49 +0000290 0); /* unsigned */
291 if (res == -1) {
Serhiy Storchakadce04052015-05-13 15:02:12 +0300292 PyMem_Free(key);
Mark Dickinson4cd60172012-12-21 21:52:49 +0000293 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000295
Serhiy Storchakadce04052015-05-13 15:02:12 +0300296#if PY_BIG_ENDIAN
297 {
298 size_t i, j;
299 /* Reverse an array. */
Zachary Warec15ea4c2015-05-17 23:46:22 -0500300 for (i = 0, j = keyused - 1; i < j; i++, j--) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700301 uint32_t tmp = key[i];
Serhiy Storchakadce04052015-05-13 15:02:12 +0300302 key[i] = key[j];
303 key[j] = tmp;
304 }
Mark Dickinson4cd60172012-12-21 21:52:49 +0000305 }
Serhiy Storchakadce04052015-05-13 15:02:12 +0300306#endif
Victor Stinnere66987e2016-09-06 16:33:52 -0700307 init_by_array(self, key, keyused);
308
309 Py_INCREF(Py_None);
310 result = Py_None;
311
Raymond Hettinger40f62172002-12-29 23:03:38 +0000312Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 Py_XDECREF(n);
314 PyMem_Free(key);
315 return result;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000316}
317
318static PyObject *
319random_getstate(RandomObject *self)
320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 PyObject *state;
322 PyObject *element;
323 int i;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 state = PyTuple_New(N+1);
326 if (state == NULL)
327 return NULL;
328 for (i=0; i<N ; i++) {
329 element = PyLong_FromUnsignedLong(self->state[i]);
330 if (element == NULL)
331 goto Fail;
332 PyTuple_SET_ITEM(state, i, element);
333 }
334 element = PyLong_FromLong((long)(self->index));
335 if (element == NULL)
336 goto Fail;
337 PyTuple_SET_ITEM(state, i, element);
338 return state;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000339
340Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 Py_DECREF(state);
342 return NULL;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000343}
344
345static PyObject *
346random_setstate(RandomObject *self, PyObject *state)
347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 int i;
349 unsigned long element;
350 long index;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (!PyTuple_Check(state)) {
353 PyErr_SetString(PyExc_TypeError,
354 "state vector must be a tuple");
355 return NULL;
356 }
357 if (PyTuple_Size(state) != N+1) {
358 PyErr_SetString(PyExc_ValueError,
359 "state vector is the wrong size");
360 return NULL;
361 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 for (i=0; i<N ; i++) {
364 element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
365 if (element == (unsigned long)-1 && PyErr_Occurred())
366 return NULL;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700367 self->state[i] = (uint32_t)element;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 }
Raymond Hettinger40f62172002-12-29 23:03:38 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
371 if (index == -1 && PyErr_Occurred())
372 return NULL;
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300373 if (index < 0 || index > N) {
374 PyErr_SetString(PyExc_ValueError, "invalid state");
375 return NULL;
376 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 self->index = (int)index;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 Py_INCREF(Py_None);
380 return Py_None;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000381}
382
Raymond Hettinger40f62172002-12-29 23:03:38 +0000383static PyObject *
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000384random_getrandbits(RandomObject *self, PyObject *args)
385{
Serhiy Storchakadce04052015-05-13 15:02:12 +0300386 int k, i, words;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700387 uint32_t r;
388 uint32_t *wordarray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 PyObject *result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
392 return NULL;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (k <= 0) {
395 PyErr_SetString(PyExc_ValueError,
396 "number of bits must be greater than zero");
397 return NULL;
398 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000399
Serhiy Storchakad8a0bac2013-01-04 12:18:35 +0200400 if (k <= 32) /* Fast path */
401 return PyLong_FromUnsignedLong(genrand_int32(self) >> (32 - k));
402
Serhiy Storchakadce04052015-05-13 15:02:12 +0300403 words = (k - 1) / 32 + 1;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -0700404 wordarray = (uint32_t *)PyMem_Malloc(words * 4);
Serhiy Storchakadce04052015-05-13 15:02:12 +0300405 if (wordarray == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 PyErr_NoMemory();
407 return NULL;
408 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000409
Serhiy Storchakadce04052015-05-13 15:02:12 +0300410 /* Fill-out bits of long integer, by 32-bit words, from least significant
411 to most significant. */
412#if PY_LITTLE_ENDIAN
413 for (i = 0; i < words; i++, k -= 32)
414#else
415 for (i = words - 1; i >= 0; i--, k -= 32)
416#endif
417 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 r = genrand_int32(self);
419 if (k < 32)
Serhiy Storchakadce04052015-05-13 15:02:12 +0300420 r >>= (32 - k); /* Drop least significant bits */
421 wordarray[i] = r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 }
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000423
Serhiy Storchakadce04052015-05-13 15:02:12 +0300424 result = _PyLong_FromByteArray((unsigned char *)wordarray, words * 4,
425 PY_LITTLE_ENDIAN, 0 /* unsigned */);
426 PyMem_Free(wordarray);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 return result;
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000428}
429
430static PyObject *
Raymond Hettinger40f62172002-12-29 23:03:38 +0000431random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 RandomObject *self;
434 PyObject *tmp;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
437 return NULL;
Georg Brandl02c42872005-08-26 06:42:30 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 self = (RandomObject *)type->tp_alloc(type, 0);
440 if (self == NULL)
441 return NULL;
442 tmp = random_seed(self, args);
443 if (tmp == NULL) {
444 Py_DECREF(self);
445 return NULL;
446 }
447 Py_DECREF(tmp);
448 return (PyObject *)self;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000449}
450
451static PyMethodDef random_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 {"random", (PyCFunction)random_random, METH_NOARGS,
453 PyDoc_STR("random() -> x in the interval [0, 1).")},
454 {"seed", (PyCFunction)random_seed, METH_VARARGS,
455 PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
456 {"getstate", (PyCFunction)random_getstate, METH_NOARGS,
457 PyDoc_STR("getstate() -> tuple containing the current state.")},
458 {"setstate", (PyCFunction)random_setstate, METH_O,
459 PyDoc_STR("setstate(state) -> None. Restores generator state.")},
460 {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
Serhiy Storchaka95949422013-08-27 19:40:23 +0300461 PyDoc_STR("getrandbits(k) -> x. Generates an int with "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 "k random bits.")},
463 {NULL, NULL} /* sentinel */
Raymond Hettinger40f62172002-12-29 23:03:38 +0000464};
465
466PyDoc_STRVAR(random_doc,
467"Random() -> create a random number generator with its own internal state.");
468
469static PyTypeObject Random_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PyVarObject_HEAD_INIT(NULL, 0)
471 "_random.Random", /*tp_name*/
472 sizeof(RandomObject), /*tp_basicsize*/
473 0, /*tp_itemsize*/
474 /* methods */
475 0, /*tp_dealloc*/
476 0, /*tp_print*/
477 0, /*tp_getattr*/
478 0, /*tp_setattr*/
479 0, /*tp_reserved*/
480 0, /*tp_repr*/
481 0, /*tp_as_number*/
482 0, /*tp_as_sequence*/
483 0, /*tp_as_mapping*/
484 0, /*tp_hash*/
485 0, /*tp_call*/
486 0, /*tp_str*/
487 PyObject_GenericGetAttr, /*tp_getattro*/
488 0, /*tp_setattro*/
489 0, /*tp_as_buffer*/
490 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
491 random_doc, /*tp_doc*/
492 0, /*tp_traverse*/
493 0, /*tp_clear*/
494 0, /*tp_richcompare*/
495 0, /*tp_weaklistoffset*/
496 0, /*tp_iter*/
497 0, /*tp_iternext*/
498 random_methods, /*tp_methods*/
499 0, /*tp_members*/
500 0, /*tp_getset*/
501 0, /*tp_base*/
502 0, /*tp_dict*/
503 0, /*tp_descr_get*/
504 0, /*tp_descr_set*/
505 0, /*tp_dictoffset*/
506 0, /*tp_init*/
507 0, /*tp_alloc*/
508 random_new, /*tp_new*/
509 PyObject_Free, /*tp_free*/
510 0, /*tp_is_gc*/
Raymond Hettinger40f62172002-12-29 23:03:38 +0000511};
512
513PyDoc_STRVAR(module_doc,
514"Module implements the Mersenne Twister random number generator.");
515
Martin v. Löwis1a214512008-06-11 05:26:20 +0000516
517static struct PyModuleDef _randommodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 PyModuleDef_HEAD_INIT,
519 "_random",
520 module_doc,
521 -1,
522 NULL,
523 NULL,
524 NULL,
525 NULL,
526 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000527};
528
Raymond Hettinger40f62172002-12-29 23:03:38 +0000529PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000530PyInit__random(void)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyObject *m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (PyType_Ready(&Random_Type) < 0)
535 return NULL;
536 m = PyModule_Create(&_randommodule);
537 if (m == NULL)
538 return NULL;
539 Py_INCREF(&Random_Type);
540 PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
541 return m;
Raymond Hettinger40f62172002-12-29 23:03:38 +0000542}