##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::generate_canonical

From cppreference.com
< cpp‎ | numeric‎ | random

template< class RealType, size_t bits, class Generator > RealType generate_canonical( Generator& g ); |  | (since C++11)

Generates a random floating point number in range [0; 1).

g() is called as many times as needed to generate enough entropy, i.e. at least max(1, ⌈ min(b
1, b
2) / log
2 R ⌉) times, where

- b1 = std::numeric_limits<RealType>::digits
- b2 = std::numeric_limits<RealType>::bits
- 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] Example

produce random numbers with 10 bits of randomness: this may produce only 1024 distinct values

Run this code

    #include <random>
    #include <iostream>

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

Output:

    0.208143 0.824147 0.0278604 0.343183 0.0173263 0.864057 0.647037 0.539467 0.0583497 0.609219

### [edit] See also

uniform_real_distribution (C++11) | produces real values evenly distributed across a range (class template) [edit]

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/numeric/random/generate_canonical&oldid=63380"