Euphoria
rng.h
Go to the documentation of this file.
1 #pragma once
2 
3 
4 #include <limits>
5 
6 #include "base/ints.h"
7 
8 
9 namespace eu::core
10 {
11  // https://en.wikipedia.org/wiki/Linear_congruential_generator
12  template<typename I, I a, I c, I modulus>
13  struct RandomLcg
14  {
15  I state;
16 
17  explicit RandomLcg(I s)
18  : state(s)
19  {
20  }
21 
22  // bug: doesn't seem to return the full 0-1 range
24  {
25  state = (a * state + c) % modulus;
26  return static_cast<float>(state)/static_cast<float>(modulus);
27  }
28  };
29 
30 
31  using RandomLnuthLcg = RandomLcg<U64, std::numeric_limits<U64>::max() /* 2^64 */, 6364136223846793005, 1442695040888963407>;
32 
33 
34  // https://en.wikipedia.org/wiki/Xorshift
35  template<typename I, I a, I b, I c>
37  {
38  I state;
39 
40  explicit RandomXorShift(I s)
41  : state(s)
42  {
43  }
44 
46  {
47  /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
48  I x = state;
49  x ^= x << a;
50  x ^= x >> b;
51  x ^= x << c;
52  state = x;
53  return state;
54  }
55 
57  {
58  const auto r = get_next_integer();
59  const auto max = static_cast<float>(std::numeric_limits<I>::max());
60  return static_cast<float>(r) / max;
61  }
62  };
63 
64 
67 }
68 
size2f max(const size2f lhs, const size2f rhs)
Definition: size2.cc:149
RandomLcg(I s)
Definition: rng.h:17
float get_next_float01()
Definition: rng.h:23
float get_next_float01()
Definition: rng.h:56