The method of generating random number in Python built-in random module

This article mainly introduces the method of generating random numbers by Python's built-in random module. This article gives you a very detailed introduction, which has certain reference value. You can refer to
In this paper, we introduce in detail the other methods of generating random sequence in the next two modules.

The application scenarios that random numbers participate in will be familiar to you. For example, when adding salt to a password, a string of random numbers will be associated with the original password, and Monte Carlo algorithm will sample through random numbers, etc. Python's built-in random module provides methods for generating random numbers, which need to be imported.

import random

Here are a few ways to generate random numbers from Python's built-in random module.

1. random.random() randomly generates floating-point numbers [0.0, 1.0] between 0 and 1. Note that the random number returned may be 0 but not 1, that is, the left closed right open interval.

print("random: ", random.random())
#random: 0.5714025946899135

2. Random. RandInt (a, b) randomly generates integers between a and B [a, b], a < = n < = B, when the random integers do not contain B [a, b], the random. Randange() method can be used.

print("randint: ", random.randint(6,8))
#randint: 8

3. Random. Random (start, stop, step) randomly takes a random number within the upper and lower limits according to step size, start < = n < stop.

print("randrange: ",random.randrange(20,100,5))
#randrange: 85

4. random.uniform(a, b) randomly generates floating-point numbers between a and B [a, b], a < = n < = B.

print("uniform: ",random.uniform(5,10))
#uniform: 5.119790163375776

5. random.choice() randomly takes an element from the list, such as list, ancestor, string, etc. Note that the method requires a non null parameter, otherwise an IndexError error error will be thrown.

print("choice: ",random.choice(""))
#choice: y

6. random.shuffle(items) randomly scrambles elements in list items. Note that if you do not want to modify the original list, you can use the copy module to copy the original list first.

num = [1, 2, 3, 4, 5]
print("shuffle: ",num)
#shuffle: [1, 3, 5, 4, 2]

7. random.sample(items, n) randomly takes n elements from the list items.

num = [1, 2, 3, 4, 5]
print("sample: ",random.sample(num, 3))
#sample: [4, 1, 5]

The random number generated by Python's random module is actually a pseudo-random number, which depends on special algorithm and seed. For example, if randint method generates random numbers within a certain range, it will first specify a specific seed, and then seed will be generated through a specific random number generation algorithm to obtain random numbers within a certain range. Therefore, the random number generated by the same seed value input will be the same. Omitting the parameter means that the current system time seconds is used as the seed value, and the random number generated by each run will be different.

print("random: ", random.random())
#random: 0.9560342718892494
print("random: ", random.random())
#random: 0.23796462709189137
random.seed(3)#The same seed value produces the same random number
print("random: ", random.random())
#random: 0.23796462709189137

The numpy library also provides a random module to generate random numbers in the form of multidimensional arrays. You need to import the numpy library when you use it.

import numpy as np

The following describes several methods of generating random numbers in random module of numpy library.


The rand function generates data between [0,1] according to the given dimension, including 0, excluding 1
dn table each dimension
The return value is the array of the specified dimension

print("np.random.rand: \n {}".format(np.random.rand(4,2))) 
# shape: 4*3
 [[0.5488135 0.71518937]
 [0.60276338 0.54488318]
 [0.4236548 0.64589411]
 [0.43758721 0.891773 ]]
print("np.random.rand: \n {}".format(np.random.rand(4,3,2))) 
# shape: 4*3*2
 [[[0.96366276 0.38344152]
 [0.79172504 0.52889492]
 [0.56804456 0.92559664]]
 [[0.07103606 0.0871293 ]
 [0.0202184 0.83261985]
 [0.77815675 0.87001215]]
 [[0.97861834 0.79915856]
 [0.46147936 0.78052918]
 [0.11827443 0.63992102]]
 [[0.14335329 0.94466892]<br>  [0.52184832 0.41466194]<br>  [0.26455561 0.77423369]]]<br>"""


The randn function returns one or a set of samples with a standard normal distribution.
dn table each dimension
The return value is the array of the specified dimension
standard normal distribution
The standard normal distribution, also known as u distribution, is a normal distribution with 0 as the mean and 1 as the standard deviation, which is recorded as N (0,1).

print("np.random.randn: \n {}".format(np.random.randn())) 
# Returns a single data when there are no parameters
print("np.random.randn: \n {}".format(np.random.randn(2,4)))
 [[-1.45436567 0.04575852 -0.18718385 1.53277921]
 [ 1.46935877 0.15494743 0.37816252 -0.88778575]]
print("np.random.randn: \n {}".format(np.random.randn(4,3,2)))
 [[[-1.98079647 -0.34791215]
 [ 0.15634897 1.23029068]
 [ 1.20237985 -0.38732682]]
 [[-0.30230275 -1.04855297]
 [-1.42001794 -1.70627019]
 [ 1.9507754 -0.50965218]]
 [[-0.4380743 -1.25279536]
 [ 0.77749036 -1.61389785]
 [-0.21274028 -0.89546656]]
 [[ 0.3869025 -0.51080514]
 [-1.18063218 -0.02818223]
 [ 0.42833187 0.06651722]]]

3,numpy.random.randint(low, high=None, size=None, dtype='l')

Returns a random integer with a range of [low,high], including low, excluding high
Parameters: low is the minimum value, high is the maximum value, size is the array dimension size, dtype is the data type, and the default data type is
When high is not filled in, the range of random number generated by default is [0, low]

print("np.random.randint: \n {}".format(np.random.randint(1,size=5)))
# Returns an integer between [0,1], so only 0
 [0 0 0 0 0]
print("np.random.randint: \n {}".format(np.random.randint(1,5)))# Returns a random integer of [1,5] time
print("np.random.randint: \n {}".format(np.random.randint(-5,5,size=(2,2))))
 [[-5 -3]
 [ 2 -3]]


Function of np.random.seed(): make random data predictable.

When we set the same seed, we generate the same random number each time. If seed is not set, different random numbers will be generated each time
Recommend our Python learning base to see how the seniors learn! From basic Python script, crawler, django, data mining and other programming technologies, as well as sorting out zero basic data to project actual combat data, to every little partner who loves to learn Python! Every day, seniors regularly explain Python technology, share some learning methods and small details that need attention, and click to join our python learners' gathering place

39 original articles published, 38 praised, 50000 visitors+
Private letter follow

Keywords: Python Django Programming

Added by rwoods on Sat, 22 Feb 2020 15:50:30 +0200