系统学习Python——科学计算库NumPy:随机数模块numpy.random
创始人
2024-05-20 13:03:22

分类目录:《系统学习Python》总目录


numpy.random.rand

创建一个给定维度的数组,并用均匀分布[0,1)[0,1)[0,1)上的随机数填充它。

语法
numpy.random.rand(d0, d1, ..., dn)
参数

返回数组的维数d0, d1, …, dn 。必须是非负的。如果没有给出参数,则返回一个Python浮点数。

返回值

返回给定维度d0, d1, …, dn 的随机值ndarray

实例
np.random.rand(3,2)

以上实例输出结果为:

array([[0.94213748, 0.59919783],[0.89463202, 0.36933844],[0.67443296, 0.75281862]])

numpy.random.randint

返回离散均匀分布[low,high)[\text{low}, \text{high})[low,high)中的随机整数。如果high\text{high}high为None,则结果来自[0,low)[0,\text{low})[0,low)。

语法
numpy.random.randint(low, high=None, size=None, dtype=int)
参数
  • lowint或元素为int`的数组。
  • highint或元素为int`的数组,可选。
  • sizeint或元素为inttuple`,可选。
  • dtype:返回值的类型,可选。
返回值

返回[low,high)[\text{low}, \text{high})[low,high)的随机整数。

实例
np.random.randint(2, size=10)
np.random.randint(1, size=10)
np.random.randint(5, size=(2, 4))
np.random.randint(1, [3, 5, 10])
np.random.randint([1, 5, 7], 10)
np.random.randint([1, 3, 5, 7], [[10], [20]])

以上实例输出结果分别为:

array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) 
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
array([[4, 0, 2, 1], [3, 2, 2, 0]])
array([2, 2, 9]) 
array([9, 8, 7]) 
array([[ 8,  6,  9,  7], [ 1, 16,  9, 12]])

numpy.random.randn

如果提供int型参数,将返回一个形状为d0, d1, …, dn 的正态随机浮点数组。如果没有提供参数,则返回单个正态随机浮点数。

语法
numpy.random.randn(d0, d1, ..., dn)
参数

可选,返回数组的维数d0, d1, …, dn

返回值

维度为d0, d1, …, dn 的正态随机浮点数组或浮点数。

实例
np.random.randn()
3 + 2.5 * np.random.randn(2, 4)

以上实例输出结果分别为:

-2.3544327146253834
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677], [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]]) 

numpy.random.random

返回一个半开区间[0.0,1.0)[0.0,1.0)[0.0,1.0)内的随机浮点数。

语法
numpy.random.random(size=None)
参数

可选,返回数组的维数d0, d1, …, dn

返回值

返回半开区间[0.0,1.0)[0.0,1.0)[0.0,1.0)的随机浮点数。

实例
np.random.random()

以上实例输出结果分别为:

0.5686311893635402

相关内容

热门资讯

最新或2023(历届)关于铁人... 王进喜,1923年10月8日出生于甘肃省玉门县赤金堡一个贫苦的农民家庭。6岁讨饭,10岁给地主放牛,...
最新或2023(历届)森林防火... 森林防火须知手抄报图片
原创 半... 朝方突然甩出一份声明,把刚有点缓和苗头的半岛,一脚踹回了紧张模式。 2025新年钟声才敲响几天,...