std::generate_canonical
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Numerics library
Mathematical special functions (C++17)
Mathematical constants (C++20)
Basic linear algebra algorithms (C++26)
Data-parallel types (SIMD) (C++26)
Floating-point environment (C++11)
Bit manipulation (C++20)
Saturation arithmetic (C++26)
(C++17)
(C++17)
(C++17)
(C++17)
(C++17)
(C++17)
Pseudo-random number generation
(C++20)
(C++11)
(C++11)
(C++11)
(C++26)
(C++11)
(C++11)
(C++11)
(C++11)
generate_canonical
(C++11)
(C++11)
(C++26)
(C++11)
(C++11)
generate_canonical
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Defined in header
<random>
template< class RealType, std::size_t Bits, class Generator >
RealType generate_canonical( Generator& g );
(since C++11)
RealType generate_canonical( Generator& g );
Generates a random floating point number in range [
0,
1)
.
To generate enough entropy, generate_canonical() will call g() exactly \(\small k\)k times, where \(\small k = \max(1, \lceil \frac{b}{\log_2 R} \rceil)\)k = max(1, ⌈ b / log2 R ⌉) and
- b = std::min (Bits, std::size_t {std::numeric_limits <RealType>::digits}),
- R = g.max() - g.min() + 1.
[edit] Parameters
g
-
generator to use to acquire entropy
[edit] Return value
Floating point value in range [
0,
1)
.
[edit] Exceptions
None except from those thrown by g.
[edit] Notes
Some existing implementations have a bug where they may occasionally return 1.0 if RealType
is float GCC #63176 LLVM #18767 MSVC STL #1074. This is LWG issue 2524.
[edit] Example
Produce random numbers with 10 bits of randomness: this may produce only k * R distinct values.
Run this code
#include <iostream> #include <random> int main() { std::random_device rd; std::mt19937 gen(rd()); for (int n = 0; n < 10; ++n) std::cout << std::generate_canonical<double, 10>(gen) << ' '; std::cout << '\n'; }
Possible output:
0.208143 0.824147 0.0278604 0.343183 0.0173263 0.864057 0.647037 0.539467 0.0583497 0.609219