What is a good random number generator for a game?

C++PerformanceRandom

C++ Problem Overview


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?

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

Edit 2: 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.

Edit 3: I'm leaning toward the Marsaglia RNGs now, but I'd still like more input. Therefore, I'm setting up a bounty.

Edit 4: Just a note: I intend to accept an answer just before midnight UTC today (to avoid messing with someone's rep cap). So if you're thinking of answering, don't wait until the last minute!
Also, I like the looks of Marsaglia's XORshift generators. Does anyone have any input about them?

C++ Solutions


Solution 1 - C++

Sometimes game developers don't want true randomness and a shuffle bag is more appropriate.

If you do want randomness, the Mersenne twister satisfies your requirements. It is fast, statistically random, has a long period and there are plenty of implementations out there.

Edit: rand() is typically implemented as a linear congruential generator. It's probably best if you make an informed choice of whether or not it's good enough for your purposes.

Solution 2 - C++

There are much better choices than Mersenne Twister nowadays. Here is a RNG called WELL512, designed by the designers of Mersenne, developed 10 years later, and an all around better choice for games. The code is put in the public domain by Dr. Chris Lomont. He claims this implementation is 40% faster than Mersenne, does not suffer from poor diffusion and trapping when the state contains many 0 bits, and is clearly a lot simpler code. It has a period of 2^512; a PC takes over 10^100 years to cycle through the states, so it is large enough.

Here is a paper overviewing PRNGs where I found the WELL512 implementation. http://www.lomont.org/Math/Papers/2008/Lomont_PRNG_2008.pdf

So - faster, simpler, created by the same designers 10 years later, and produces better numbers than Mersenne. How can you go wrong? :)

UPDATE (11-18-14): Fixed error (changed 0xDA442D20UL to 0xDA442D24UL, as described in the paper linked above).

/* initialize state to random bits */
static unsigned long state[16];
/* init should also reset this to 0 */
static unsigned int index = 0;
/* return 32 bit random number */
unsigned long WELLRNG512(void)
   {
   unsigned long a, b, c, d;
   a = state[index];
   c = state[(index+13)&15];
   b = a^c^(a<<16)^(c<<15);
   c = state[(index+9)&15];
   c ^= (c>>11);
   a = state[index] = b^c;
   d = a^((a<<5)&0xDA442D24UL);
   index = (index + 15)&15;
   a = state[index];
   state[index] = a^b^d^(a<<2)^(b<<18)^(c<<28);
   return state[index];
   }

Solution 3 - C++

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, ...)

Solution 4 - C++

Mersenne Twister is typical in the industry, especially since it lends itself well to SIMD and can be made super fast. Knuth is popular too (thanks, David).

In most game applications speed is really the critical factor, since players are going to complain about low framerate a lot more than they will complain about the fact that there is a slight bias towards generating a 3 whenever it is preceded by a 7, 2, and 9 in that order.

The exception of course is gambling for money, but there your relevant licensing authority will specifically lay out the algorithms that you can use.

Solution 5 - C++

Buy a cheap webcamera, a ionizing smoke detector. Disassemble both of them, smoke detector contain little radioactive material - a source of gamma waves - which will result in firing photons at your webcamera. That's your source of true randomness :)

Solution 6 - C++

Mersenne Twister is very good, and it's fast as well. I used it in a game and it's not hard at all to implement or use.

The WELL random algorithm was designed as an improvement over the Mersenne Twister. Game Gems 7 has more info. on it, if you can borrow that or have it.

On that WELL page I linked you to, the number is the period of the algorithm. That is, you can get 2^N - 1 numbers before it needs reseeding, where N is: 512, 1024, 19937, or 44497. Mersenne Twister has a period of N = 19937, or 2^19937 - 1. You'll see this is a very large number :)

The only other thing I can point out is that boost has a random library, which you should find useful.

In response to your edit, yes the Twister or WELL is that much better than rand(). Also, the old modulus trick harms the distribution of the numbers. Even more reason to use boost :)

Solution 7 - C++

In a real-time game, there's no way for a player to determine the difference between a "good" generator and a "bad" one. In a turn-based game, you're right--some minority of zealots will complain. They'll even tell you stories, in excruciating detail, of how you ruined their lives with a bad random number generator.

