Common functions/methods of random modules in Python (1)-random.seed()

To learn the random module in Python, the first function you need to understand is the method random.seed() to set the random number seed .

(1) Understanding of random.seed() function

The random module uses the Mersenne Twister algorithm to calculate and generate random numbers. This is an indeterminate algorithm, but the initialization seed can be modified through the random.seed() function.
The number in seed parentheses is the basis for the computer to create random numbers. After the number is determined (such as seed(1)), all subsequent random operations are deterministic .

The popular understanding is: if the same seed() value is used, the random number generated each time will be the same.

(2) When to use random.seed() function

The seed() method changes the seed of the random number generator. You can call this function before calling other random module functions to make the random numbers consistent.

(3) Grammar

import random
random.seed( [x] )

The parameter x is to change the seed of the random number generator. If this value is not set, the system chooses this value by itself according to the time. At this time, the random number generated each time is different due to the time difference.

(4) Examples

import random

# 不设置参数值时,产生的随机数是不一样的
random.seed()
print('不设置参数值1:',random.random())
random.seed()
print('不设置参数值2:',random.random())

# 设置参数值为1,产生的随机数一样
random.seed(1)
print('设置参数值1:',random.random())
random.seed(1)
print('设置参数值2:',random.random())
random.seed(1)
print('设置参数值3:',random.random())

# 改变参数值为2,产生的随机数也会发生变化
random.seed(2)
print('改变参数值1:',random.random())
random.seed(2)
print('改变参数值2:',random.random())

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45154565/article/details/114915430