np.random中一些常用函数的使用:rand(),randn(),standard_normal(),randint(),normal()

numpy中的random模块是用来产生随机数的,以下是我总结的一些它里面常用函数的使用方法,如有不正确的地方,欢迎指正。

import numpy as np
import matplotlib.pyplot as plt


# 第一个函数rand(),产生[0, 1)范围内的随机数,参数代表它的形状,英文解释如下:
# Create an array of the given shape and populate it with random samples from a uniform 
# distribution(均匀分布) over ``[0, 1)``
# The dimensions of the returned array, should all be positive.If no argument 
# is given a single Python float is returned.
print(np.random.rand(3,2))#随机数组的形状是3行2列


# 第二个函数是randn(),产生均值0,方差1的正态分布随机数,参数代表它的形状,英文解释如下:
# Return a sample (or samples) from the "standard normal" distribution.
# If positive, int_like or int-convertible arguments are provided,
# `randn` generates an array of shape ``(d0, d1, ..., dn)``, filled
# with random floats sampled from a univariate "normal" (Gaussian)
# distribution of mean 0 and variance 1
# The dimensions of the returned array, should be all positive.
# If no argument is given a single Python float is returned.
# This is a convenience function.  If you want an interface that takes a
# tuple as the first argument, use `numpy.random.standard_normal` instead.
x=np.random.randn(10000)#一万个随机数
fig=plt.figure()
ax=plt.axes()
plt.hist(x,10,(-5,5))#可视化结果
plt.show()


# 第三个函数是standard_normal(),产生标准正态分布随机数,参数代表它的形状,英文解释如下:
# Draw samples from a standard Normal distribution (mean=0, stdev=1).
# size : int or tuple of ints, optional
#         Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
#         ``m * n * k`` samples are drawn.  Default is None, in which case a
#         single value is returned.
print(np.random.standard_normal((3,2)))#随机数组的形状是3行2列


# 第四个函数是randint(),产生[low,high)范围的随机数,size代表它的形状,英文解释如下:
# randint(low, high=None, size=None, dtype='l')
# Return random integers from `low` (inclusive) to `high` (exclusive).
# Return random integers from the "discrete uniform" distribution of
#     the specified dtype in the "half-open" interval [`low`, `high`). If
#     `high` is None (the default), then results are from [0, `low`).
print(np.random.randint(0,11,(3,2)))#产生[0,11)范围内int类型的随机数,数组形状3行2列


# 第五个函数是normal(),产生正太分布的随机数,英文解释如下:
# loc : float or array_like of floats
#         Mean ("centre") of the distribution.
#     scale : float or array_like of floats
#         Standard deviation (spread or "width") of the distribution.
#     size : int or tuple of ints, optional
#         Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
#         ``m * n * k`` samples are drawn.  If size is ``None`` (default),
#         a single value is returned if ``loc`` and ``scale`` are both scalars.
#         Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
print(np.random.normal(2,1,(4,4)))#产生均值2,方差1的正态分布随机数,形状是4行4列

猜你喜欢

转载自blog.csdn.net/qq_38828003/article/details/81782798