2 产生随机数
PS:说明一下这个是按照我所遇到的一些函数的重要性来说明的,内容的排序没有很强的逻辑关系,实用为主
2.1 综述随机数的产生
之前说过numpy有产生随机数的功能(主要是针对数组)
>>> import numpy
>>> help(numpy.random)
Help on package numpy.random in numpy:
NAME
numpy.random
DESCRIPTION
========================
Random Number Generation
========================
==================== =========================================================
Utility functions
==============================================================================
random_sample Uniformly distributed floats over ``[0, 1)``.
random Alias for `random_sample`.
bytes Uniformly distributed random bytes.
random_integers Uniformly distributed integers in a given range.
permutation Randomly permute a sequence / generate a random sequence.
shuffle Randomly permute a sequence in place.
seed Seed the random number generator.
choice Random sample from 1-D array.
==================== =========================================================
==================== =========================================================
Compatibility functions
==============================================================================
rand Uniformly distributed values.
randn Normally distributed values.
滴滴滴~~=不想看上面文档 的话就看这里:
随机数的产生主要是使用的numpy.random
下面提供几个函数使用
Utility functions(实用函数):
random_sample(别名就是random) ``[0, 1)``均匀分布的float
seed 产生随机数种子
Compatibility functions(兼容性函数):
rand 均匀分布产生的值
randn 正态分布产生的值
2.2 numpy.random.rand()
接下来详细的介绍一下numpy.random.rand()
函数的使用
老规矩,先来看看说明文档(不看也行直接跳过,下面有解释)
>>> import numpy
>>> help(numpy.random.rand)
Help on built-in function rand:
rand(...) method of mtrand.RandomState instance
rand(d0, d1, ..., dn)
Random values in a given shape.
Create an array of the given shape and populate it with
random samples from a uniform distribution
over ``[0, 1)``.
Parameters
----------
d0, d1, ..., dn : int, optional
The dimensions of the returned array, should all be positive.
If no argument is given a single Python float is returned.
Returns
-------
out : ndarray, shape ``(d0, d1, ..., dn)``
Random values.
See Also
--------
random
Notes
-----
This is a convenience function. If you want an interface that
takes a shape-tuple as the first argument, refer to
np.random.random_sample .
Examples
--------
>>> np.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random
滴滴滴~~
首先说明一下这个函数的作用:
创建一个给定形状的n维数组,数组元素的填充是[0, 1)
之间的随机float
。
用法如下:
参数:d0,d1,...,dn
(即返回数组的维数)
返回值:n维数组,形状是(d0, d1, ..., dn)
(填充的是[0, 1)
之间的随机数)
>>> numpy.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random
2.3 numpy.random.random()
(其实这里想换点其他的词来叙述,但是大肚空了。。。哈哈哈,词穷,每一个程序员都是一个想象力极其丰富的,哈哈哈)
so…
接下来详细的介绍一下numpy.random.random()
函数的使用
老规矩,先来看看说明文档(不看也行直接跳过,下面有解释)
>>> import numpy
>>> help(numpy.random.random)
Help on built-in function random_sample:
random_sample(...) method of mtrand.RandomState instance
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Results are from the "continuous uniform" distribution over the
stated interval. To sample :math:`Unif[a, b), b > a` multiply
the output of `random_sample` by `(b-a)` and add `a`::
(b - a) * random_sample() + a
Parameters
----------
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.
Returns
-------
out : float or ndarray of floats
Array of random floats of shape `size` (unless ``size=None``, in which
case a single float is returned).
Examples
--------
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])
Three-by-two array of random numbers from [-5, 0):
>>> 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984],
[-2.99091858, -0.79479508],
[-1.23204345, -1.75224494]])
滴滴滴~~
ps:这个函数的使用就是十分灵活的了
说明一下,numpy.random.random() = numpy.random.random_sample()
函数的作用 是产生[0.0, 1.0)
的随机float.
具体的使用random(size=None)
参数size
:int或者int类型的元组,(可选)
表示的是输出的形状,其中默认的size=None,即只返回单值
输出:很好理解就是一个float或者n维的float数组
Examples
--------
>>> np.random.random()
0.47108547995356098
>>> type(np.random.random())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])
如何产生自己的需求区间呢
通过如下的使用方式
# (b - a) * random_sample() + a
Examples
--------
>>> 5 * numpy.random.random((3, 2)) - 5
array([[-3.99149989, -0.52338984],
[-2.99091858, -0.79479508],
[-1.23204345, -1.75224494]])
解释一下:
参数是元组(3,2)
因此产生的是3*2维的数组
numpy.random.random()
函数产生的值是[0.0, 1.0)
之间
5 * numpy.random.random((3, 2))
函数产生的值是[0.0, 5.0)
之间
5 * numpy.random.random((3, 2)) - 5
函数产生的值是[-5.0, 0.0)
之间
2.4 numpy.arange()和python的内建range()函数
首先、了解一下python的内建函数的range()
函数的使用
help文档查看
>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
| These are exactly the valid indices for a list of 4 elements.
| When step is given, it specifies the increment (or decrement).
ps:这上面的内容被我省略了很多,我只介绍使用方法
haha,是不是大吃一惊,range竟然是一个类,我们平时使用的range都是他的构造方法(这里其实不需要知道,会用就行)。
作用: 返回一个从[start,stop)
固定步长的序列对象(步长是可选参数)
使用:
range(stop) -> range object
range(4) produces 0, 1, 2, 3
-------------------------------
>>> range(4)
range(0, 4)
#使用类别可视化
>>> list(range(4))
[0, 1, 2, 3]
range(start, stop[, step]) -> range object
range(2,7) produces 2,3,4,5,6
range(2,7,2) produces 2,4,6
--------------------------------------------
>>> range(2,7)
range(2, 7)
#使用类别可视化
>>> list(range(2,7))
[2, 3, 4, 5, 6]
>>> range(2,7,2)
range(2, 7, 2)
#使用类别可视化
>>> list(range(2,7,2))
[2, 4, 6]
其次、
咱们首先看一下帮助文档中numpy.arange()
函数的使用
ps: python中的模块、类、函数自己通过帮助文档来查询具体的使用方法是及其的有用和方便的,能够解决你的大部分的困惑
老规矩: 此处不看可以直接跳过,看下面的解释
>>> help(numpy.arange)
Help on built-in function arange in module numpy.core.multiarray:
arange(...)
arange([start,] stop[, step,], dtype=None)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval ``[start, stop)``
(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range <http://docs.python.org/lib/built-in-funcs.html>`_ function,
but returns an ndarray rather than a list.
When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use ``linspace`` for these cases.
Parameters
----------
start : number, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : number
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : number, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
Returns
-------
arange : ndarray
Array of evenly spaced values.
For floating point arguments, the length of the result is
``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.
See Also
--------
linspace : Evenly spaced numbers with careful handling of endpoints.
ogrid: Arrays of evenly spaced numbers in N-dimensions.
mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
Examples
--------
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
解释一下:
arange()
函数的作用是产生给定区间的等间距值
没时间了,以后再补吧。。。