I had a requirement to have random numbers generated in a C application.
1 2 3 4 5 6 7 8 9 10
I ran the code once and saw that random numbers were getting generated.
But to my surprise when I ran the code second time, I saw the same numbers getting printed.
What??? Does it mean random numbers are predictable? If so, why is it called random?
Predictablewords literally contradicting each other.
But I remember using random.random() in Python which each time gave different output.
1 2 3
Each time I executed this code I got different set of output.
Is the random function implementation in libc is so buggy? Of course, cannot be!!!
Oh wait. Are we missing something here.
If there is going to some algorithm for generating random numbers it means that we telling the computer to perform a series of steps and give us a result. If the series of steps is defined it implies that the result is predictable.
But people coming up with such algorithms would have definitely thought about this.
They would have added some variable parameter into the equation making it unpredictable. That variable parameter can be anything like – derived from current timestamp or current data in the network device.
If so, does it mean Python implementors thought of this and libc implementors missed it?
When I checked the man page of random() function in my Linux machine. It said,
The random() function uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately
16 * ((2^31) - 1).
So, this is it. It is not random it is actually pseudo-random.
Meaning of pseudorandom from dictionary,
pseudorandom |ˌsjuːdəʊˈrandəm| adjective
(of a number, a sequence of numbers, or any digital data) satisfying one or more statistical tests for
randomness but produced by a definite mathematical procedure.most computers have built-in functions which will generate sequences of pseudorandom numbers.`
Aha. We are there. Whatever we discussed so far is making sense.
Also, there can be a requirement, where, for some experiment which uses random numbers has to be reproducible.
So thats the reason. Why random() function in libc is returning same sequence. The same can be achieved even in Python using seed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
The output of the above code twice,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
The same seed returns the same sequence.
So thats the feature of libc, which allows the caller to set
different seed each time based on the requirement.
Moral of the story is,
- random numbers generated by computer are only pseudo random numbers.
Seeds used in random numbers are meant for two reasons,
to increase the degree of randomness
to make experiment that uses random numbers reproducible