hn.today

Everything should be a random number generator

en.cppreference.com3 points0 comments
Screenshot of Everything should be a random number generator

C++ random-number generation is organized around a distinction between engines and distributions. An engine maintains a state, advances it through a transition algorithm, and turns that state into pseudo-random values; its seed or seed sequence determines its initial state. The standard library offers engines with different trade-offs: linear congruential generators are compact and moderately fast, Mersenne Twisters provide long periods and strong statistical characteristics at greater cost, and subtract-with-carry engines favor speed. C++26 adds Philox, a counter-based option designed for parallel and vectorized simulation. Adaptors can reshape an engine’s output, while named presets such as mt19937 and ranlux provide ready-made configurations. None of these engines is cryptographically secure.

Distributions transform engine output to match a desired statistical pattern, separating the source of random bits from the values an application needs. Available choices include uniform integers and reals, Bernoulli and Poisson families, Gaussian and other continuous distributions, and weighted or piecewise sampling. The page also covers random_device, which may draw on hardware entropy but is permitted to fall back to a pseudo-random engine when nondeterministic sources are unavailable. Utilities include seed_seq and canonical real-number generation; C++26 adds an algorithm for filling ranges with random values. A worked example combines random_device, an engine, and distributions to select a mean and generate a normal-distribution sample. The older C rand/srand facilities remain available but are not recommended; secure applications should instead use a cryptographic library.

Read on en.cppreference.com0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.