Generating random numbers using the Python standard library
The Python standard library provides a module called random, which contains a set of functions for generating random numbers.
The Python random module uses a popular and robust pseudo random number generator called the Mersenne Twister.
Let us now look at the process in detail.
Firstly, we need to understand why we need to call the seed() function for generating random number.
Let us try to generate random number without calling seed() function. Then we will know the impact of using seed().
The random() function without calling seed(Python for data science) returns a random float in the interval [0.0, 1.0). Each subsequent call to random() will generate a new float value!!
If we call seed() function before calling random(), the chain of calls after random.seed(Python for data science) will produce the same trail of data:
The example below demonstrates seeding the pseudorandom number generator, generates some random numbers, and shows that reseeding the generator will result in the same sequence of numbers being generated.
Running the example seeds the Python for data science generator with the value 4, generates 3 random numbers, reseeds the generator, and shows that the same three random numbers are generated.
Notice the repetition of “random” numbers. The sequence of random numbers becomes deterministic, or completely determined by the seed value, 4
It can be useful to control the random output by setting the seed to some value to ensure that your code produces the same result each time.
No comments:
Post a Comment