You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

random.cpp 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <random.hpp>
  2. #include <math.hpp>
  3. #include <time.h>
  4. #include <sys/time.h>
  5. namespace rack {
  6. namespace random {
  7. // xoroshiro128+
  8. // from http://xoroshiro.di.unimi.it/xoroshiro128plus.c
  9. thread_local uint64_t xoroshiro128plus_state[2];
  10. static uint64_t rotl(const uint64_t x, int k) {
  11. return (x << k) | (x >> (64 - k));
  12. }
  13. static uint64_t xoroshiro128plus_next(void) {
  14. const uint64_t s0 = xoroshiro128plus_state[0];
  15. uint64_t s1 = xoroshiro128plus_state[1];
  16. const uint64_t result = s0 + s1;
  17. s1 ^= s0;
  18. xoroshiro128plus_state[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b
  19. xoroshiro128plus_state[1] = rotl(s1, 36); // c
  20. return result;
  21. }
  22. void init() {
  23. struct timeval tv;
  24. gettimeofday(&tv, NULL);
  25. xoroshiro128plus_state[0] = tv.tv_sec;
  26. xoroshiro128plus_state[1] = tv.tv_usec;
  27. // Generate a few times to fix the fact that the time is not a uniform u64
  28. for (int i = 0; i < 10; i++) {
  29. xoroshiro128plus_next();
  30. }
  31. }
  32. uint32_t u32() {
  33. return xoroshiro128plus_next() >> 32;
  34. }
  35. uint64_t u64() {
  36. return xoroshiro128plus_next();
  37. }
  38. float uniform() {
  39. return (xoroshiro128plus_next() >> (64 - 24)) / std::pow(2.f, 24);
  40. }
  41. float normal() {
  42. // Box-Muller transform
  43. float radius = std::sqrt(-2.f * std::log(1.f - uniform()));
  44. float theta = 2.f * M_PI * uniform();
  45. return radius * std::sin(theta);
  46. // // Central Limit Theorem
  47. // const int n = 8;
  48. // float sum = 0.0;
  49. // for (int i = 0; i < n; i++) {
  50. // sum += uniform();
  51. // }
  52. // return (sum - n / 2.f) / std::sqrt(n / 12.f);
  53. }
  54. } // namespace random
  55. } // namespace rack