In programming, random number generation is a very common requirement. Whether it is simulating random events, generating random samples, building games, data analysis, machine learning, etc., it is inseparable from the use of random numbers. Python'srandom
The library provides us with a wealth of functions that can easily generate various types of random numbers and provide fine control over random processes. This article will analyze in depthrandom
Library, which takes you through how to generate and control random numbers in Python.
1. The basic functions of the random library
Python'srandom
The library supports multiple types of random number generation, including integers, floating point numbers, random sequence sampling, etc. Here are some common functions:
1. Generate random integers
-
(a, b)
: Return to a located[a, b]
Random integers in intervals, including boundaries. -
(start, stop[, step])
: Return a fromstart
arrivestop
(not included) random integer with step sizestep
, suitable for generating random numbers at specific intervals.
import random print((1, 10)) # Generate random integers between 1 and 10print((0, 10, 2)) # Generate even numbers between 0 and 10
2. Generate random floating point numbers
-
()
: Return one[0.0, 1.0)
Random floating point number of intervals. -
(a, b)
: return[a, b]
Random floating point number of intervals.
print(()) # Generate random floating point numbers between 0 and 1print((1.5, 3.5)) # Generate random floating point numbers between 1.5 and 3.5
3. Randomly select from the sequence
-
(seq)
: From non-empty sequenceseq
Returns an element randomly. -
(seq, weights=None, k=1)
: fromseq
Random selectionk
Elements, support weighted random selection.
colors = ['red', 'green', 'blue', 'yellow'] print((colors)) # Select a color randomly from colorsprint((colors, k=2)) # Randomly select 2 colorsprint((colors, weights=[1, 1, 10, 1], k=3)) # 'blue' has a high weight and a higher probability of being selected
4. Randomly disrupt sequences
-
(seq)
: Sequenceseq
The elements in the middle are randomly disrupted. Note that the method is directly modified on the original sequence and there is no return value.
numbers = [1, 2, 3, 4, 5] (numbers) print(numbers) # Output: [3, 1, 5, 2, 4], random order
5. Generate random samples
-
(population, k)
: frompopulation
Random selectionk
A non-repetitive element is suitable for cases where there is no re-release sampling.
numbers = list(range(1, 11)) print((numbers, 3)) # Randomly select 3 unrepeated numbers from 1 to 10
2. Advanced control of random number generation
1. Set random seeds: ()
To ensure the reproducibility of random number sequences, you can use()
Function sets random seeds. The same seed value generates the same random sequence, suitable for testing and debugging.
(42) print((1, 10)) # Use the same seed and the results will be consistent
2. Control the random number generation of probability distribution
random
The library also provides a variety of random number generation methods for probability distributions, including:
-
normal distribution:
(mu, sigma)
or(mu, sigma)
, return mean ismu
, the standard deviation issigma
Normally distributed random number. -
Exponential distribution:
(lambd)
, return the average value as1/lambd
The exponential distribution random number. -
Even distribution:
(a, b)
,return[a, b]
The evenly distributed random numbers between them. -
Beta distribution:
(alpha, beta)
, returns a random number that matches the beta distribution, suitable for the probability distribution model.
# normal distributionprint((0, 1)) # Normal distribution of mean 0, standard deviation 1 # Exponential Distributionprint((0.5)) # lambd = 0.5 # beta distributionprint((2, 5)) # alpha = 2, beta = 5
3. Practical Examples
Example 1: Simulation of dice rolling
We can use()
Simulate the dice rolls multiple times and count the results.
import random def roll_dice(n): results = [(1, 6) for _ in range(n)] return results print(roll_dice(10)) # Simulation throw 10 times dice
Example 2: Generate a random password
Randomly generate a password containing upper and lower case letters and numbers.
import random import string def generate_password(length): chars = string.ascii_letters + password = ''.join((chars, k=length)) return password print(generate_password(8)) # Generate 8-bit random password
Example 3: Simulate normal distributed data and visualize
Generate data that conforms to normal distribution and usematplotlib
Visualization.
import random import as plt # Generate 1000 normally distributed datadata = [(0, 1) for _ in range(1000)] # Draw histogram(data, bins=30, edgecolor='black') ("Normal Distribution") ("Value") ("Frequency") ()
Example 4: Weighted Random Selection Simulation Lottery
Suppose there are 4 kinds of prizes, each with a different chance of winning. The draw process can be simulated by setting weights.
prizes = ['Prize A', 'Prize B', 'Prize C', 'Prize D'] weights = [0.1, 0.2, 0.5, 0.2] # Prize weight, Prize C has the highest probability of winning # mock lotteryresult = (prizes, weights=weights, k=1) print(f"The prize won is: {result[0]}")
Example 5: Simulate user behavioral data when accessing websites
In data science and machine learning projects, we often need to simulate user behavior data to test models. For example, suppose we need to generate the number of times a user visits a website per hour, we can use a normal distribution to simulate fluctuations in access behavior.
import random import as plt # Simulate 24 hours of access datahours = list(range(24)) visits = [int((50, 15)) for _ in hours] # Average visits per hour 50, standard deviation 15 # Draw access behavior diagram(hours, visits, marker='o') ("Simulated Website Visits Per Hour") ("Hour of the Day") ("Number of Visits") (hours) (True) ()
In this example, we assume that hourly visits meet a normal distribution, with an average of 50 and a standard deviation of 15. Through this simulation, we can obtain a set of access data with normal fluctuations for testing and analysis.
Example 6: Implementing a simple dice game
We can implement a simple dice game using random number generation. Two dices are thrown at each time, if the sum of the points is 7 or 11, the player wins, otherwise the player fails.
import random def dice_game(): dice1 = (1, 6) dice2 = (1, 6) total = dice1 + dice2 print(f"Dice results:{dice1} and {dice2},总and:{total}") if total in {7, 11}: return "Congratulations, you won!" else: return "I'm sorry, you lost." # Play gamesprint(dice_game())
This simple dice game can be expanded into multiplayer games, or add more rules, such as continuous throws, accumulated scores, etc. Through random generation and result judgment of dice, we simulated a simple game scene.
Example 7: Generate random numbers that match custom probability distributions
In some cases, we need to generate random numbers that match a particular probability distribution, for example, generate a random number that matches the Gaussian distribution but is within a certain interval. Can be used()
Generate values and combine loops and conditional restrictions to ensure that the generated random numbers are within a certain interval.
import random def bounded_normal_dist(mean, std_dev, lower_bound, upper_bound): while True: value = (mean, std_dev) if lower_bound <= value <= upper_bound: return value # Generate random numbers with a conforming mean of 10, a standard deviation of 3, and a range of 5 to 15print(bounded_normal_dist(10, 3, 5, 15))
Here, the random numbers we generate conform to the normal distribution, but are limited to[5, 15]
Within the interval. Through this approach, we can generate customized random data that meets business needs more flexibly.
summary
This article discusses in depthrandom
The library's random number generation and control includes common operations such as basic random integers, floating-point number generation, random sequence sampling, weighted selection, random sequence disruption and other common operations. We also discussed how to set up random seeds, simulate probability distribution, and demonstrated them in combination with actual cases.random
Flexible application of the library.
Random number generation is an indispensable tool in many fields such as data science, simulation experiments, and game development. I hope that the content of this article can help your project and improve the efficiency and accuracy of random number generation!
4. Things to note
Pseudo-randomity of random numbers:
random
The random numbers in the library are pseudo-random numbers and are generated by mathematical algorithms. Therefore, although it may seem random on the surface, the results are predictable as long as the seeds are the same.Multiple experiments controllability: When simulating experiments, the same seeds are usually set before each experiment so that the results are controllable. If random numbers are generated in a concurrent environment, it is recommended that each thread use independent seeds to ensure that the generation process is independent.
Beware of deviations in randomness: Unexpected deviations may occur when generating random numbers. For example, when weighted random selection, make sure that the total weight is set appropriately to avoid the probability of an element being far higher than that of other elements.
Summarize
Python'srandom
The library provides rich random number generation and control functions, which can meet the random number needs in most scenarios. Through the functions and examples introduced in this article, you can easily generate random numbers of integers, floating point numbers, sequence samples and other types, and control the probability distribution of the generation process. The generation of random numbers is very useful in the fields of simulation, data analysis, machine learning, etc. Mastering these technologies will make your program more flexible and random.
This is the introduction to this article about the actual combat of random number generation random library in Python. For more related content of Python random library, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!