If you need a bunch of genuine random numbers (and you're an online game), you can get some at Random.org. Use them for turn-based games, or as seeds for real-time games.

Solution 8 - C++

I'm a fan of Isaac, unlike mersense twister, it's crypographically secure (you *can't crack the period by observing the rolls)

IBAA (rc4?) is also one that is used by blizzard to prevent people from predicting the random number used for loot rolls.. I imagine something similar is done w/ diablo II when you are playing off of a battle.net server.

*can't within any reasonable timeframe (centuries?)

Solution 9 - C++

Based on the random number generator by Ian C. Bullard:

// utils.hpp
namespace utils {
    void srand(unsigned int seed);
    void srand();
    unsigned int rand();
}

// utils.cpp
#include "utils.hpp"
#include <time.h>

namespace {
	static unsigned int s_rand_high = 1;
	static unsigned int s_rand_low = 1 ^ 0x49616E42;
}

void utils::srand(unsigned int seed)
{
	s_rand_high = seed;
	s_rand_low = seed ^ 0x49616E42;
}

void utils::srand()
{
	utils::srand(static_cast<unsigned int>(time(0)));
}

unsigned int utils::rand()
{
	static const int shift = sizeof(int) / 2;
	s_rand_high = (s_rand_high >> shift) + (s_rand_high << shift);
	s_rand_high += s_rand_low;
	s_rand_low += s_rand_high;
	return s_rand_high;
}

Why?

  • very, very fast
  • higher entropy than most standard rand() implementations
  • easy to understand

Solution 10 - C++

An additional criteria you should consider is thread safety. (And you should be using threads in todays multi-core environments.) Just calling rand from more than one thread can mess with it's deterministic behavior (if your game depends on that). At the very least I'd recommend you switch to rand_r.

Solution 11 - C++

I'd vote for the Mersenne Twister as well. Implementations are widely available, it has a very large period of 2^19937 -1, is reasonably fast and passes most randomness tests including the Diehard tests developed by Marsaglia. rand() and Co., being LCGs, produce lower quality deviates and their successive values can be easily inferred.

One point of note, however, is to properly seed MT into a state that passes randomness tests. Usually a LCG like drand48() is used for that purpose.

I'd say the MT satisfies all the requirements you've set (provably), and it'd be an overkill to go for something like MWCG imo.

Solution 12 - C++

GameRand implement the algorithm posted here http://www.flipcode.com/archives/07-15-2002.shtml

This is something I originally developed in the late 80s. It easily beat rand() in term of numerical quality, and as the side benefit to be the fastest random algorithm possible.

Solution 13 - C++

> 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.

A-ha!

There's your real requirement!

No one could fault you for using Mersenne Twister in this application.

Solution 14 - C++

Depending on the target OS, you might be able to use /dev/random. It doesn't really require any implementation, and on Linux (and maybe some other operating systems) it's truly random. The read blocks until sufficient entropy is available, so you might want to read the file and store it in a buffer or something using another thread. If you can't use a blocking read call, you can use /dev/urandom. It generates random data almost as well as /dev/random, but it reuses some random data to give output instantly. It's not as secure, but it could work fine depending on what you plan to do with it.

Solution 15 - C++

You know what? Forgive me if you think this answer completely sucks... But I've been (for god only knows what reason...) using DateTime.Now.Milliseconds as a way to get a random number. I know it's not completely random, but it appears to be...

I just couldn't be bothered typing so much JUST to get a random number! :P

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael MyersView Question on Stackoverflow
Solution 1 - C++David JohnstoneView Answer on Stackoverflow
Solution 2 - C++Chris LomontView Answer on Stackoverflow
Solution 3 - C++redcalxView Answer on Stackoverflow
Solution 4 - C++CrashworksView Answer on Stackoverflow
Solution 5 - C++VexatusView Answer on Stackoverflow
Solution 6 - C++GManNickGView Answer on Stackoverflow
Solution 7 - C++NosrednaView Answer on Stackoverflow
Solution 8 - C++Ape-inagoView Answer on Stackoverflow
Solution 9 - C++Armin RonacherView Answer on Stackoverflow
Solution 10 - C++geowarView Answer on Stackoverflow
Solution 11 - C++Michael FoukarakisView Answer on Stackoverflow
Solution 12 - C++sschaemView Answer on Stackoverflow
Solution 13 - C++Marsh RayView Answer on Stackoverflow
Solution 14 - C++nonpolynomial237View Answer on Stackoverflow
Solution 15 - C++jay_t55View Answer on Stackoverflow