Namespaces
Variants

std::generate_canonical

From cppreference.com
 
 
 
 
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 [0, 1).

To generate enough entropy, generate_canonical() will call g() exactly k times, where 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.

Parameters

g - generator to use to acquire entropy

Return value

Floating point value in range [0, 1).

Exceptions

None except from those thrown by g.

Notes

libstdc++ has correct behaviour as of GCC 16

libc++ may incorrectly occasionally return 1.0 (issue)

vc++ avoids returning 1.0, but does so incorrectly by subtracting a small value instead of rerolling the generator (testcase issue).

For cases where the result is close to zero, only a fraction of the bits of entropy obtained should go into the result. The effect is that if all values generated less than, say, 0.001 are placed in a bucket, the number of different values that may appear would be many fewer than could be represented. Most implementations instead preserve as much of the obtained entropy as can be represented in the result.

Example

Produce random numbers with maximum randomness.

#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, -1u>(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

See also

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