1 | /* |
2 | Copyright (c) 2005-2019 Intel Corporation |
3 | |
4 | Licensed under the Apache License, Version 2.0 (the "License"); |
5 | you may not use this file except in compliance with the License. |
6 | You may obtain a copy of the License at |
7 | |
8 | http://www.apache.org/licenses/LICENSE-2.0 |
9 | |
10 | Unless required by applicable law or agreed to in writing, software |
11 | distributed under the License is distributed on an "AS IS" BASIS, |
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | See the License for the specific language governing permissions and |
14 | limitations under the License. |
15 | */ |
16 | |
17 | #ifndef FAST_RANDOM_H_ |
18 | #define FAST_RANDOM_H_ |
19 | namespace utility{ |
20 | //------------------------------------------------------------------------ |
21 | // FastRandom |
22 | //------------------------------------------------------------------------ |
23 | |
24 | namespace internal{ |
25 | size_t GetPrime ( size_t seed ); |
26 | } |
27 | |
28 | //! A fast random number generator. |
29 | /** Uses linear congruential method. */ |
30 | class FastRandom { |
31 | size_t x, a; |
32 | public: |
33 | //! Get a random number. |
34 | unsigned short get() { |
35 | return get(x); |
36 | } |
37 | //! Get a random number for the given seed; update the seed for next use. |
38 | unsigned short get( size_t& seed ) { |
39 | unsigned short r = (unsigned short)(seed>>16); |
40 | seed = seed*a+1; |
41 | return r; |
42 | } |
43 | //! Construct a random number generator. |
44 | FastRandom( size_t seed ) { |
45 | x = seed*internal::GetPrime(seed); |
46 | a = internal::GetPrime(x); |
47 | } |
48 | }; |
49 | } |
50 | |
51 | namespace utility { |
52 | namespace internal{ |
53 | //! Table of primes used by fast random-number generator (FastRandom). |
54 | static const unsigned Primes[] = { |
55 | 0x9e3779b1, 0xffe6cc59, 0x2109f6dd, 0x43977ab5, |
56 | 0xba5703f5, 0xb495a877, 0xe1626741, 0x79695e6b, |
57 | 0xbc98c09f, 0xd5bee2b3, 0x287488f9, 0x3af18231, |
58 | 0x9677cd4d, 0xbe3a6929, 0xadc6a877, 0xdcf0674b, |
59 | 0xbe4d6fe9, 0x5f15e201, 0x99afc3fd, 0xf3f16801, |
60 | 0xe222cfff, 0x24ba5fdb, 0x0620452d, 0x79f149e3, |
61 | 0xc8b93f49, 0x972702cd, 0xb07dd827, 0x6c97d5ed, |
62 | 0x085a3d61, 0x46eb5ea7, 0x3d9910ed, 0x2e687b5b, |
63 | 0x29609227, 0x6eb081f1, 0x0954c4e1, 0x9d114db9, |
64 | 0x542acfa9, 0xb3e6bd7b, 0x0742d917, 0xe9f3ffa7, |
65 | 0x54581edb, 0xf2480f45, 0x0bb9288f, 0xef1affc7, |
66 | 0x85fa0ca7, 0x3ccc14db, 0xe6baf34b, 0x343377f7, |
67 | 0x5ca19031, 0xe6d9293b, 0xf0a9f391, 0x5d2e980b, |
68 | 0xfc411073, 0xc3749363, 0xb892d829, 0x3549366b, |
69 | 0x629750ad, 0xb98294e5, 0x892d9483, 0xc235baf3, |
70 | 0x3d2402a3, 0x6bdef3c9, 0xbec333cd, 0x40c9520f |
71 | }; |
72 | size_t GetPrime ( size_t seed ) { |
73 | return Primes[seed%(sizeof(Primes)/sizeof(Primes[0]))]; |
74 | } |
75 | } |
76 | } |
77 | |
78 | #endif /* FAST_RANDOM_H_ */ |
79 | |