Python random number generation (1): random module

There are two main ways to generate random numbers in Python , one is to use the random module to generate, and the other is to use the random function in the numpy library to generate. In our daily use, if it is to obtain a random single number , consider the random module ; if it is to obtain a matrix of random decimals or integers , consider the random function in numpy .
In addition, the scipy.stats module can also generate random numbers and random numbers from a specific distribution.

For other ways to generate random numbers, see the author's other articles:
Python Random Number Generation (2): The random function in the numpy library

The random module generates random numbers

(1) Generate random integers

① random.randint(a, b)

Function: Return a random integer N satisfying a ≤ N ≤ b. Equivalent to randrange(a, b+1).
usage:

import random
number = random.randint(3,7)
# 输出:6

② random.randrange(start, stop[, step])

Function: Randomly select a number in an integer sequence generated <starting with a, incrementing at each step, and ending with b>. [, step] indicates that the parameter is optional.
usage:

import random
number = random.randrange(2,8,2)
# 输出:6

(2) Generate random floating point numbers

random.random()

Function: Generate a random floating point number between [0,1).
usage:

import random
number = random.random()
# 输出:0.7365131579088379

② random.uniform(a, b)

Function: Return a random floating-point number N between a and b. When a ≤ b, the range of N is [a, b], and when b < a, the range of N is [b, a].
usage:

import random
number = random.uniform(1,4)
# 输出:1.8288291918995063

(3) Generate random numbers from the specified sequence

① random.choice(seq)

Function: Randomly select an element from the sequence seq.
usage:

import random
a = random.choice(range(1,10))
# 输出:4
b = random.choice('abcdefg')
# 输出:e

② random.choices(seq, weights=None, *, cum_weights=None, k=1)

Function: Randomly select k elements from the sequence seq with the specified weight , and return a new list.

  • If a weight sequence is specified, selections are made based on relative weights .
  • If the cum_weights sequence is specified, selections are made based on cumulative weights .
  • If neither weight nor cum_weights are specified, selections are made with equal probability .
  • If a weight sequence is provided , it must be the same length as the seq sequence .

usage:

import random
a = random.choices(['red', 'black', 'green'], [18, 18, 2], k=6)
# 输出:['red', 'black', 'red', 'red', 'black', 'red']

③ random.sample(seq, k)

Function: Randomly select k elements from the sequence seq and return a new list.
usage:

import random
a = ['小红','小兰','小王','小张','小梁']
b = random.sample(a,2)
# 输出:['小梁', '小王']

④ random.shuffle(seq)

Function: Randomly sort the elements in the sequence seq.
usage:

import random
a = ['小红','小兰','小王','小张','小梁']
random.shuffle(a) # 打乱这个操作不需要重新定义对象,它作用的是对象本身
# 输出:['小兰', '小王', '小红', '小梁', '小张']

(4) Generate random numbers of a specific distribution

1. Uniform distribution

Uniform distribution means that in the event space, the probability of all events is equal to the continuous distribution, and its probability density is (
insert image description here
a+b)/2 with a mean of (a+b)/2 and a variance of (b−a)^2/12

random.random()

Function: Generate a random floating point number between [0,1).
See above for usage.

② random.uniform(a, b)

Function: Return a random floating-point number N between a and b. When a ≤ b, the range of N is [a, b], and when b < a, the range of N is [b, a].
See above for usage.

2. Triangular distribution

For a triangular distribution whose lower limit is a, upper limit is b, and mode is c, the probability density function is
insert image description here

① random.triangular(low, high, mode)

Function: Return a random floating-point number N of a triangular distribution, such that low ≤ N ≤ high, mode indicates where the mode appears. low and high default to 0 and 1. The mode parameter defaults to the midpoint between low and high, giving a symmetrical triangular distribution.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.triangular(2,3,2.5) for i in range(20000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000")#密度图

Histogram:
insert image description here
Density plot:
insert image description here

3. Exponential distribution

The exponential distribution is a continuous distribution, and the probability density function is:


The distribution function is:

insert image description here
Expectation: , Variance:insert image description here

① random.expovariate(lambd)

Function: Exponential distribution. lambd is 1.0 divided by the desired mean, which should be non-zero. (The parameter should have been named "lambda", but that's a reserved word in Python.) If lambd is positive, the return value ranges from 0 to positive infinity; if lambd is negative, the return value ranges from negative infinity to 0 .
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.expovariate(2) for i in range(50000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here

Density plot:
insert image description here

4. Normal distribution

① random.normalvariate(mu, sigma)

Function: Normal distribution. mu is the mean and sigma is the standard deviation.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.normalvariate(2,4) for i in range(20000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here
Density plot:
insert image description here

5. Lognormal distribution

① random.lognormvariate(mu, sigma)

Function: lognormal distribution. Taking the natural logarithm of this distribution results in a normal distribution with mean mu and standard deviation sigma. mu can be any value and sigma must be greater than zero.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.lognormvariate(4,2) for i in range(50000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here
Density plot:
insert image description here

6. Gaussian distribution

① random.gauss(mu, sigma)

Function: Gaussian distribution. mu is the mean and sigma is the standard deviation. This is slightly faster than the random.normalvariate(mu, sigma) function.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.gauss(2,2) for i in range(50000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here
Density plot:
insert image description here

7. Beta distribution

① random.betvariate(alpha, beta)

Function: Beta distribution. The parameters are conditional on alpha > 0 and beta > 0. The returned value ranges between 0 and 1.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.betavariate(1,2) for i in range(20000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here
Density plot:
insert image description here

8. Gamma distribution

① random.gammavariate(alpha, beta)

Function: Gamma distribution. (Not the gamma function!) The parameters are conditional on alpha > 0 and beta > 0.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.gammavariate(2,2) for i in range(50000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here
Density plot:
insert image description here

9. Pareto distribution

In 1906, Pareto proposed the law of wealth distribution in Italian society, that is, 20% of the population owned 80% of the wealth. This law was later found to be so common that Joseph Juran later called it Pareto. The Tortoise Rule is also known as the Eighty-Two Rule.
The Pareto distribution is exactly the description of this rule, and its probability distribution function is
insert image description here

① random.paretovariate(alpha)

Function: Pareto distribution. alpha is a shape parameter.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.paretovariate(4) for i in range(50000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here
Density plot:
insert image description here

10. Weibull distribution

① random.weibullvariate(alpha, beta)

Function: Weibull distribution. alpha is a scale parameter and beta is a shape parameter.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.weibullvariate(1,2) for i in range(20000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here

Density plot:
insert image description here

11. Von Mises distribution

① random.vonmisesvariate(mu, kappa)

Function: von Mises distribution. mu is the mean angle, expressed in radians, between 0 and 2 pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa equals zero, the distribution reduces to a uniform random angle in the range 0 to 2 pi.
usage:

import random
import matplotlib.pyplot as plt
import seaborn as sns
data = [random.vonmisesvariate(2,2) for i in range(20000)]
plt.hist(data, bins=100, color="#FF0000", alpha=.7) # 直方图
sns.kdeplot(data, shade=True,color="#FF0000") # 密度图

Histogram:
insert image description here
Density plot:
insert image description here

references

1. Generation of random numbers in Python
2. Official documentation of the Random module

Guess you like

Origin blog.csdn.net/weixin_44842318/article/details/129615388