std::generate_canonical(3)
π 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 you1.0when 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_distributionproduces 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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms