# A good random number generator for C

10,228

## Solution 1

This seems like a good use-case for the Mersenne Twister

• It's faster than most standard implementations of rand()
• It has a very long (2^19937 − 1) period
• It has a pretty high quality - it passes most standardized randomness tests
• It's public domain

## Solution 2

If you are looking for a very fast, decent quality algorithm, you should think about `xorshift128+` or `xorshift1024*`. They are almost as fast as LCGs (according to my comparison they are only 30% slower than simply inline LCG), having much better quality than LCG the same time.

You can find their code and comparison here: http://xorshift.di.unimi.it/

Share:
10,228
Author by

### Void Star

Hi, my name is Kyle. I have been interested in science, math, and engineering for (quite literally) as long as I can remember. I am an avid programmer and electronics hobbyist. I attended the University of Washington as an undergraduate in the Electrical Engineering department and now work for Keysight Technologies as a research and development software engineer.

Updated on June 16, 2022

• Void Star 8 months

I need a good random number generator for a program I'm writing in C. It's a fractal flame generator, if you're interested. My images were coming out very grainy, even though I had success with the same algorithm in the past. The difference, I finally realized, was the random number generator I was using. Incredibly, it makes an ENORMOUS difference. I'm hoping that an even better random number generator might yield better results. The answer could come in the form of a code sample or a link to a pre-existing random number library. The most important requirements:

• it should produce relatively high quality streams of random numbers
• its period must be over ten billion
• it should be fast enough and offer a good performance trade-off.
• UmNyobe almost 10 years
no, he is giving a candidate. +1 btw, never heard of Mersenne before
• Void Star almost 10 years
Wow, this looks like a REALLY good random number generator. Thanks so much Philipp, I would never have found this on my own.
• Steve Jessop almost 10 years
I'm surprised that MT is faster than most implementations of `rand()`. Isn't `rand()` commonly an LCG, hence very fast but poor quality?
• zeboidlund over 9 years
Considering the fact that this actually turned my non-working `rand()`-based algorithm into something I could actually work with, +1!
• Void Star about 6 years
underappreciated answer here - I've used these in a couple projects so far and they work great, with such a simple implementation!