[Python basic tutorial] Python generates random numbers


foreword

The functions under the random module are generally used to generate random numbers. The generated random numbers are not real random numbers, but a simulation of random numbers. The random module contains various pseudo-random number generation functions, as well as various functions that generate random numbers from probability distributions. Our goal today is to find out how random numbers can be generated.


insert image description here

1. Random number seed

Why propose a random number seed? As we mentioned earlier, random numbers are all simulated.
If you want to simulate more realistically, you need to change the value in the seed function. Generally, the timestamp is used as the seed of the random function.
For example, in the following case, when the random number seed is fixed, the generated random number will also be fixed.
By default, the system uses the timestamp as the seed to generate random numbers.
Single timestamp
insert image description here
Random timestamp
insert image description here
First result
insert image description here
Second result
insert image description here

2. Generate random numbers

以下一生成10个1-100的随机数为例

1.random()

The random number that generates [0-1) is of type float. Most of the following functions are based on this function for random number generation.
If you want to generate random numbers in the response area, you can use this function to multiply a corresponding integer

from random import *
for i in range(10):
    print(int(random()*100+1),end=" ")
print()

2.ranint(a,b)

Randomly generate an integer of ab

from random import *
for i in range(10):
    print(randint(1,100),end=" ")

3.randrange (start, stop [, step])

There are three elements: start, end, and step size. When generating random numbers, the lower limit is included but the upper limit is not included.

from random import *
for i in range(10):
    print(int(randrange(1,101)),end=" ")


4. geared bits(k)

Returns a random integer whose bit length is k bits.

from random import *
for i in range(10):
    print(int(getrandbits(4)),end=" ")

3. Generate random sequences

1.choice(seq)

Randomly draw one from the given sequence

code show as below:

from random import *
test=[12,3,1,2,33,21]
for i in range(10):
    print(choice(test))

2. samplex(sequence, k)

Randomly select k elements from the sequence, and these k elements will not be repeated. (need to satisfy len(sequence)>=k)

code show as below:

from random import *
test=[1,23,3,22,13]
print(sample(test,3))

3.shuffle(x[,random])

The purpose of this function is to sort randomly and sort on the basis of the original sequence.

code show as below:

from random import *
test=[1,23,3,22,13]
shuffle(test)
print(test)

insert image description here


Guess you like

Origin blog.csdn.net/apple_51931783/article/details/123144689