1 | /** |
2 | * Copyright (c) Glow Contributors. See CONTRIBUTORS file. |
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 | #ifndef GLOW_SUPPORT_RANDOM_H |
17 | #define GLOW_SUPPORT_RANDOM_H |
18 | |
19 | #include <random> |
20 | |
21 | namespace glow { |
22 | |
23 | /// A pseudo-random number generator. |
24 | /// |
25 | /// A PseudoRNG generates a deterministic sequence of numbers controlled by the |
26 | /// initial seed. Use the various templates from the <random> standard library |
27 | /// header to draw numbers from a specific distribution. |
28 | class PseudoRNG { |
29 | public: |
30 | /// Glow uses the Mersenne Twister engine. |
31 | typedef std::mt19937 Engine; |
32 | |
33 | private: |
34 | Engine engine_; |
35 | |
36 | public: |
37 | /// Get a freshly initialized pseudo-random number generator. |
38 | /// |
39 | /// All the generators created by this default constructor will generate the |
40 | /// same deterministic sequence of numbers, controlled by the |
41 | /// "-pseudo-random-seed" command line option. |
42 | PseudoRNG(); |
43 | |
44 | /// \returns a pseudo-random floating point number from the half-open range |
45 | /// [-1; 1). |
46 | double nextRand(); |
47 | |
48 | /// \returns a pseudo-random floating point number from the half-open |
49 | /// user-specified range [a; b). |
50 | double nextRandReal(double a, double b); |
51 | |
52 | /// \returns the next uniform random integer in the closed interval [a, b]. |
53 | int nextRandInt(int a, int b) { |
54 | return std::uniform_int_distribution<int>(a, b)(engine_); |
55 | } |
56 | |
57 | /// This typedef and the methods below implement the standard interface for a |
58 | /// random number generator. |
59 | typedef Engine::result_type result_type; |
60 | /// \returns the next pseudo-random number between min() and max(). |
61 | result_type operator()() { return engine_(); } |
62 | /// \returns the smallest possible value generated. |
63 | static constexpr result_type min() { return Engine::min(); } |
64 | /// \returns the largest possible value generated. |
65 | static constexpr result_type max() { return Engine::max(); } |
66 | }; |
67 | |
68 | } // namespace glow |
69 | |
70 | #endif // GLOW_SUPPORT_RANDOM_H |
71 | |