Python random module usage arrangement

Random numbers play an important role in the field of computer science and are used to simulate real-world randomness, data generation, cryptography, and many other fields. The random module in Python provides a wealth of random number generation functions. This article summarizes the use of the random module.

Python random module

Precautions

  • Pseudorandomness : Python uses the random module to generate pseudorandom numbers from various distributions . Computer-generated random numbers are all pseudo-random numbers, which are generated by a deterministic algorithm and just look random. If a high degree of randomness is required, additional sources of randomness are required.

  • Different types of randomness : In scenarios such as simulation, cryptography, etc., different types of randomness requirements need to be paid attention to. If you head to the Python docs for documentation for this module, you'll see a warning:

    insert image description here
    Obviously, the random module is only suitable for general random number needs. The random module uses the Mersenne Twister algorithm to generate random numbers. But this algorithm is completely deterministic, and for scenarios that require high-intensity randomness, such as cryptography, the secrets module should be used.

Built-in functions of the Python random module

Below are the various built-in functions under the random module. These functions can generate pseudo-random numbers in different scenarios:

insert image description here
The following list contains brief descriptions of the above random number generator functions:

Function name describe
randint(a, b) generate a [a, b]random integer in the range
randrange(start, stop, step) generate a steprandom element in a sequence of integers incremented by
random() Generate a random floating point number in the range [0.0, 1.0)
uniform(a, b) Generates a [a, b)random floating point number in the range
gauss(mu, sigma) Generate a random floating-point number that conforms to a Gaussian distribution with mean muand standard deviationsigma
sample(population, k) populationRandomly select kelements from the sequence without repetition
choice(sequence) Randomly select an element from a sequence
shuffle(sequence) Randomly shuffle the order of elements in a sequence
seed(a=None) Initialize the seed of the random number generator used to reproduce the random sequence

Below are more detailed descriptions and examples of these functions.

randint()

This function generates integers between the specified range. It accepts two parameters xxxyyy and generate integeriii,使得 x < = i < = y x <= i <= y x<=i<=y

import random

a = random.randint(3, 6)
print(a)	# 输出:3

randrange()

This function generates a random element in a sequence of integers stepwith a step size of . startand stopare ranges, and the range of values ​​is [start, stop). If stepthe parameter is omitted, it defaults to 1.

import random

a = random.randrange(1, 10, 2)
print(a)	# 输出:7

random()

This function generates a [0.0, 1.0)random floating point number in the range. All numbers in this range have equal probability.

import random

a = random.random()
print(a)	# 输出:0.6427979778735594

uniform()

This function generates a [a, b)random floating point number in the range. Similar random(), but you can specify a range.

import random

a = random.uniform(3, 6)
print(a)	# 输出:3.512451152441262

gauss(mu, sigma)

This function generates a random floating point number that follows a Gaussian distribution (also known as a normal distribution). muis the mean and sigmais the standard deviation, controlling the shape of the distribution.

import random

a = random.gauss(3, 0.5)
print(a)	# 输出:2.9743970359818612

sample()

If you want multiple random elements in a sequence, you can use sample(). It takes two arguments populationand k, where populationis a sequence and kis an integer. The function then populationrandomly selects kelements from the sequence and returns them as a list. Choose not to repeat.

import random

seq = (12, 33, 67, 55, 78, 90, 34, 67, 88)
a = random.sample(seq, 5)
print(a)	# 输出:[88, 78, 67, 34, 33]

choice(sequence)

You can use this function if you want to select random elements from a specific sequence. It takes one parameter -- sequence. It returns a random element from a sequence.

import random

seq = (12, 33, 67, 55, 78, 90, 34, 67, 88)
a = random.choice(seq)
print(a)	# 输出:88

Notice: random.choice(seq)Not equivalent to random.sample(seq, 1), the former returns an element, and the latter returns a list.

shuffle(sequence)

This function takes one parameter - a list. It then shuffles the elements of the list and returns.

import random

a = [10, 20, 30, 40, 50]
random.shuffle(a)
print(a)	# 输出:[30, 10, 20, 40, 50]

seed(a=None)

This function can be used when the same sequence of random numbers needs to be generated multiple times. It takes one parameter - the seed value. This value initializes the pseudorandom number generator. Whenever the function is called with the same seed value seed(), it will produce the exact same sequence of random numbers, which is useful for cases where random results need to be reproduced.

import random
# seed value = 3
random.seed(3)
for i in range(3):
    print(random.random(), end = ' ')

print('\n')

# seed value = 8
random.seed(8)
for i in range(3):
    print(random.random(), end = ' ')

print('\n')

# seed value again = 3
random.seed(3)
for i in range(3):
    print(random.random(), end = ' ')

print('\n')

Output:
0.23796462709189137 0.5442292252959519 0.36995516654807925

0.2267058593810488 0.9622950358343828 0.12633089865085956

0.23796462709189137 0.5442292252959519 0.36995516654807925

It can be seen that for seed = 3, the same sequence is generated every time.

Guess you like

Origin blog.csdn.net/a2360051431/article/details/132308513