What is a good random number generator to use for a game in C++?
My considerations are:
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.
Apparently (I forget where I read it, just like I forget where I read that curry is good to prevent altzheimas), taking the absolute value of the checksum of a newly generated GUID is nicely random. It's a large number, and you can use a modulo of it to shrink it down.
So in SQL (my area), this is ABS(CHECKSUM(NEWID())) % 1000
Rob
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 :)
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?
rand()
implementationsAn 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.
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.