AppDividend
Latest Code Tutorials

Python random seed: How to Use random.seed() Method

0

The random() function in Python is used to generate the pseudo-random numbers. It generates numbers for some values called seed value.

How does seed function work?

The seed function is used to store a random method to generate the same random numbers on multiple executions of the code on the same machine or different machines.

The seed value is precious in computer security to pseudo-randomly produce a secure secret encryption key. So using the custom seed value, you can initialize the secure pseudo-random number generator the extent you need.

Python random seed

The random.seed() function in Python is used to initialize the random numbers. By default, the random number generator uses the current system time. If you use the same seed value twice, you get the same output means random number twice.

Syntax

random.seed(svalue, version)

Parameters

The svalue parameter is optional, and it is the seed value needed to generate a random number. The default value is None, and if None, the generator uses the current system time.

It is an integer specifying how to convert the svalue parameter into an integer. The default value is 2.

Example

# app.py

import random

random.seed(10)
print(random.random())

random.seed(10)
print(random.random())

Output

0.5714025946899135
0.5714025946899135

This example demonstrates that if you use the same seed value twice, you will get the same random number twice.

Let’s see another example in which we generate the same random number many times.

# app.py

import random

for i in range(5):

    # Any number can be used in place of '11'.
    random.seed(11)

    # Generated random number will be between 1 to 1000.
    print(random.randint(1, 1000))

Output

464
464
464
464
464

When we supply a specific seed to the random generator, every time you execute a program, you will get the same numbers. That is useful when you need a predictable source of random numbers.

It makes optimization of codes easy where random numbers are used for testing. The output of the code sometime depends on the input. So the use of random numbers for testing algorithms can be problematic.

Also, the seed function is used to generate the same random numbers again and again and simplifies the algorithm testing process.

That is it for Python random seed() function.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.