std::generate_canonical(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::generate_canonical πŸ’–

From the C++ Standard Libary manual, bestie β€” yes, that’s the exact spelling on the page, don’t come for me πŸ’…. This is the C++ random-number glow-up moment.


✨ NAME ✨

std::generate_canonical β€” std::generate_canonical. That’s the name, that’s the function, that’s the whole vibe. πŸ‘‘


πŸŒ€ Synopsis πŸŒ€

Defined in header <random>:

template< class RealType, std::size_t Bits, class Generator >  (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 k times, where k = max(1, ⌈ b / log_2 R βŒ‰) β€” the page also writes it as k = \max(1, \lceil \frac{b}{\log_2 R} \rceil) β€” 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.

fr fr, the only drama comes from g. No extra surprises from this function itself. 🫢

πŸ’… 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.

Not me warning you about a bug that can hand you 1.0 when the range says [0, 1) 😭 β€” that’s the whole point of the note. Keep it in mind.

πŸ“ 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

🌈 See also 🌈

  • uniform_real_distribution produces real values evenly distributed across a range (C++11) (class template).

okay bestie that’s the whole page πŸ’œ β€” source: http://cppreference.com, version/date: 2024.06.10. Go generate something canonical, ily! πŸŒŸπŸŽ€

πŸ“¦ where this page comes from