Skip to main content

Random.ixx File

Utility class for pseudo-random number generation. More...

Included Headers

#include <cstdint> #include <random>

Namespaces Index

namespacehelios
namespaceutil

Utility functions and helper classes. More...

Classes Index

classRandom

Utility class for generating pseudo-random numbers. More...

Description

Utility class for pseudo-random number generation.

File Listing

The file content with the documentation metadata removed is:

1/**
2 * @file Random.ixx
3 * @brief Utility class for pseudo-random number generation.
4 */
5module;
6
7#include <cstdint>
8#include <random>
9
10export module helios.util.Random;
11
12
13export namespace helios::util {
14
15 /**
16 * @brief Utility class for generating pseudo-random numbers.
17 *
18 * @details This class provides a random number generator based on the
19 * Mersenne Twister algorithm (`std::mt19937`).
20 *
21 * Example usage:
22 * ```cpp
23 * auto rng = helios::util::Random(12345);
24 * float value = rng.randomFloat(0.0f, 1.0f);
25 * ```
26 */
27 class Random {
28
29 private:
30
31 /**
32 * @brief The Mersenne Twister pseudo-random number generator.
33 */
34 std::mt19937 gen_;
35
36 /**
37 * @brief Uniform real distribution for generating floating-point numbers.
38 *
39 * @see https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
40 */
41 std::uniform_real_distribution<float> uniformDist_;
42
43 /**
44 * @brief The initial seed used to initialize the generator.
45 *
46 * @details Stored for use by `reset()` to restore the generator to its
47 * initial state.
48 */
49 uint32_t initialSeed_;
50
51 public:
52
53 /**
54 * @brief Initializes the generator with the provided seed value.
55 *
56 * @param seed The seed value for the random number generator.
57 */
58 explicit Random(const uint32_t seed) : gen_(seed), initialSeed_(seed) {};
59
60 /**
61 * @brief Resets the generator to its initial state.
62 *
63 * @details Re-seeds the generator with the original seed value and
64 * resets the distribution state. Useful for reproducible sequences.
65 */
66 void reset() {
67 gen_.seed(initialSeed_);
68
69 uniformDist_.reset();
70 }
71
72 /**
73 * @brief Generates a pseudo-random float in the range [a, b).
74 *
75 * @details Uses `std::uniform_real_distribution` to generate a uniformly
76 * distributed floating-point number.
77 *
78 * @param a The lower bound of the range (inclusive).
79 * @param b The upper bound of the range (exclusive).
80 *
81 * @return A random float value in the range [a, b).
82 *
83 * @see https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
84 */
85 [[nodiscard]] float randomFloat(float a, float b) noexcept {
86
87 if (b < a) {
88 auto tmp = a; a = b; b = tmp;
89 }
90
91 if (a == b) {
92 return a;
93 }
94
95 return uniformDist_(
96 gen_,
97 std::uniform_real_distribution<float>::param_type{a, b}
98 );
99 }
100
101 };
102
103
104}

Generated via doxygen2docusaurus 2.0.0 by Doxygen 1.15.0.