I am a bit confused on what random.seed()
does in Python. For example, why does the below trials do what they do (consistently)?
>>> import random
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.randint(1, 10)
3
>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
7
I couldn't find good documentation on this.
Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.
Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.
Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.
May be it is worth mentioning that sometimes we want to give seed so that same random sequence is generated on every run of the program. Sometimes, randomness in software program(s) is avoided to keep program behavior deterministic and possibility of reproducing the issues / bugs.
Following what @ViFI said, keeping program behavior deterministic (with a fixed seed, or fixed sequence of seeds) can also allow you to better assess whether some change to your program is beneficial or not.
would you mind explaining with some real life scenario. I cant understand a use case for the same. Do we have something similar to this in other programming language as well ?
Here's a real life scenario: stackoverflow.com/questions/5836335/…. Random seeds are also common to create reproducible results for research. For example, if you're a data scientist and you want to publish your results with some kind of model that uses randomness (e.g. a random forest), you'll want to include a seed in your published code so people can make sure your calculations are reproducible.
so seed literally works to de-randomize the random function in a way we want ... ?