Random Number

How we do generate a random number?

In real life, a true random number generator simply doesn’t work, because we will always find an underlying pattern/sequence in the long run. That’s why we say pseudorandom, i.e. it is approximately random. https://en.wikipedia.org/wiki/Pseudorandom_number_generator

Uniform Random Number

There are several ways to generate a uniform random number, such as using:

  • Linear Congruential Generator (LCG)
  • Xorshift
  • Marsaglia Multiply with Carry (MWC) apparently one of the fastest? (used in the Ziggurat Algorithm)

Python’s random() uses the Mersenne Twister as the core generator, produces 53-bit precision floats and has a period of .

Personal Experience: I was implementing the Xorshift algorithms, however I noticed that they performed worse than the default np.random.rand() even though they were faster, and it is because the period is much smaller.

Even with the biggest xorshift: xoshiro1024, it only has a period of , which is not enough.

In C++

I was curious about what srand(time(NULL)) actually does.

When you do rand() you get the current number on the current book and advance to the next.

When you do srand(<number>) you select the book rand() will use from that point forward.

time(NULL) return the number (after conversion) of seconds since about midnight 1970-01-01. That number changes every second, so using that number to “select a book” pretty much guarantees a new sequence of “random” numbers every time your program runs.

Linear Congruential Generator (LCG)

In C (gcc), it seems that they use a Linear Congruential Generator (which uses modular arithmetic), The generator is defined by the recurrence relation:

Normal Random

See Normal Distribution to generate random normal numbers.