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 .
Initializes a given random number seed , The default is the current system time
>>>random.seed(10) # Produce seeds 10 Corresponding sequence
Generate a [0.0,1.0) Between random decimals
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
Generate a [a,b] Integer between
Generate a [m,n) Between k Is a random integer of step size
Generate a k Random integers that are longer than special
Generate a [a,b] Between random decimals
Randomly select an element from a sequence
>>>random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9])
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]