random Libraries use random numbers Python Standard library .
From the perspective of probability theory , Random numbers are randomly generated data ( Like tossing coins ), But computers can't produce random values , A real random number is also a definite value generated under certain conditions , But we don't understand these conditions , Or it's beyond our understanding . Computers can't produce real random numbers , Then pseudo random numbers are called random numbers .
Pseudo random number : In a computer, it is generated by using the Mason rotation algorithm ( false ) Random sequence elements .
python The library for generating pseudo-random numbers in is random.
The standard library is because , Just use it :import random that will do .
random The library contains two types of functions , Commonly used 8 individual :
Python To generate random numbers in Random number seed To produce .
As long as the seeds are the same , Generated random sequence , Whether it's every number , Or is the relationship between numbers certain , So the seed of the random number determines the generation of the random sequence . Every number in a random sequence is a random number .
function | describe |
seed(a=None) | Initializes a given random number seed , The default is the current system time >>>random.seed(10) # Produce seeds 10 Corresponding sequence |
random() | Generate a [0.0,1.0) Between random decimals >>>random.random() 0.5714025946899135 |
The advantage of using random number seeds is that programs with random numbers can be reproduced .
Key points of using random number function :
-- Can use random number seeds to generate “ determine ” Pseudo random number :seed Produce seeds ,random Function produces random numbers
-- Can produce random integers
-- The ability to randomly manipulate sequence types
function | describe |
randint(a,b) | Generate a [a,b] Integer between >>>random.randint(10,1000) 49 |
randrange(m,n[,k]) | Generate a [m,n) Between k Is a random integer of step size >>>random.randrange(10,1000,10) 620 |
getrandbits(k) | Generate a k Random integers that are longer than special >>>random.getrandbits(16) 16383 |
uniform(a,b) | Generate a [a,b] Between random decimals >>>random.uniform(10,100) 24.684121564308157 |
choice(seq) Sequence related |
Randomly select an element from a sequence >>>random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9]) 5 |
shuffle(seq) Sequence related |
The sequence of seq The elements are arranged randomly , Return to the scrambled sequence >>>s=[1, 2, 3, 4, 5, 6, 7, 8, 9]; random.shuffle(s); print(s) [3, 9, 7, 4, 1, 2, 6, 5, 8] |