# C++ Fast random number generation

## Recommended Posts

Posted (edited)

Hi,

i am playing with a ray tracer tutorial. Random number between [0.0..1.0) are used (high)frequently but they use c-style routines.

So, my question is, is the C++ pseudo generator like mersenne-twister less performant then c-style rand() ?

Or is one of the many other C++ generators better suited for the job ?

Edited by Green_Baron

##### Share on other sites

The Mersenne-twister is quite expensive, it is however really random.

rand() is known to not be a good random generator, over many many samples patterns emerge. It is however decently fast. Fast 'random' is usually a Linear Congruential Generator (https://en.wikipedia.org/wiki/Linear_congruential_generator)

However if you are using it for a ray tracer, you actually don't want pure random samples as pure random is usually not very uniform. You want something a little better. Hammersley is a good start, but depending on your exact case not great (http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html

If you want to get higher quality you need to look at something like: http://s2017.siggraph.org/technical-papers/sessions/random-sampling.html

But keep in mind, different use cases, different generators. Different people, different opinions.

Never the less, I hope this gets you in the right direction.

##### Share on other sites

Phew ...

... and in C++ one can choose a generator and set the distribution.

Simple solutions to complex problems are an illusion.🤔

##### Share on other sites

C++ offers three basic pseudorandom number generators (PRNG)  in its <random> standard library:  a linear congruential (C-style) one, which is moderately fast and has state of one word of memory but has affinity for certain patterns on its spectral distribution, a lagged Fibonacci one, which is very fast but has larger state but can have clustering, and the Mersenne twister, which is very slow and has a large state but provides a very long sequent with broad spectral characteristics.

For what you're doing, the basic linear congruential engine (std::minstd_rand) is likely good enough.  It's just like the one in C, except it uses local state instead of global state so it's still better than C.

disclaimer: I implemented the tr1 <random> for GCC.

##### Share on other sites

Cool, thanks !

First hand info 🙂

## Create an account

Register a new account

• 9
• 24
• 9
• 13