224

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.

YetAnotherBot
  • 1,937
  • 2
  • 25
  • 32
Ahaan S. Rungta
  • 2,323
  • 2
  • 12
  • 15
  • 48
    Random number generation isn't truly "random". It is deterministic, and the sequence it generates is dictated by the seed value you pass into `random.seed`. Typically you just invoke `random.seed()`, and it uses the current time as the seed value, which means whenever you run the script you will get a different sequence of values. – Asad Saeeduddin Mar 25 '14 at 15:50
  • 5
    Passing the same seed to random, and then calling it will give you the same set of numbers. This is working as intended, and if you want the results to be different every time you will have to seed it with something different every time you start an app (for example output from /dev/random or time) – Tymoteusz Paul Mar 25 '14 at 15:51
  • 7
    The seed is what is fed to the RNG to generate the first random number. After that, they RNG is self-fed. You don't see the same answer consistently because of this. If you run this script again, you will get the same sequence of "random" numbers. Setting the seed is helpful if you want to reproduce results, as all the "random" numbers generated will always be the same. – Blink Mar 25 '14 at 15:52
  • Worth mentioning: the sequence shown in this post is in Python 2. Python 3 gives a different sequence. – ggorlen May 30 '19 at 21:31
  • 2
    @Blink 's use of "random number" is misleading. The RNG has an internal state that is self-fed. From this internal state, output for randint(1,10) and other calls are derived. If the RNG was feeding from the output of randint(1,10) the sequence would collapse to 1 of at most 10 sequences and the sequence would repeat after at most 10 numbers. – Joachim Wagner Sep 24 '19 at 09:00

12 Answers12

262

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.

Eric Finn
  • 8,629
  • 3
  • 33
  • 42
  • 61
    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. – ViFI Apr 25 '17 at 06:20
  • 4
    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. – shaneb Jul 27 '18 at 18:34
  • 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 ? – Shashank Vivek Nov 17 '18 at 16:11
  • 4
    Here's a real life scenario: https://stackoverflow.com/questions/5836335/consistently-create-same-random-numpy-array. 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. – Galen Long Feb 13 '19 at 07:15
  • so seed literally works to de-randomize the random function in a way we want ... ? – Jitin Sep 10 '20 at 06:06
  • 1
    @Jitin Not quite. PRNGs actually produce a (very long) repeating sequence of numbers. That is, in theory, if you kept requesting random numbers for long enough, you'd eventually start getting the same numbers, in the same order, as when you started. The seed you provide just specifies where in this sequence you're starting. – Eric Finn Sep 10 '20 at 20:43
109

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
ayhan
  • 70,170
  • 20
  • 182
  • 203
Ritesh Karwa
  • 2,196
  • 1
  • 13
  • 17
47
>>> random.seed(9001)   
>>> random.randint(1, 10)  
1     
>>> random.seed(9001)     
>>> random.randint(1, 10)    
1           
>>> random.seed(9001)          
>>> random.randint(1, 10)                 
1                  
>>> random.seed(9001)         
>>> random.randint(1, 10)          
1     
>>> random.seed(9002)                
>>> random.randint(1, 10)             
3

You try this.

Let's say 'random.seed' gives a value to random value generator ('random.randint()') which generates these values on the basis of this seed. One of the must properties of random numbers is that they should be reproducible. When you put same seed, you get the same pattern of random numbers. This way you are generating them right from the start. You give a different seed- it starts with a different initial (above 3).

Given a seed, it will generate random numbers between 1 and 10 one after another. So you assume one set of numbers for one seed value.

Yogesh
  • 1,384
  • 1
  • 12
  • 16
20

A random number is generated by some operation on previous value.

If there is no previous value then the current time is taken as previous value automatically. We can provide this previous value by own using random.seed(x) where x could be any number or string etc.

Hence random.random() is not actually perfect random number, it could be predicted via random.seed(x).

import random 
random.seed(45)            #seed=45  
random.random()            #1st rand value=0.2718754143840908
0.2718754143840908  
random.random()            #2nd rand value=0.48802820785090784
0.48802820785090784  
random.seed(45)            # again reasign seed=45  
random.random()
0.2718754143840908         #matching with 1st rand value  
random.random()
0.48802820785090784        #matching with 2nd rand value

