Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast Random Generator

Tags:

c#

random

How can I make a fast RNG (Random Number Generator) in C# that support filling an array of bytes with a maxValue (and/or a minValue)? I have found this http://www.codeproject.com/KB/cs/fastrandom.aspx but doesn't have these feature.

like image 605
tazzo Avatar asked Nov 24 '09 15:11

tazzo


People also ask

How fast is a random number generator?

Laser generates quantum randomness at a rate of 250 trillion bits per second, and could lead to devices small enough to fit on a single chip. Researchers have built the fastest random-number generator ever made, using a simple laser.

Which package provides fast random number generators RNG?

The dqrng package provides fast random number generators (RNG) with good statistical properties for usage with R. It combines these RNGs with fast distribution functions to sample from uniform, normal or exponential distributions.

How many types of RNG are there?

There are generally two kinds of random number generators: non-deterministic random number generators, sometimes called "true random number generators" (TRNG), and deterministic random number generators, also called pseudorandom number generators (PRNG).


1 Answers

The fact that you're filling bytes with integers is different enough from the typical usage case for System.Random that you can probably beat it badly if you really need to.

System.Random is made for general use. (In fact, I usually find system random routines uninspiring when I do speed and distribution tests on them.) There are cases where you'd want something else. But you have to be very explicit about your needs. How fast? What are you willing to give up?

If you really need "fast," Marsaglia has produced a number of very fast random number generators that could be adapted to your needs. Here are a few links about one of them, Xorshift:

  • Xorshift (Wikipedia)
  • Fastest implementation of Xorshift in C#, and measurements comparing it to System.Random
  • The Diehard tests are interesting.
  • Agner has C++ code for many fast randoms.
  • Here's a fast twister that uses SIMD instructions.

The last one addresses the fact that you are targeting bytes.

I've only needed super fast randoms a few times. In console games with slow processors where random could make the difference between hitting the frame rate target and not hitting it. What is your use case? By all means, use System.Random if you can.

Or, adapt the routine you link to in your question (which the author claims is 8x the speed of System.Random.)

like image 95
Nosredna Avatar answered Oct 19 '22 19:10

Nosredna