random.h 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2012-2014 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #pragma once
  6. namespace crown
  7. {
  8. /// Pseudo-random number generator.
  9. ///
  10. /// Uses LCG algorithm: fast and compatible with the standard C rand().
  11. struct Random
  12. {
  13. /// Initializes the generator with the given @a seed.
  14. Random(int32_t seed);
  15. /// Returns a pseudo-random integer in the range [0, 32767].
  16. int32_t integer();
  17. /// Returns a pseudo-random integer in the range [0, max).
  18. int32_t integer(int32_t max);
  19. /// Returns a pseudo-random float in the range [0.0, 1.0].
  20. float unit_float();
  21. private:
  22. int32_t _seed;
  23. };
  24. inline Random::Random(int32_t seed) : _seed(seed)
  25. {
  26. }
  27. inline int32_t Random::integer()
  28. {
  29. _seed = 214013 * _seed + 13737667;
  30. return (_seed >> 16) & 0x7FFF;
  31. }
  32. inline int32_t Random::integer(int32_t max)
  33. {
  34. return (max == 0) ? 0 : integer() % max;
  35. }
  36. inline float Random::unit_float()
  37. {
  38. return integer() / (float) 0x7FFF;
  39. }
  40. } // namespace crown