modrandom.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2016 Paul Sokolovsky
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <assert.h>
  27. #include <string.h>
  28. #include "py/runtime.h"
  29. #if MICROPY_PY_RANDOM
  30. // Work out if the seed will be set on import or not.
  31. #if MICROPY_MODULE_BUILTIN_INIT && defined(MICROPY_PY_RANDOM_SEED_INIT_FUNC)
  32. #define SEED_ON_IMPORT (1)
  33. #else
  34. #define SEED_ON_IMPORT (0)
  35. #endif
  36. // Yasmarang random number generator
  37. // by Ilya Levin
  38. // http://www.literatecode.com/yasmarang
  39. // Public Domain
  40. #if !MICROPY_ENABLE_DYNRUNTIME
  41. #if SEED_ON_IMPORT
  42. // If the state is seeded on import then keep these variables in the BSS.
  43. static uint32_t yasmarang_pad, yasmarang_n, yasmarang_d;
  44. static uint8_t yasmarang_dat;
  45. #else
  46. // Without seed-on-import these variables must be initialised via the data section.
  47. static uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233;
  48. static uint8_t yasmarang_dat = 0;
  49. #endif
  50. #endif
  51. static uint32_t yasmarang(void) {
  52. yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n;
  53. yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29);
  54. yasmarang_n = yasmarang_pad | 2;
  55. yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 1);
  56. yasmarang_dat ^= (char)yasmarang_pad ^ (yasmarang_d >> 8) ^ 1;
  57. return yasmarang_pad ^ (yasmarang_d << 5) ^ (yasmarang_pad >> 18) ^ (yasmarang_dat << 1);
  58. } /* yasmarang */
  59. // End of Yasmarang
  60. #if MICROPY_PY_RANDOM_EXTRA_FUNCS
  61. // returns an unsigned integer below the given argument
  62. // n must not be zero
  63. static uint32_t yasmarang_randbelow(uint32_t n) {
  64. uint32_t mask = 1;
  65. while ((n & mask) < n) {
  66. mask = (mask << 1) | 1;
  67. }
  68. uint32_t r;
  69. do {
  70. r = yasmarang() & mask;
  71. } while (r >= n);
  72. return r;
  73. }
  74. #endif
  75. static mp_obj_t mod_random_getrandbits(mp_obj_t num_in) {
  76. mp_int_t n = mp_obj_get_int(num_in);
  77. if (n > 32 || n < 0) {
  78. mp_raise_ValueError(MP_ERROR_TEXT("bits must be 32 or less"));
  79. }
  80. if (n == 0) {
  81. return MP_OBJ_NEW_SMALL_INT(0);
  82. }
  83. uint32_t mask = ~0;
  84. // Beware of C undefined behavior when shifting by >= than bit size
  85. mask >>= (32 - n);
  86. return mp_obj_new_int_from_uint(yasmarang() & mask);
  87. }
  88. static MP_DEFINE_CONST_FUN_OBJ_1(mod_random_getrandbits_obj, mod_random_getrandbits);
  89. static mp_obj_t mod_random_seed(size_t n_args, const mp_obj_t *args) {
  90. mp_uint_t seed;
  91. if (n_args == 0 || args[0] == mp_const_none) {
  92. #ifdef MICROPY_PY_RANDOM_SEED_INIT_FUNC
  93. seed = MICROPY_PY_RANDOM_SEED_INIT_FUNC;
  94. #else
  95. mp_raise_ValueError(MP_ERROR_TEXT("no default seed"));
  96. #endif
  97. } else {
  98. seed = mp_obj_get_int_truncated(args[0]);
  99. }
  100. yasmarang_pad = (uint32_t)seed;
  101. yasmarang_n = 69;
  102. yasmarang_d = 233;
  103. yasmarang_dat = 0;
  104. return mp_const_none;
  105. }
  106. static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_random_seed_obj, 0, 1, mod_random_seed);
  107. #if MICROPY_PY_RANDOM_EXTRA_FUNCS
  108. static mp_obj_t mod_random_randrange(size_t n_args, const mp_obj_t *args) {
  109. mp_int_t start = mp_obj_get_int(args[0]);
  110. if (n_args == 1) {
  111. // range(stop)
  112. if (start > 0) {
  113. return mp_obj_new_int(yasmarang_randbelow((uint32_t)start));
  114. } else {
  115. goto error;
  116. }
  117. } else {
  118. mp_int_t stop = mp_obj_get_int(args[1]);
  119. if (n_args == 2) {
  120. // range(start, stop)
  121. if (start < stop) {
  122. return mp_obj_new_int(start + yasmarang_randbelow((uint32_t)(stop - start)));
  123. } else {
  124. goto error;
  125. }
  126. } else {
  127. // range(start, stop, step)
  128. mp_int_t step = mp_obj_get_int(args[2]);
  129. mp_int_t n;
  130. if (step > 0) {
  131. n = (stop - start + step - 1) / step;
  132. } else if (step < 0) {
  133. n = (stop - start + step + 1) / step;
  134. } else {
  135. goto error;
  136. }
  137. if (n > 0) {
  138. return mp_obj_new_int(start + step * yasmarang_randbelow((uint32_t)n));
  139. } else {
  140. goto error;
  141. }
  142. }
  143. }
  144. error:
  145. mp_raise_ValueError(NULL);
  146. }
  147. static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_random_randrange_obj, 1, 3, mod_random_randrange);
  148. static mp_obj_t mod_random_randint(mp_obj_t a_in, mp_obj_t b_in) {
  149. mp_int_t a = mp_obj_get_int(a_in);
  150. mp_int_t b = mp_obj_get_int(b_in);
  151. if (a <= b) {
  152. return mp_obj_new_int(a + yasmarang_randbelow((uint32_t)(b - a + 1)));
  153. } else {
  154. mp_raise_ValueError(NULL);
  155. }
  156. }
  157. static MP_DEFINE_CONST_FUN_OBJ_2(mod_random_randint_obj, mod_random_randint);
  158. static mp_obj_t mod_random_choice(mp_obj_t seq) {
  159. mp_int_t len = mp_obj_get_int(mp_obj_len(seq));
  160. if (len > 0) {
  161. return mp_obj_subscr(seq, mp_obj_new_int(yasmarang_randbelow((uint32_t)len)), MP_OBJ_SENTINEL);
  162. } else {
  163. mp_raise_type(&mp_type_IndexError);
  164. }
  165. }
  166. static MP_DEFINE_CONST_FUN_OBJ_1(mod_random_choice_obj, mod_random_choice);
  167. #if MICROPY_PY_BUILTINS_FLOAT
  168. // returns a number in the range [0..1) using Yasmarang to fill in the fraction bits
  169. static mp_float_t yasmarang_float(void) {
  170. mp_float_union_t u;
  171. u.p.sgn = 0;
  172. u.p.exp = (1 << (MP_FLOAT_EXP_BITS - 1)) - 1;
  173. if (MP_FLOAT_FRAC_BITS <= 32) {
  174. u.p.frc = yasmarang();
  175. } else {
  176. u.p.frc = ((uint64_t)yasmarang() << 32) | (uint64_t)yasmarang();
  177. }
  178. return u.f - 1;
  179. }
  180. static mp_obj_t mod_random_random(void) {
  181. return mp_obj_new_float(yasmarang_float());
  182. }
  183. static MP_DEFINE_CONST_FUN_OBJ_0(mod_random_random_obj, mod_random_random);
  184. static mp_obj_t mod_random_uniform(mp_obj_t a_in, mp_obj_t b_in) {
  185. mp_float_t a = mp_obj_get_float(a_in);
  186. mp_float_t b = mp_obj_get_float(b_in);
  187. return mp_obj_new_float(a + (b - a) * yasmarang_float());
  188. }
  189. static MP_DEFINE_CONST_FUN_OBJ_2(mod_random_uniform_obj, mod_random_uniform);
  190. #endif
  191. #endif // MICROPY_PY_RANDOM_EXTRA_FUNCS
  192. #if SEED_ON_IMPORT
  193. static mp_obj_t mod_random___init__(void) {
  194. // This module may be imported by more than one name so need to ensure
  195. // that it's only ever seeded once.
  196. static bool seeded = false;
  197. if (!seeded) {
  198. seeded = true;
  199. mod_random_seed(0, NULL);
  200. }
  201. return mp_const_none;
  202. }
  203. static MP_DEFINE_CONST_FUN_OBJ_0(mod_random___init___obj, mod_random___init__);
  204. #endif
  205. #if !MICROPY_ENABLE_DYNRUNTIME
  206. static const mp_rom_map_elem_t mp_module_random_globals_table[] = {
  207. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_random) },
  208. #if SEED_ON_IMPORT
  209. { MP_ROM_QSTR(MP_QSTR___init__), MP_ROM_PTR(&mod_random___init___obj) },
  210. #endif
  211. { MP_ROM_QSTR(MP_QSTR_getrandbits), MP_ROM_PTR(&mod_random_getrandbits_obj) },
  212. { MP_ROM_QSTR(MP_QSTR_seed), MP_ROM_PTR(&mod_random_seed_obj) },
  213. #if MICROPY_PY_RANDOM_EXTRA_FUNCS
  214. { MP_ROM_QSTR(MP_QSTR_randrange), MP_ROM_PTR(&mod_random_randrange_obj) },
  215. { MP_ROM_QSTR(MP_QSTR_randint), MP_ROM_PTR(&mod_random_randint_obj) },
  216. { MP_ROM_QSTR(MP_QSTR_choice), MP_ROM_PTR(&mod_random_choice_obj) },
  217. #if MICROPY_PY_BUILTINS_FLOAT
  218. { MP_ROM_QSTR(MP_QSTR_random), MP_ROM_PTR(&mod_random_random_obj) },
  219. { MP_ROM_QSTR(MP_QSTR_uniform), MP_ROM_PTR(&mod_random_uniform_obj) },
  220. #endif
  221. #endif
  222. };
  223. static MP_DEFINE_CONST_DICT(mp_module_random_globals, mp_module_random_globals_table);
  224. const mp_obj_module_t mp_module_random = {
  225. .base = { &mp_type_module },
  226. .globals = (mp_obj_dict_t *)&mp_module_random_globals,
  227. };
  228. MP_REGISTER_EXTENSIBLE_MODULE(MP_QSTR_random, mp_module_random);
  229. #endif
  230. #endif // MICROPY_PY_RANDOM