std::generate_canonical

From cppreference.com
< cpp‎ | numeric‎ | random
 
 
 
Pseudo-random number generation
Uniform random bit generators
Engines and engine adaptors
Non-deterministic generator
Distributions
Uniform distributions
generate_canonical
(C++11)
Bernoulli distributions
Poisson distributions
Normal distributions
Sampling distributions
Seed Sequences
(C++11)
C library
 
Defined in header <random>
template< class RealType, std::size_t Bits, class Generator >
RealType generate_canonical( Generator& g );
(since C++11)

Generates a random floating point number in range [01).

To generate enough entropy, generate_canonical() will call g() exactly k times, where k = max(1, ⌈ b / log
2
R ⌉)
and

Parameters

g - generator to use to acquire entropy

Return value

Floating point value in range [01).

Exceptions

None except from those thrown by g.

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.

Example

Produce random numbers with 10 bits of randomness: this may produce only k * R distinct values.

#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) << ' ';
}

Possible output:

0.208143 0.824147 0.0278604 0.343183 0.0173263 0.864057 0.647037 0.539467 0.0583497 0.609219

See also

produces real values evenly distributed across a range
(class template)