Table of contents
Basic random number function():
Extended random number function():
The random library contains two types of functions: basic random number functions and extended random number functions.
Basic random number functions: seed(), random()
Extended random number functions: randint, getrandbits(), uniform(), randrange(), choice(), shuffle()
Basic random number function():
rand.seed()
When random.seed() is called, it takes the incoming seed as a parameter and converts it into an integer value. This integer value is used to set the starting state of the random number generator. The random number generator generates a sequence of random numbers based on the starting state. These random numbers can be obtained through functions such as random.random().
Note: A seed is a starting value that is used as a starting point for generating a sequence of random numbers. The random number generator calculates the next random number based on the seed and passes that number as the seed to the next calculation.
random.seed(10)#Generate the sequence corresponding to seed 10
#By default, the system time will be used to initialize the seed of the random number generator.
import numpy as np
num = 0
np.random.seed(0)
while (num < 5):
print(np.random.rand(1,5))
num += 1
print('-------------------------')
It can be found that after setting the random seed, the random number will be the same every time it is run.
If you annotate the random seed of your program:
import numpy as np
num = 0
#np.random.seed(0)
while (num < 5):
print(np.random.rand(1,5))
num += 1
print('-------------------------')
Then you can find that the random number of each execution result is different:
random()
Generate a random decimal between [0.0,1.0)
>>>random.random()
0.5714025946899135
Extended random number function():
function | describe |
return(a, b) | Generate an integer between [a, b] |
>>>random.randint(10, 100) | |
64 | |
randrange(m, n[, k]) | Generate a random integer between [m, n) with k as the step size |
>>>random.randrange(10, 100, 10) | |
80 | |
getrandbits(k) | Generate a k-bit long random integer |
>>>random.getrandbits(16) | |
37885 | |
uniform(a, b) | Generate a random decimal between [a, b] |
>>>random.uniform(10, 100) | |
13.09632165 | |
choice(seq) | Randomly select an element from the sequence seq |
>>>random.choice([1,2,3,4,5,6,7,8,9]) | |
8 | |
shuffle(seq) | Randomly arrange the elements in the sequence seq and return the scrambled sequence |
>>>s=[1,2,3,4,5,6,7,8,9];random.shuffle(s);print(s) | |
[3, 5, 8, 9, 6, 1, 2, 7, 4] |