伪随机数生成
# 伪随机数概念
numpy.random 模块对 Python 内置的 random 进行了补充,增加了一些用于高效生成多种概率分布的样本值的函数
之所以被称作伪随机数而不是随机数是因为它们都是通过算法基于随机数生成器种子在确定性的条件下生成的
# 常用函数
rand
产生指定形状的均匀分布的样本值
randint
从给定的上下限范围内选取随机整数
randn
产生正态分布(平均值为 0,标准差为 1)的样本值,类似于 MATLAB 接口
binomial
产生二项分布的样本值
normal
产生正态(高斯)分布的样本值
beta
产生 Beta 分布的样本值
chisquare
产生卡方分布的样本值
gamma
产生 Gamma 分布的样本值
uniform
产生在指定范围中均匀分布的样本值
seed
确定随机数生成器的种子
permutation
返回一个序列的随机排列或返回一个随机排列的范围
shuffle
对一个序列就地随机排列
import numpy as np
1
np.random.rand(3,4)
1
array([[0.25576472, 0.79349969, 0.27850507, 0.90933056],
[0.1968004 , 0.43184137, 0.85308284, 0.63514769],
[0.63847559, 0.69836197, 0.93565657, 0.14745512]])
np.random.randint(5, size=(3, 4))
1
array([[2, 1, 3, 4],
[0, 2, 0, 0],
[0, 3, 1, 1]])
np.random.randn(2, 4)
1
array([[-1.79805827, 0.89237606, -1.21227477, -0.20863569],
[-0.81141731, 1.74030762, -1.38814223, -0.03197699]])
mu, sigma = 0, 0.1
np.random.normal(mu, sigma, 10)
1
2
2
array([-0.03016733, 0.11870897, -0.05943379, 0.18551091, -0.01320171,
0.03111292, -0.20898771, 0.17931511, -0.0242517 , 0.09924793])
# 生成指定范围的样本值
np.random.uniform(1, 2, 100)
1
2
2
array([1.51425789, 1.42449746, 1.45887765, 1.91509535, 1.92949115,
1.99208297, 1.26730716, 1.06134035, 1.10288814, 1.39686364,
1.75348267, 1.08746638, 1.68855474, 1.02284299, 1.49622678,
1.04692763, 1.38959372, 1.09019307, 1.37183829, 1.17243861,
1.84493604, 1.73825886, 1.5884553 , 1.09940849, 1.84580879,
1.67676695, 1.55877251, 1.58046459, 1.33408609, 1.29782968,
1.75106753, 1.61941412, 1.26676746, 1.31206665, 1.20164265,
1.99517187, 1.69007977, 1.32918295, 1.6460843 , 1.92691491,
1.77403678, 1.80892126, 1.21145148, 1.34260398, 1.34524418,
1.9365615 , 1.47606591, 1.39958125, 1.33588063, 1.88750897,
1.42572515, 1.44809173, 1.71830767, 1.41811896, 1.19826113,
1.32594578, 1.67826219, 1.85311161, 1.04663232, 1.42194556,
1.92904229, 1.83680751, 1.64237948, 1.4085441 , 1.81492615,
1.58980861, 1.23311607, 1.74682403, 1.52345087, 1.57221728,
1.65626852, 1.03119812, 1.48341747, 1.64399359, 1.19550523,
1.79558785, 1.98058089, 1.33055709, 1.76171829, 1.70375583,
1.8616869 , 1.26968364, 1.96928118, 1.40622763, 1.52917968,
1.64951899, 1.68269751, 1.64226908, 1.41391802, 1.83384097,
1.56406308, 1.52084994, 1.182223 , 1.49735871, 1.29772454,
1.2376237 , 1.64392624, 1.68856876, 1.53722271, 1.84031282])
上次更新: 2023/11/01, 03:11:44