Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random.seed(): What does it do?

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.

like image 762
Ahaan S. Rungta Avatar asked Mar 25 '14 15:03

Ahaan S. Rungta


People also ask

What does random seed () do?

Python Random seed() Method The seed() method is used to initialize the random number generator. The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time.

Why do we need random seed in Python?

random. seed(a, version) in python is used to initialize the pseudo-random number generator (PRNG). PRNG is algorithm that generates sequence of numbers approximating the properties of random numbers. These random numbers can be reproduced using the seed value.

What is seed in random split?

seed: A random number generator seed. The default value is 1 .

Why do we seed a random number generator?

TL;DR; A seed usually enables you to reproduce the sequence of random numbers. In that sense they are not true random numbers but "pseudo random numbers", hence a PNR Generator (PNRG). These are a real help in real life!


2 Answers

All the other answers don't seem to explain the use of random.seed(). Here is a simple example (source):

import random random.seed( 3 ) print "Random number with seed 3 : ", random.random() #will generate a random number  #if you want to use the same random number once again in your program random.seed( 3 ) random.random()   # same random number as before 
like image 34
Ritesh Karwa Avatar answered Sep 28 '22 04:09

Ritesh Karwa


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.

like image 55
Eric Finn Avatar answered Sep 28 '22 05:09

Eric Finn