Hence, generating a random number is not actually random, because it runs on algorithms. Algorithms always give the same output based on the same input. This means, it depends on the value of the seed. So, in order to make it more random, time is automatically assigned to seed().

Sathvik
  • 565
  • 1
  • 7
  • 17
abhay Maurya
  • 201
  • 2
  • 3
14
Seed() can be used for later use ---

Example:
>>> import numpy as np
>>> np.random.seed(12)
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
>>>
>>> np.random.seed(12) # When you use same seed as before you will get same random output as before
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
Gour Bera
  • 141
  • 1
  • 4
13
# Simple Python program to understand random.seed() importance

import random

random.seed(10)

for i in range(5):    
    print(random.randint(1, 100))

Execute the above program multiple times...

1st attempt: prints 5 random integers in the range of 1 - 100

2nd attempt: prints same 5 random numbers appeared in the above execution.

3rd attempt: same

.....So on

Explanation: Every time we are running the above program we are setting seed to 10, then random generator takes this as a reference variable. And then by doing some predefined formula, it generates a random number.

Hence setting seed to 10 in the next execution again sets reference number to 10 and again the same behavior starts...

As soon as we reset the seed value it gives the same plants.

Note: Change the seed value and run the program, you'll see a different random sequence than the previous one.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Brahma
  • 131
  • 1
  • 4
9

In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.

suavidas
  • 105
  • 3
6

Imho, it is used to generate same random course result when you use random.seed(samedigit) again.

In [47]: random.randint(7,10)

Out[47]: 9


In [48]: random.randint(7,10)

Out[48]: 9


In [49]: random.randint(7,10)

Out[49]: 7


In [50]: random.randint(7,10)

Out[50]: 10


In [51]: random.seed(5)


In [52]: random.randint(7,10)

Out[52]: 9


In [53]: random.seed(5)


In [54]: random.randint(7,10)

Out[54]: 9
Tonechas
  • 13,398
  • 16
  • 46
  • 80
sixsixsix
  • 1,768
  • 21
  • 19
5

Set the seed(x) before generating a set of random numbers and use the same seed to generate the same set of random numbers. Useful in case of reproducing the issues.

>>> from random import *
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> 
alx lark
  • 784
  • 1
  • 6
  • 21
user3221795
  • 51
  • 1
  • 1
3

Here is my understanding. Every time we set a seed value, a "label" or " reference" is generated. The next random.function call is attached to this "label", so next time you call the same seed value and random.function, it will give you the same result.

np.random.seed( 3 )
print(np.random.randn()) # output: 1.7886284734303186

np.random.seed( 3 )
print(np.random.rand()) # different function. output: 0.5507979025745755

np.random.seed( 5 )
print(np.random.rand()) # different seed value. output: 0.22199317108973948
Vicky Miao
  • 61
  • 2
2

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. So, if you provide seed value, PRNG starts from an arbitrary starting state using a seed.

Argument a is the seed value. If the a value is None, then by default, current system time is used.

and version is An integer specifying how to convert the a parameter into a integer. Default value is 2.

import random
random.seed(9001)
random.randint(1, 10) #this gives output of 1
# 1

If you want the same random number to be reproduced then provide the same seed again

random.seed(9001)
random.randint(1, 10) # this will give the same output of 1
# 1

If you don't provide the seed, then it generate different number and not 1 as before

random.randint(1, 10) # this gives 7 without providing seed
# 7

If you provide different seed than before, then it will give you a different random number

random.seed(9002)
random.randint(1, 10) # this gives you 5 not 1
# 5

So, in summary, if you want the same random number to be reproduced, provide the seed. Specifically, the same seed.

Santosh M.
  • 2,356
  • 1
  • 17
  • 29
1

Here is a small test that demonstrates that feeding the seed() method with the same argument will cause the same pseudo-random result:

# testing random.seed()

import random

def equalityCheck(l):
    state=None
    x=l[0]
    for i in l:
        if i!=x:
            state=False
            break
        else:
            state=True
    return state


l=[]

for i in range(1000):
    random.seed(10)
    l.append(random.random())

print "All elements in l are equal?",equalityCheck(l)