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.

37 lines
812B

  1. #include "cmwc.hh"
  2. #include <stdlib.h>
  3. static
  4. uint32_t rand32(void) {
  5. uint32_t result = rand();
  6. return result << 16 | rand();
  7. }
  8. void cmwc::seed(unsigned int seed) {
  9. srand(seed);
  10. for (int i = 0; i < CMWC_CYCLE; i++)
  11. this->Q[i] = rand32();
  12. do
  13. this->c = rand32();
  14. while (this->c >= CMWC_C_MAX);
  15. this->i = CMWC_CYCLE - 1;
  16. }
  17. uint32_t cmwc::next() {
  18. uint64_t const a = 18782; // as Marsaglia recommends
  19. uint32_t const m = 0xfffffffe; // as Marsaglia recommends
  20. uint64_t t;
  21. uint32_t x;
  22. this->i = (this->i + 1) & (CMWC_CYCLE - 1);
  23. t = a * this->Q[this->i] + this->c;
  24. /* Let c = t / 0xfffffff, x = t mod 0xffffffff */
  25. this->c = t >> 32;
  26. x = t + this->c;
  27. if (x < this->c) {
  28. x++;
  29. this->c++;
  30. }
  31. return this->Q[this->i] = m - x;
  32. }