gKit2 light
Loading...
Searching...
No Matches
crng.h
Go to the documentation of this file.
1
3
4#ifndef _CRNG_H
5#define _CRNG_H
6
7#include <cstdint>
8
9
10// counter based rng, 32 bits
11// periode 2^32
12struct CRNG32
13{
14 CRNG32( ) : n(), key() { seed(123451); }
15 CRNG32( const unsigned s ) : n(), key() { seed(s); }
16 void seed( const unsigned s ) { n= 0; key= (s << 1) | 1; }
17
18 CRNG32& index( const unsigned i ) { n= i; return *this;}
19 unsigned sample( ){ return hash(++n * key); }
20
21 unsigned sample_range( const unsigned range )
22 {
23 // Efficiently Generating a Number in a Range
24 // cf http://www.pcg-random.org/posts/bounded-rands.html
25 unsigned divisor= ((-range) / range) + 1; // (2^32) / range
26 if(divisor == 0) return 0;
27
28 while(true)
29 {
30 unsigned x= sample() / divisor;
31 if(x < range) return x;
32 }
33 }
34
35 // c++ interface
36 unsigned operator() ( ) { return sample(); }
37 static constexpr unsigned min( ) { return 0; }
38 static constexpr unsigned max( ) { return ~unsigned(0); }
39 typedef unsigned result_type;
40
41 // 2 rounds
42 unsigned hash( unsigned x )
43 {
44 x ^= x >> 16;
45 x *= 0x21f0aaad;
46 x ^= x >> 15;
47 x *= 0xd35a2d97;
48 x ^= x >> 15;
49 return x;
50 }
51 // cf "hash prospector" https://github.com/skeeto/hash-prospector/blob/master/README.md
52
53 unsigned n;
54 unsigned key;
55};
56
57
58// counter based rng, 64 bits
59// periode 2^64
60struct CRNG64
61{
62 CRNG64( ) : n(), key() { seed64(0xc58efd154ce32f6d); }
63 CRNG64( const uint64_t s ) : n(), key() { seed64(s); }
64 CRNG64( const unsigned hi, const unsigned lo= 0x40ba6a95 ) : n(), key() { seed(hi, lo); }
65
66 void seed( const unsigned hi, const unsigned lo= 0x40ba6a95 ) { seed64( uint64_t(hi) << 32 | uint64_t(lo) ); }
67 void seed64( const uint64_t s ) { n= 0; key= (s << 1) | 1; }
68
69 CRNG64& index( const uint64_t i ) { n= i; return *this;}
70 unsigned sample( ) { return hash(++n * key); }
71
72 unsigned sample_range( const unsigned range )
73 {
74 // Efficiently Generating a Number in a Range
75 // cf http://www.pcg-random.org/posts/bounded-rands.html
76 unsigned divisor= ((-range) / range) + 1; // (2^32) / range
77 if(divisor == 0) return 0;
78
79 while(true)
80 {
81 unsigned x= sample() / divisor;
82 if(x < range) return x;
83 }
84 }
85
86 // c++ interface
87 unsigned operator() ( ) { return sample(); }
88 static constexpr unsigned min( ) { return 0; }
89 static constexpr unsigned max( ) { return ~unsigned(0); }
90 typedef unsigned result_type;
91
92 unsigned hash( uint64_t v )
93 {
94 v ^= (v >> 31);
95 v *= 0x7fb5d329728ea185;
96 v ^= (v >> 27);
97 v *= 0x81dadef4bc2dd44d;
98 v ^= (v >> 33);
99 return v;
100 }
101 // cf "hash prospector" https://github.com/skeeto/hash-prospector/blob/master/README.md
102
103 uint64_t n;
104 uint64_t key;
105};
106
107#endif