MiniDNN
RNG.h
1 #ifndef RNG_H_
2 #define RNG_H_
3 
4 namespace MiniDNN {
5 
6 
13 class RNG
14 {
15 private:
16  const unsigned int m_a; // multiplier
17  const unsigned long m_max; // 2^31 - 1
18  long m_rand;
19 
20  inline long next_long_rand(long seed)
21  {
22  unsigned long lo, hi;
23 
24  lo = m_a * (long)(seed & 0xFFFF);
25  hi = m_a * (long)((unsigned long)seed >> 16);
26  lo += (hi & 0x7FFF) << 16;
27  if(lo > m_max)
28  {
29  lo &= m_max;
30  ++lo;
31  }
32  lo += hi >> 15;
33  if(lo > m_max)
34  {
35  lo &= m_max;
36  ++lo;
37  }
38  return (long)lo;
39  }
40 public:
41  RNG(unsigned long init_seed) :
42  m_a(16807),
43  m_max(2147483647L),
44  m_rand(init_seed ? (init_seed & m_max) : 1)
45  {}
46 
47  virtual ~RNG() {}
48 
49  virtual void seed(unsigned long seed)
50  {
51  m_rand = (seed ? (seed & m_max) : 1);
52  }
53 
54  virtual double rand()
55  {
56  m_rand = next_long_rand(m_rand);
57  return double(m_rand) / double(m_max);
58  }
59 };
60 
61 
62 } // namespace MiniDNN
63 
64 
65 #endif /* RNG_H_ */