Python seed() Function
Description
seed()This method changes the seed of the random number generator and can be called before calling other random module functions.
Syntax
Following is the syntax for the seed() method:
import random random.seed ( [x] )
When we call random.random() to generate random numbers, every generated number is random. However, when we pre-set the seed using random.seed(x), where x can be any number, such as 10, then after calling it first, the random numbers generated using random() will be the same.
Note:seed() cannot be accessed directly. You need to import the random module, and then call this method through the random static object.
Parameters
- x -- Changes the seed of the random number generator. If you don't understand the underlying principle, you don't need to set the seed manually; Python will choose the seed for you.
Return Value
This function has no return value.
Example
The following example shows the usage of the seed() method:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import random
print random.random()
print random.random()
print "------- Set seed -------"
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
# Generate the same random number
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
# Generate the same random number
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
# -*- coding: UTF-8 -*-
import random
print random.random()
print random.random()
print "------- Set seed -------"
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
# Generate the same random number
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
# Generate the same random number
random.seed( 10 )
print "Random number with seed 10 : ", random.random()
After running the above example, the output result is:
0.739880443211 0.78969784712 ------- 设置种子 seed ------- Random number with seed 10 : 0.57140259469 Random number with seed 10 : 0.57140259469 Random number with seed 10 : 0.57140259469Other Extensions
Python Numbers