]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.2/Modules/_randommodule.c
EmbeddedPkg: Extend NvVarStoreFormattedLib LIBRARY_CLASS
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.2 / Modules / _randommodule.c
CommitLineData
4710c53d 1/* Random objects */\r
2\r
3/* ------------------------------------------------------------------\r
4 The code in this module was based on a download from:\r
5 http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html\r
6\r
7 It was modified in 2002 by Raymond Hettinger as follows:\r
8\r
9 * the principal computational lines untouched.\r
10\r
11 * renamed genrand_res53() to random_random() and wrapped\r
12 in python calling/return code.\r
13\r
14 * genrand_int32() and the helper functions, init_genrand()\r
15 and init_by_array(), were declared static, wrapped in\r
16 Python calling/return code. also, their global data\r
17 references were replaced with structure references.\r
18\r
19 * unused functions from the original were deleted.\r
20 new, original C python code was added to implement the\r
21 Random() interface.\r
22\r
23 The following are the verbatim comments from the original code:\r
24\r
25 A C-program for MT19937, with initialization improved 2002/1/26.\r
26 Coded by Takuji Nishimura and Makoto Matsumoto.\r
27\r
28 Before using, initialize the state by using init_genrand(seed)\r
29 or init_by_array(init_key, key_length).\r
30\r
31 Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,\r
32 All rights reserved.\r
33\r
34 Redistribution and use in source and binary forms, with or without\r
35 modification, are permitted provided that the following conditions\r
36 are met:\r
37\r
38 1. Redistributions of source code must retain the above copyright\r
39 notice, this list of conditions and the following disclaimer.\r
40\r
41 2. Redistributions in binary form must reproduce the above copyright\r
42 notice, this list of conditions and the following disclaimer in the\r
43 documentation and/or other materials provided with the distribution.\r
44\r
45 3. The names of its contributors may not be used to endorse or promote\r
46 products derived from this software without specific prior written\r
47 permission.\r
48\r
49 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
50 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
51 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
52 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\r
53 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
54 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
55 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r
56 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r
57 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
58 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r
59 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
60\r
61\r
62 Any feedback is very welcome.\r
63 http://www.math.keio.ac.jp/matumoto/emt.html\r
64 email: matumoto@math.keio.ac.jp\r
65*/\r
66\r
67/* ---------------------------------------------------------------*/\r
68\r
69#include "Python.h"\r
70#include <time.h> /* for seeding to current time */\r
71\r
72/* Period parameters -- These are all magic. Don't change. */\r
73#define N 624\r
74#define M 397\r
75#define MATRIX_A 0x9908b0dfUL /* constant vector a */\r
76#define UPPER_MASK 0x80000000UL /* most significant w-r bits */\r
77#define LOWER_MASK 0x7fffffffUL /* least significant r bits */\r
78\r
79typedef struct {\r
80 PyObject_HEAD\r
81 unsigned long state[N];\r
82 int index;\r
83} RandomObject;\r
84\r
85static PyTypeObject Random_Type;\r
86\r
87#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)\r
88\r
89\r
90/* Random methods */\r
91\r
92\r
93/* generates a random number on [0,0xffffffff]-interval */\r
94static unsigned long\r
95genrand_int32(RandomObject *self)\r
96{\r
97 unsigned long y;\r
98 static unsigned long mag01[2]={0x0UL, MATRIX_A};\r
99 /* mag01[x] = x * MATRIX_A for x=0,1 */\r
100 unsigned long *mt;\r
101\r
102 mt = self->state;\r
103 if (self->index >= N) { /* generate N words at one time */\r
104 int kk;\r
105\r
106 for (kk=0;kk<N-M;kk++) {\r
107 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\r
108 mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];\r
109 }\r
110 for (;kk<N-1;kk++) {\r
111 y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\r
112 mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];\r
113 }\r
114 y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);\r
115 mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];\r
116\r
117 self->index = 0;\r
118 }\r
119\r
120 y = mt[self->index++];\r
121 y ^= (y >> 11);\r
122 y ^= (y << 7) & 0x9d2c5680UL;\r
123 y ^= (y << 15) & 0xefc60000UL;\r
124 y ^= (y >> 18);\r
125 return y;\r
126}\r
127\r
128/* random_random is the function named genrand_res53 in the original code;\r
129 * generates a random number on [0,1) with 53-bit resolution; note that\r
130 * 9007199254740992 == 2**53; I assume they're spelling "/2**53" as\r
131 * multiply-by-reciprocal in the (likely vain) hope that the compiler will\r
132 * optimize the division away at compile-time. 67108864 is 2**26. In\r
133 * effect, a contains 27 random bits shifted left 26, and b fills in the\r
134 * lower 26 bits of the 53-bit numerator.\r
135 * The orginal code credited Isaku Wada for this algorithm, 2002/01/09.\r
136 */\r
137static PyObject *\r
138random_random(RandomObject *self)\r
139{\r
140 unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;\r
141 return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));\r
142}\r
143\r
144/* initializes mt[N] with a seed */\r
145static void\r
146init_genrand(RandomObject *self, unsigned long s)\r
147{\r
148 int mti;\r
149 unsigned long *mt;\r
150\r
151 mt = self->state;\r
152 mt[0]= s & 0xffffffffUL;\r
153 for (mti=1; mti<N; mti++) {\r
154 mt[mti] =\r
155 (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);\r
156 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\r
157 /* In the previous versions, MSBs of the seed affect */\r
158 /* only MSBs of the array mt[]. */\r
159 /* 2002/01/09 modified by Makoto Matsumoto */\r
160 mt[mti] &= 0xffffffffUL;\r
161 /* for >32 bit machines */\r
162 }\r
163 self->index = mti;\r
164 return;\r
165}\r
166\r
167/* initialize by an array with array-length */\r
168/* init_key is the array for initializing keys */\r
169/* key_length is its length */\r
170static PyObject *\r
171init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_length)\r
172{\r
173 unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */\r
174 unsigned long *mt;\r
175\r
176 mt = self->state;\r
177 init_genrand(self, 19650218UL);\r
178 i=1; j=0;\r
179 k = (N>key_length ? N : key_length);\r
180 for (; k; k--) {\r
181 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))\r
182 + init_key[j] + j; /* non linear */\r
183 mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */\r
184 i++; j++;\r
185 if (i>=N) { mt[0] = mt[N-1]; i=1; }\r
186 if (j>=key_length) j=0;\r
187 }\r
188 for (k=N-1; k; k--) {\r
189 mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))\r
190 - i; /* non linear */\r
191 mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */\r
192 i++;\r
193 if (i>=N) { mt[0] = mt[N-1]; i=1; }\r
194 }\r
195\r
196 mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */\r
197 Py_INCREF(Py_None);\r
198 return Py_None;\r
199}\r
200\r
201/*\r
202 * The rest is Python-specific code, neither part of, nor derived from, the\r
203 * Twister download.\r
204 */\r
205\r
206static PyObject *\r
207random_seed(RandomObject *self, PyObject *args)\r
208{\r
209 PyObject *result = NULL; /* guilty until proved innocent */\r
210 PyObject *masklower = NULL;\r
211 PyObject *thirtytwo = NULL;\r
212 PyObject *n = NULL;\r
213 unsigned long *key = NULL;\r
214 unsigned long keymax; /* # of allocated slots in key */\r
215 unsigned long keyused; /* # of used slots in key */\r
216 int err;\r
217\r
218 PyObject *arg = NULL;\r
219\r
220 if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))\r
221 return NULL;\r
222\r
223 if (arg == NULL || arg == Py_None) {\r
224 time_t now;\r
225\r
226 time(&now);\r
227 init_genrand(self, (unsigned long)now);\r
228 Py_INCREF(Py_None);\r
229 return Py_None;\r
230 }\r
231 /* If the arg is an int or long, use its absolute value; else use\r
232 * the absolute value of its hash code.\r
233 */\r
234 if (PyInt_Check(arg) || PyLong_Check(arg))\r
235 n = PyNumber_Absolute(arg);\r
236 else {\r
237 long hash = PyObject_Hash(arg);\r
238 if (hash == -1)\r
239 goto Done;\r
240 n = PyLong_FromUnsignedLong((unsigned long)hash);\r
241 }\r
242 if (n == NULL)\r
243 goto Done;\r
244\r
245 /* Now split n into 32-bit chunks, from the right. Each piece is\r
246 * stored into key, which has a capacity of keymax chunks, of which\r
247 * keyused are filled. Alas, the repeated shifting makes this a\r
248 * quadratic-time algorithm; we'd really like to use\r
249 * _PyLong_AsByteArray here, but then we'd have to break into the\r
250 * long representation to figure out how big an array was needed\r
251 * in advance.\r
252 */\r
253 keymax = 8; /* arbitrary; grows later if needed */\r
254 keyused = 0;\r
255 key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key));\r
256 if (key == NULL)\r
257 goto Done;\r
258\r
259 masklower = PyLong_FromUnsignedLong(0xffffffffU);\r
260 if (masklower == NULL)\r
261 goto Done;\r
262 thirtytwo = PyInt_FromLong(32L);\r
263 if (thirtytwo == NULL)\r
264 goto Done;\r
265 while ((err=PyObject_IsTrue(n))) {\r
266 PyObject *newn;\r
267 PyObject *pychunk;\r
268 unsigned long chunk;\r
269\r
270 if (err == -1)\r
271 goto Done;\r
272 pychunk = PyNumber_And(n, masklower);\r
273 if (pychunk == NULL)\r
274 goto Done;\r
275 chunk = PyLong_AsUnsignedLong(pychunk);\r
276 Py_DECREF(pychunk);\r
277 if (chunk == (unsigned long)-1 && PyErr_Occurred())\r
278 goto Done;\r
279 newn = PyNumber_Rshift(n, thirtytwo);\r
280 if (newn == NULL)\r
281 goto Done;\r
282 Py_DECREF(n);\r
283 n = newn;\r
284 if (keyused >= keymax) {\r
285 unsigned long bigger = keymax << 1;\r
286 if ((bigger >> 1) != keymax) {\r
287 PyErr_NoMemory();\r
288 goto Done;\r
289 }\r
290 key = (unsigned long *)PyMem_Realloc(key,\r
291 bigger * sizeof(*key));\r
292 if (key == NULL)\r
293 goto Done;\r
294 keymax = bigger;\r
295 }\r
296 assert(keyused < keymax);\r
297 key[keyused++] = chunk;\r
298 }\r
299\r
300 if (keyused == 0)\r
301 key[keyused++] = 0UL;\r
302 result = init_by_array(self, key, keyused);\r
303Done:\r
304 Py_XDECREF(masklower);\r
305 Py_XDECREF(thirtytwo);\r
306 Py_XDECREF(n);\r
307 PyMem_Free(key);\r
308 return result;\r
309}\r
310\r
311static PyObject *\r
312random_getstate(RandomObject *self)\r
313{\r
314 PyObject *state;\r
315 PyObject *element;\r
316 int i;\r
317\r
318 state = PyTuple_New(N+1);\r
319 if (state == NULL)\r
320 return NULL;\r
321 for (i=0; i<N ; i++) {\r
322 element = PyLong_FromUnsignedLong(self->state[i]);\r
323 if (element == NULL)\r
324 goto Fail;\r
325 PyTuple_SET_ITEM(state, i, element);\r
326 }\r
327 element = PyLong_FromLong((long)(self->index));\r
328 if (element == NULL)\r
329 goto Fail;\r
330 PyTuple_SET_ITEM(state, i, element);\r
331 return state;\r
332\r
333Fail:\r
334 Py_DECREF(state);\r
335 return NULL;\r
336}\r
337\r
338static PyObject *\r
339random_setstate(RandomObject *self, PyObject *state)\r
340{\r
341 int i;\r
342 unsigned long element;\r
343 long index;\r
344\r
345 if (!PyTuple_Check(state)) {\r
346 PyErr_SetString(PyExc_TypeError,\r
347 "state vector must be a tuple");\r
348 return NULL;\r
349 }\r
350 if (PyTuple_Size(state) != N+1) {\r
351 PyErr_SetString(PyExc_ValueError,\r
352 "state vector is the wrong size");\r
353 return NULL;\r
354 }\r
355\r
356 for (i=0; i<N ; i++) {\r
357 element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));\r
358 if (element == (unsigned long)-1 && PyErr_Occurred())\r
359 return NULL;\r
360 self->state[i] = element & 0xffffffffUL; /* Make sure we get sane state */\r
361 }\r
362\r
363 index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));\r
364 if (index == -1 && PyErr_Occurred())\r
365 return NULL;\r
366 self->index = (int)index;\r
367\r
368 Py_INCREF(Py_None);\r
369 return Py_None;\r
370}\r
371\r
372/*\r
373Jumpahead should be a fast way advance the generator n-steps ahead, but\r
374lacking a formula for that, the next best is to use n and the existing\r
375state to create a new state far away from the original.\r
376\r
377The generator uses constant spaced additive feedback, so shuffling the\r
378state elements ought to produce a state which would not be encountered\r
379(in the near term) by calls to random(). Shuffling is normally\r
380implemented by swapping the ith element with another element ranging\r
381from 0 to i inclusive. That allows the element to have the possibility\r
382of not being moved. Since the goal is to produce a new, different\r
383state, the swap element is ranged from 0 to i-1 inclusive. This assures\r
384that each element gets moved at least once.\r
385\r
386To make sure that consecutive calls to jumpahead(n) produce different\r
387states (even in the rare case of involutory shuffles), i+1 is added to\r
388each element at position i. Successive calls are then guaranteed to\r
389have changing (growing) values as well as shuffled positions.\r
390\r
391Finally, the self->index value is set to N so that the generator itself\r
392kicks in on the next call to random(). This assures that all results\r
393have been through the generator and do not just reflect alterations to\r
394the underlying state.\r
395*/\r
396\r
397static PyObject *\r
398random_jumpahead(RandomObject *self, PyObject *n)\r
399{\r
400 long i, j;\r
401 PyObject *iobj;\r
402 PyObject *remobj;\r
403 unsigned long *mt, tmp;\r
404\r
405 if (!PyInt_Check(n) && !PyLong_Check(n)) {\r
406 PyErr_Format(PyExc_TypeError, "jumpahead requires an "\r
407 "integer, not '%s'",\r
408 Py_TYPE(n)->tp_name);\r
409 return NULL;\r
410 }\r
411\r
412 mt = self->state;\r
413 for (i = N-1; i > 1; i--) {\r
414 iobj = PyInt_FromLong(i);\r
415 if (iobj == NULL)\r
416 return NULL;\r
417 remobj = PyNumber_Remainder(n, iobj);\r
418 Py_DECREF(iobj);\r
419 if (remobj == NULL)\r
420 return NULL;\r
421 j = PyInt_AsLong(remobj);\r
422 Py_DECREF(remobj);\r
423 if (j == -1L && PyErr_Occurred())\r
424 return NULL;\r
425 tmp = mt[i];\r
426 mt[i] = mt[j];\r
427 mt[j] = tmp;\r
428 }\r
429\r
430 for (i = 0; i < N; i++)\r
431 mt[i] += i+1;\r
432\r
433 self->index = N;\r
434 Py_INCREF(Py_None);\r
435 return Py_None;\r
436}\r
437\r
438static PyObject *\r
439random_getrandbits(RandomObject *self, PyObject *args)\r
440{\r
441 int k, i, bytes;\r
442 unsigned long r;\r
443 unsigned char *bytearray;\r
444 PyObject *result;\r
445\r
446 if (!PyArg_ParseTuple(args, "i:getrandbits", &k))\r
447 return NULL;\r
448\r
449 if (k <= 0) {\r
450 PyErr_SetString(PyExc_ValueError,\r
451 "number of bits must be greater than zero");\r
452 return NULL;\r
453 }\r
454\r
455 bytes = ((k - 1) / 32 + 1) * 4;\r
456 bytearray = (unsigned char *)PyMem_Malloc(bytes);\r
457 if (bytearray == NULL) {\r
458 PyErr_NoMemory();\r
459 return NULL;\r
460 }\r
461\r
462 /* Fill-out whole words, byte-by-byte to avoid endianness issues */\r
463 for (i=0 ; i<bytes ; i+=4, k-=32) {\r
464 r = genrand_int32(self);\r
465 if (k < 32)\r
466 r >>= (32 - k);\r
467 bytearray[i+0] = (unsigned char)r;\r
468 bytearray[i+1] = (unsigned char)(r >> 8);\r
469 bytearray[i+2] = (unsigned char)(r >> 16);\r
470 bytearray[i+3] = (unsigned char)(r >> 24);\r
471 }\r
472\r
473 /* little endian order to match bytearray assignment order */\r
474 result = _PyLong_FromByteArray(bytearray, bytes, 1, 0);\r
475 PyMem_Free(bytearray);\r
476 return result;\r
477}\r
478\r
479static PyObject *\r
480random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
481{\r
482 RandomObject *self;\r
483 PyObject *tmp;\r
484\r
485 if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))\r
486 return NULL;\r
487\r
488 self = (RandomObject *)type->tp_alloc(type, 0);\r
489 if (self == NULL)\r
490 return NULL;\r
491 tmp = random_seed(self, args);\r
492 if (tmp == NULL) {\r
493 Py_DECREF(self);\r
494 return NULL;\r
495 }\r
496 Py_DECREF(tmp);\r
497 return (PyObject *)self;\r
498}\r
499\r
500static PyMethodDef random_methods[] = {\r
501 {"random", (PyCFunction)random_random, METH_NOARGS,\r
502 PyDoc_STR("random() -> x in the interval [0, 1).")},\r
503 {"seed", (PyCFunction)random_seed, METH_VARARGS,\r
504 PyDoc_STR("seed([n]) -> None. Defaults to current time.")},\r
505 {"getstate", (PyCFunction)random_getstate, METH_NOARGS,\r
506 PyDoc_STR("getstate() -> tuple containing the current state.")},\r
507 {"setstate", (PyCFunction)random_setstate, METH_O,\r
508 PyDoc_STR("setstate(state) -> None. Restores generator state.")},\r
509 {"jumpahead", (PyCFunction)random_jumpahead, METH_O,\r
510 PyDoc_STR("jumpahead(int) -> None. Create new state from "\r
511 "existing state and integer.")},\r
512 {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,\r
513 PyDoc_STR("getrandbits(k) -> x. Generates a long int with "\r
514 "k random bits.")},\r
515 {NULL, NULL} /* sentinel */\r
516};\r
517\r
518PyDoc_STRVAR(random_doc,\r
519"Random() -> create a random number generator with its own internal state.");\r
520\r
521static PyTypeObject Random_Type = {\r
522 PyVarObject_HEAD_INIT(NULL, 0)\r
523 "_random.Random", /*tp_name*/\r
524 sizeof(RandomObject), /*tp_basicsize*/\r
525 0, /*tp_itemsize*/\r
526 /* methods */\r
527 0, /*tp_dealloc*/\r
528 0, /*tp_print*/\r
529 0, /*tp_getattr*/\r
530 0, /*tp_setattr*/\r
531 0, /*tp_compare*/\r
532 0, /*tp_repr*/\r
533 0, /*tp_as_number*/\r
534 0, /*tp_as_sequence*/\r
535 0, /*tp_as_mapping*/\r
536 0, /*tp_hash*/\r
537 0, /*tp_call*/\r
538 0, /*tp_str*/\r
539 PyObject_GenericGetAttr, /*tp_getattro*/\r
540 0, /*tp_setattro*/\r
541 0, /*tp_as_buffer*/\r
542 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\r
543 random_doc, /*tp_doc*/\r
544 0, /*tp_traverse*/\r
545 0, /*tp_clear*/\r
546 0, /*tp_richcompare*/\r
547 0, /*tp_weaklistoffset*/\r
548 0, /*tp_iter*/\r
549 0, /*tp_iternext*/\r
550 random_methods, /*tp_methods*/\r
551 0, /*tp_members*/\r
552 0, /*tp_getset*/\r
553 0, /*tp_base*/\r
554 0, /*tp_dict*/\r
555 0, /*tp_descr_get*/\r
556 0, /*tp_descr_set*/\r
557 0, /*tp_dictoffset*/\r
558 0, /*tp_init*/\r
559 0, /*tp_alloc*/\r
560 random_new, /*tp_new*/\r
561 _PyObject_Del, /*tp_free*/\r
562 0, /*tp_is_gc*/\r
563};\r
564\r
565PyDoc_STRVAR(module_doc,\r
566"Module implements the Mersenne Twister random number generator.");\r
567\r
568PyMODINIT_FUNC\r
569init_random(void)\r
570{\r
571 PyObject *m;\r
572\r
573 if (PyType_Ready(&Random_Type) < 0)\r
574 return;\r
575 m = Py_InitModule3("_random", NULL, module_doc);\r
576 if (m == NULL)\r
577 return;\r
578 Py_INCREF(&Random_Type);\r
579 PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);\r
580}\r