Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cheap and cheerful rand() replacement

Tags:

c

random

After profiling a large game playing program, I have found that the library function rand() is consuming a considerable fraction of the total processing time. My requirements for the random number generator are not very onerous - its not important that it pass a great battery of statistical tests of pure randomness. I just want something cheap and cheerful that is very fast. Any suggestions?

like image 619
Mick Avatar asked Jun 16 '10 10:06

Mick


People also ask

How do I generate random numbers without rand () function?

For "not too random" integers, you could start with the current UNIX time, then use the recursive formula r = ((r * 7621) + 1) % 32768; . The nth random integer between 0 (inclusive) and M (exclusive) would be r % M after the nth iteration. This is called a linear congruential generator.

Is rand () truly random?

However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed.

Why does rand () return the same number?

The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.

What is the range of rand () in C?

The rand function returns a pseudorandom integer in the range 0 to RAND_MAX (32767).


1 Answers

There are few algorithms in common use that are faster than an LCG (which is very, very likely what rand() is using). You may want to try Marsaglia's Xorshift generator which is pretty fast (depending on the hardware). The WELL512a generator is also quite fast (more so than MT19937 or MT19937-64).

like image 70
Joey Avatar answered Oct 24 '22 02:10

Joey