Search code examples
c++performancerandom

What is a good random number generator for a game?


What is a good random number generator to use for a game in C++?

My considerations are:

  1. Lots of random numbers are needed, so speed is good.
  2. Players will always complain about random numbers, but I'd like to be able to point them to a reference that explains that I really did my job.
  3. Since this is a commercial project which I don't have much time for, it would be nice if the algorithm either a) was relatively easy to implement or b) had a good non-GPL implementation available.
  4. I'm already using rand() in quite a lot of places, so any other generator had better be good to justify all the changes it would require.

I don't know much about this subject, so the only alternative I could come up with is the Mersenne Twister; does it satisfy all these requirements? Is there anything else that's better?


Mersenne Twister seems to be the consensus choice. But what about point #4? Is it really that much better than rand()?

Let me be a little clearer on point 2: There is no way for players to cheat by knowing the random numbers. Period. I want it random enough that people (at least those who understand randomness) can't complain about it, but I'm not worried about predictions.

That's why I put speed as the top consideration.


Solution

  • George Marsaglia has developed some of the best and fastest RNGs currently available Multiply-with-carry being a notable one for a uniform distribution.

    === Update 2018-09-12 ===

    For my own work I'm now using Xoshiro256**, which is a sort of evolution/update on Marsaglia's XorShift.

    === Update 2021-02-23 ===

    In .NET 6 (currently in preview) the implementation of System.Random has been changed to use xoshiro256**, but only for the parameterless constructor. The constructor that takes a seed uses the old PRNG in order to maintain backwards compatibility. For more info see Improve Random (performance, APIs, ...)