random.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "pocketpy/random.h"
  2. #if PK_MODULE_RANDOM
  3. #include <random>
  4. namespace pkpy{
  5. struct Random{
  6. PY_CLASS(Random, random, Random)
  7. std::mt19937 gen;
  8. Random(){
  9. gen.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
  10. }
  11. static void _register(VM* vm, PyObject* mod, PyObject* type){
  12. vm->bind_default_constructor<Random>(type);
  13. vm->bind_method<1>(type, "seed", [](VM* vm, ArgsView args) {
  14. Random& self = _CAST(Random&, args[0]);
  15. self.gen.seed(CAST(i64, args[1]));
  16. return vm->None;
  17. });
  18. vm->bind_method<2>(type, "randint", [](VM* vm, ArgsView args) {
  19. Random& self = _CAST(Random&, args[0]);
  20. i64 a = CAST(i64, args[1]);
  21. i64 b = CAST(i64, args[2]);
  22. std::uniform_int_distribution<i64> dis(a, b);
  23. return VAR(dis(self.gen));
  24. });
  25. vm->bind_method<0>(type, "random", [](VM* vm, ArgsView args) {
  26. Random& self = _CAST(Random&, args[0]);
  27. std::uniform_real_distribution<f64> dis(0.0, 1.0);
  28. return VAR(dis(self.gen));
  29. });
  30. vm->bind_method<2>(type, "uniform", [](VM* vm, ArgsView args) {
  31. Random& self = _CAST(Random&, args[0]);
  32. f64 a = CAST(f64, args[1]);
  33. f64 b = CAST(f64, args[2]);
  34. std::uniform_real_distribution<f64> dis(a, b);
  35. return VAR(dis(self.gen));
  36. });
  37. }
  38. };
  39. void add_module_random(VM* vm){
  40. PyObject* mod = vm->new_module("random");
  41. Random::register_class(vm, mod);
  42. CodeObject_ code = vm->compile(kPythonLibs["random"], "random.py", EXEC_MODE);
  43. vm->_exec(code, mod);
  44. }
  45. } // namespace pkpy
  46. #else
  47. namespace pkpy{
  48. void add_module_random(VM* vm){ (void)vm; }
  49. } // namespace pkpy
  50. #endif