The science behind the Random Numbers.

The science behind the Random Numbers.

How a computer generates a Random Number?

Photo by Drew Beamer on Unsplash

To understand how a computer generates a Random Number, we must understand how a computer works.

A computer works in a simple way, you give a set of instructions and it will process those instructions by following certain steps. We all know the fact that Computers are great at following instructions and doing computations.

but when you tell the computer to “give me a random number”, The computer is confused, “what is Random?”, “How will you define Random?”, “I don’t understand Random…”.

source: https://dilbert.com/strip/2001-10-25

Hence, the Random number generated by a computer is not a Random number per se, in algorithmic terminology, we call it a “Pseudo-Random Number”.

A Pseudo-Random Number generation algorithm (also known as a Pseudo-Random Number Generator (P.R.N.G.)) starts with a Number known as a “seed” and then follows some instructions to generate the next Pseudo-Random Number and so on and when it reaches its limitation whether it’s calculation limit or any other defined limit, it again starts from the seed due to which it’s bound to repeat its sequence. The duration after which a pseudo-random number generator repeats its sequence is called “period”.

The period of a PRNG defines its efficiency, the higher the period the better the algorithm.

Let me explain with some examples [No worries, instead of Code, I will write simple instructions]

Simplest Random Number generator

I know the instructions in the above code look stupid but it’s an algorithm with Seed 13 and Period 0 (since it will always return the same number).

Another simple Random Number generator

As you can see in the instructions above, we are starting with Seed as 13 and the next Pseudo-Random Number is generated by multiplying the number by 2 and so on till it reaches 100 after 100, we are again starting with seed so the sequence will be repeated.

The resultant sequence will be: 13, 26, 52, 13, 26, 52, 13…

So the period of this algorithm will be 3 since the sequence is repeated after 3 pseudo-random numbers.

Conclusion

  • Though we call it a Random Number, it’s not actually random, a PRNG follows a set of instructions to calculate the Random Number.
  • The random number generators start with a seed and follow some instructions to generate the next pseudo-random number and so on.
  • The period of a PRNG is the number after which it repeats its sequence and is used to measure the efficiency of the algorithm.