random: Generation and application of random numbers in Python

Foreword

In actual development, random number generation is often used. The random library is dedicated to the generation of random numbers. It provides a fast pseudo-random number generator based on the Mersenne Twister algorithm.

This article will explain in detail the application of random number generation in various scenarios.

Generate random numbers

For the generation of random numbers, the random library provides many functions, some are responsible for generating floating point numbers, some are responsible for generating integers, and some can generate random numbers within an interval, etc.

Function name Parameters Meaning
random No parameters Randomly generate floating point numbers between [0-1]
uniform 2 integer parameters: minimum number, maximum number Randomly generate a floating point number between the minimum and maximum
randint 2 integer parameters: minimum number, maximum number Randomly generate 3 integers between the minimum and maximum
randrange Integer parameters: minimum number, maximum number, step size Randomly generate the interval step size integer between the minimum and maximum

Next, let’s take a look at the applications of these commonly used random number generation functions:

import random

# Randomly generate floating point numbers between [0-1]
print(" .2f" % random.random())
# Randomly generate floating point numbers
print(" .2f" % random.uniform(100, 200))
# Randomly generate integers
print(random.randint(1, 200))
# Randomly generate integers
print(random.randrange(0, 200, 5))

After running, the effect is as follows:

The above are the most commonly used and common uses of random numbers.

Seeds

I don’t know if readers have noticed that although random numbers can be generated through the above methods, the random numbers are all disordered. This time you may run it with a number at the beginning and a number at the end. Next time you run it, the beginning and end will be different. This is obviously not suitable for random number requirements that require a fixed sequence.

Therefore, the random library provides us with the seed function: random.seed(). The seed will control the first value generated by the formula. Since the formula is deterministic, as long as the seed is the same every time, the sequence value of the random number generated will be the same every time.

import random

random.seed(1)
# Randomly generate floating point numbers
print(" .2f" % random.random())
# Randomly generate floating point numbers
print(" .2f" % random.uniform(100, 200))
# Randomly generate integers
print(random.randint(1, 200))
# Randomly generate integers
print(random.randrange(0, 200, 5))

Run the above code multiple times and you will find that the random number is the same every time.

random.sample

Bloggers often write scripts to brush comments, but for crawlers, there is a unique random number requirement. For example, if I want to comment on 20 web pages, then if I put the 20 web pages in the array, there will be an index of (0, 19) to select. If you use ordinary interval random numbers, you may miss some values, which means you will also miss some web pages without comments.

At this time, the blogger definitely hopes to generate a random number sample in the (0, 19) interval without repetition. It is guaranteed that after a cycle of comments is completed, no web page is missed. So how to use the random library to operate this requirement?

Of course, the answer is already given in the subtitle, you can use the random.sample() function:

import random

print(random.sample(range(0, 20), 20))

After running, the effect is as follows:

The first parameter of random.sample is an interval array. For example, the random number is in (0,19), then the first parameter is range(0,19); the second parameter is how many non-repeating random numbers to generate, all of which are needed here. All web pages can be commented on, so 20 random numbers are generated. You can see that all the random numbers above do not repeat, and are all in intervals and unique. (This function can also be used to issue playing cards. Interested readers can write their own code to master it)

Random element

In probability statistics, we often use random numbers to predict probabilities, such as what is the probability of a coin landing on heads, etc. What if this random element operation for finding probability is implemented through random numbers?

The answer is the random.choice() function, which randomly selects elements from a sequence. For example, here we toss a coin 10,000 times and see what the probability is of each side landing up. The specific code is as follows:

import random

coin_pro = {
    'heads': 0,
    'tails': 0,
}
coin = ['heads', 'tails']
for i in range(10000):
    coin_pro[random.choice(coin)] + = 1
print("Number of heads:", coin_pro['heads'])
print("Number of tails:", coin_pro['tails'])

After running, we will get the times, so we can also calculate the probability.

SystemRandom

There is also a SystemRandom class under the random library. The series generated by this class is non-renewable because its randomness follows the system, not from the software itself.

Let’s look at a piece of code first:

import random
import time

r1 = random.SystemRandom()

print(r1.random())
seed = time.time()

r1 = random.SystemRandom(seed)
print(r1.random())

After running, the effect is as follows:

You can simply understand SystemRandom as a random number generated based on the system time factor as the random number generation factor. (Just making an analogy), that is, the above seed factor does not work at all, it only uses the random seed of the system.

Non-uniform distribution

Readers who use the numpy library should often use this library to generate some normally distributed values. Similarly, the random random number library also provides functions of these distributions for scientific computing applications. Next, we will explain how these random numbers are generated.

Function Meaning
betavariate() Returns a random floating point number between 0 and 1 (used for statistical information) according to the Beta distribution
expovariate() According to the exponent Distribution (used for statistics), returns a random floating point number between 0 and 1 or between 0 and -1 if the argument is negative
gammavariate() Returns a random floating point number between 0 and 1 (used for statistical information) according to the Gamma distribution
gauss() Returns a random floating point number between 0 and 1 according to the Gaussian distribution (used in probability theory)
lognormvariate() Returns a random floating point number between 0 and 1 according to the lognormal distribution (used in probability theory)
normalvariate() Returns a random floating point number between 0 and 1 according to the normal distribution (used in probability theory)
vonmisesvariate() According to von The Mises distribution returns a random floating point number between 0 and 1 (used for directional statistics)
paretovariate() According to the Pareto distribution (in Used in probability theory) returns a random floating point number between 0 and 1
weibullvariate() Returns between 0 and 1 according to the Weibull distribution of random floating point numbers (used for statistics)

Normal distribution

The random library provides the functions normalvariate() and gauss() to generate normal distributed random numbers (Gaussian distribution). Of course, there is also a function lognormvariate() that can also generate a normal distribution, but the normal distribution it generates is suitable for the product of multiple non-interacting random variables.

import random

for i in range(2):
    print(random.normalvariate(0, 1))

for i in range(2):
    print(random.gauss(0, 1))

After running, the effect is as follows:

All of the above have 2 parameters: mean and covariance. The average is a coordinate in N-dimensional space, indicating the most likely location of the sample. This is similar to the peak of a bell curve of a one-dimensional or univariate normal distribution. Covariance represents the level at which two variables vary together.

Approximate distribution

Triangular distribution, also known as Simpson distribution or triangular distribution. In probability theory and statistics, the triangular distribution is a continuous probability distribution with a lower limit a, a mode c, and an upper limit b.

The triangular() method returns a random floating point number between two specified numbers (inclusive), but you can also specify a third parameter, the mode parameter. The mode parameter gives you the opportunity to weigh possible outcomes closer to one of the other two parameter values. The mode parameter defaults to the midpoint between the other two parameter values, which will not weigh possible outcomes in any direction.

import random

print(random.triangular(20, 60, 30))

After running, the effect is as follows:


———————————END——————- ——–

Digression

In this era of big data, how can you keep up with scripting without mastering a programming language? Python, the hottest programming language at the moment, has a bright future! If you also want to keep up with the times and improve yourself, please take a look.

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.


CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

1. Python learning routes in all directions

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Essential development tools for Python

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

img

6. Interview Guide

Resume template

CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

If there is any infringement, please contact us for deletion.