numpy.polynomial.hermite.Hermite   class numpy.polynomial.hermite.Hermite(coef, domain=None, window=None)[source]

An Hermite series class. The Hermite class provides the standard Python numerical methods ‘+’, ‘-’, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the attributes and methods listed in the ABCPolyBase documentation.  Parameters

coefarray_like

Hermite coefficients in order of increasing degree, i.e, (1, 2, 3) gives 1*H_0(x) + 2*H_1(X) + 3*H_2(x).
domain(2,) array_like, optional

Domain to use. The interval [domain[0], domain[1]] is mapped to the interval [window[0], window[1]] by shifting and scaling. The default value is [-1, 1].
window(2,) array_like, optional

Window, see domain for its use. The default value is [-1, 1].  New in version 1.6.0.      Methods
__call__(arg) Call self as a function.
basis(deg[, domain, window]) Series basis polynomial of degree deg.
cast(series[, domain, window]) Convert series to series of this class.
convert([domain, kind, window]) Convert series to a different kind and/or domain and/or window.
copy() Return a copy.
cutdeg(deg) Truncate series to the given degree.
degree() The degree of the series.
deriv([m]) Differentiate.
fit(x, y, deg[, domain, rcond, full, w, window]) Least squares fit to data.
fromroots(roots[, domain, window]) Return series instance that has the specified roots.
has_samecoef(other) Check if coefficients match.
has_samedomain(other) Check if domains match.
has_sametype(other) Check if types match.
has_samewindow(other) Check if windows match.
identity([domain, window]) Identity function.
integ([m, k, lbnd]) Integrate.
linspace([n, domain]) Return x, y values at equally spaced points in domain.
mapparms() Return the mapping parameters.
roots() Return the roots of the series polynomial.
trim([tol]) Remove trailing coefficients
truncate(size) Truncate series to length size.


numpy.polynomial.hermite_e.HermiteE   class numpy.polynomial.hermite_e.HermiteE(coef, domain=None, window=None)[source]

An HermiteE series class. The HermiteE class provides the standard Python numerical methods ‘+’, ‘-’, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the attributes and methods listed in the ABCPolyBase documentation.  Parameters

coefarray_like

HermiteE coefficients in order of increasing degree, i.e, (1, 2, 3) gives 1*He_0(x) + 2*He_1(X) + 3*He_2(x).
domain(2,) array_like, optional

Domain to use. The interval [domain[0], domain[1]] is mapped to the interval [window[0], window[1]] by shifting and scaling. The default value is [-1, 1].
window(2,) array_like, optional

Window, see domain for its use. The default value is [-1, 1].  New in version 1.6.0.      Methods
__call__(arg) Call self as a function.
basis(deg[, domain, window]) Series basis polynomial of degree deg.
cast(series[, domain, window]) Convert series to series of this class.
convert([domain, kind, window]) Convert series to a different kind and/or domain and/or window.
copy() Return a copy.
cutdeg(deg) Truncate series to the given degree.
degree() The degree of the series.
deriv([m]) Differentiate.
fit(x, y, deg[, domain, rcond, full, w, window]) Least squares fit to data.
fromroots(roots[, domain, window]) Return series instance that has the specified roots.
has_samecoef(other) Check if coefficients match.
has_samedomain(other) Check if domains match.
has_sametype(other) Check if types match.
has_samewindow(other) Check if windows match.
identity([domain, window]) Identity function.
integ([m, k, lbnd]) Integrate.
linspace([n, domain]) Return x, y values at equally spaced points in domain.
mapparms() Return the mapping parameters.
roots() Return the roots of the series polynomial.
trim([tol]) Remove trailing coefficients
truncate(size) Truncate series to length size.


numpy.polynomial.laguerre.Laguerre   class numpy.polynomial.laguerre.Laguerre(coef, domain=None, window=None)[source]

A Laguerre series class. The Laguerre class provides the standard Python numerical methods ‘+’, ‘-’, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the attributes and methods listed in the ABCPolyBase documentation.  Parameters

coefarray_like

Laguerre coefficients in order of increasing degree, i.e, (1, 2, 3) gives 1*L_0(x) + 2*L_1(X) + 3*L_2(x).
domain(2,) array_like, optional

Domain to use. The interval [domain[0], domain[1]] is mapped to the interval [window[0], window[1]] by shifting and scaling. The default value is [0, 1].
window(2,) array_like, optional

Window, see domain for its use. The default value is [0, 1].  New in version 1.6.0.      Methods
__call__(arg) Call self as a function.
basis(deg[, domain, window]) Series basis polynomial of degree deg.
cast(series[, domain, window]) Convert series to series of this class.
convert([domain, kind, window]) Convert series to a different kind and/or domain and/or window.
copy() Return a copy.
cutdeg(deg) Truncate series to the given degree.
degree() The degree of the series.
deriv([m]) Differentiate.
fit(x, y, deg[, domain, rcond, full, w, window]) Least squares fit to data.
fromroots(roots[, domain, window]) Return series instance that has the specified roots.
has_samecoef(other) Check if coefficients match.
has_samedomain(other) Check if domains match.
has_sametype(other) Check if types match.
has_samewindow(other) Check if windows match.
identity([domain, window]) Identity function.
integ([m, k, lbnd]) Integrate.
linspace([n, domain]) Return x, y values at equally spaced points in domain.
mapparms() Return the mapping parameters.
roots() Return the roots of the series polynomial.
trim([tol]) Remove trailing coefficients
truncate(size) Truncate series to length size.


numpy.polynomial.legendre.Legendre   class numpy.polynomial.legendre.Legendre(coef, domain=None, window=None)[source]

A Legendre series class. The Legendre class provides the standard Python numerical methods ‘+’, ‘-’, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the attributes and methods listed in the ABCPolyBase documentation.  Parameters

coefarray_like

Legendre coefficients in order of increasing degree, i.e., (1, 2, 3) gives 1*P_0(x) + 2*P_1(x) + 3*P_2(x).
domain(2,) array_like, optional

Domain to use. The interval [domain[0], domain[1]] is mapped to the interval [window[0], window[1]] by shifting and scaling. The default value is [-1, 1].
window(2,) array_like, optional

Window, see domain for its use. The default value is [-1, 1].  New in version 1.6.0.      Methods
__call__(arg) Call self as a function.
basis(deg[, domain, window]) Series basis polynomial of degree deg.
cast(series[, domain, window]) Convert series to series of this class.
convert([domain, kind, window]) Convert series to a different kind and/or domain and/or window.
copy() Return a copy.
cutdeg(deg) Truncate series to the given degree.
degree() The degree of the series.
deriv([m]) Differentiate.
fit(x, y, deg[, domain, rcond, full, w, window]) Least squares fit to data.
fromroots(roots[, domain, window]) Return series instance that has the specified roots.
has_samecoef(other) Check if coefficients match.
has_samedomain(other) Check if domains match.
has_sametype(other) Check if types match.
has_samewindow(other) Check if windows match.
identity([domain, window]) Identity function.
integ([m, k, lbnd]) Integrate.
linspace([n, domain]) Return x, y values at equally spaced points in domain.
mapparms() Return the mapping parameters.
roots() Return the roots of the series polynomial.
trim([tol]) Remove trailing coefficients
truncate(size) Truncate series to length size.


numpy.polynomial.polynomial.Polynomial   class numpy.polynomial.polynomial.Polynomial(coef, domain=None, window=None)[source]

A power series class. The Polynomial class provides the standard Python numerical methods ‘+’, ‘-’, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the attributes and methods listed in the ABCPolyBase documentation.  Parameters

coefarray_like

Polynomial coefficients in order of increasing degree, i.e., (1, 2, 3) give 1 + 2*x + 3*x**2.
domain(2,) array_like, optional

Domain to use. The interval [domain[0], domain[1]] is mapped to the interval [window[0], window[1]] by shifting and scaling. The default value is [-1, 1].
window(2,) array_like, optional

Window, see domain for its use. The default value is [-1, 1].  New in version 1.6.0.     Attributes
 basis_name
   Methods
__call__(arg) Call self as a function.
basis(deg[, domain, window]) Series basis polynomial of degree deg.
cast(series[, domain, window]) Convert series to series of this class.
convert([domain, kind, window]) Convert series to a different kind and/or domain and/or window.
copy() Return a copy.
cutdeg(deg) Truncate series to the given degree.
degree() The degree of the series.
deriv([m]) Differentiate.
fit(x, y, deg[, domain, rcond, full, w, window]) Least squares fit to data.
fromroots(roots[, domain, window]) Return series instance that has the specified roots.
has_samecoef(other) Check if coefficients match.
has_samedomain(other) Check if domains match.
has_sametype(other) Check if types match.
has_samewindow(other) Check if windows match.
identity([domain, window]) Identity function.
integ([m, k, lbnd]) Integrate.
linspace([n, domain]) Return x, y values at equally spaced points in domain.
mapparms() Return the mapping parameters.
roots() Return the roots of the series polynomial.
trim([tol]) Remove trailing coefficients
truncate(size) Truncate series to length size.


numpy.polysub   numpy.polysub(a1, a2)[source]

Difference (subtraction) of two polynomials.  Note This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.  Given two polynomials a1 and a2, returns a1 - a2. a1 and a2 can be either array_like sequences of the polynomials’ coefficients (including coefficients equal to zero), or poly1d objects.  Parameters

a1, a2array_like or poly1d

Minuend and subtrahend polynomials, respectively.    Returns

outndarray or poly1d

Array or poly1d object of the difference polynomial’s coefficients.      See also
polyval, polydiv, polymul, polyadd

  Examples  \[(2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2)\] >>> np.polysub([2, 10, -2], [3, 10, -4])
array([-1,  0,  2])


numpy.polyval   numpy.polyval(p, x)[source]

Evaluate a polynomial at specific values.  Note This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.  If p is of length N, this function returns the value: p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1] If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite polynomial p(x(t)) is returned.  Parameters

parray_like or poly1d object

1D array of polynomial coefficients (including coefficients equal to zero) from highest degree to the constant term, or an instance of poly1d.
xarray_like or poly1d object

A number, an array of numbers, or an instance of poly1d, at which to evaluate p.    Returns

valuesndarray or poly1d

If x is a poly1d instance, the result is the composition of the two polynomials, i.e., x is “substituted” in p and the simplified result is returned. In addition, the type of x - array_like or poly1d - governs the type of the output: x array_like => values array_like, x a poly1d object => values is also.      See also  poly1d

A polynomial class.    Notes Horner’s scheme [1] is used to evaluate the polynomial. Even so, for polynomials of high degree the values may be inaccurate due to rounding errors. Use carefully. If x is a subtype of ndarray the return value will be of the same type. References  1
I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng. trans. Ed.), Handbook of Mathematics, New York, Van Nostrand Reinhold Co., 1985, pg. 720.   Examples >>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
76
>>> np.polyval([3,0,1], np.poly1d(5))
poly1d([76])
>>> np.polyval(np.poly1d([3,0,1]), 5)
76
>>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
poly1d([76])


numpy.positive   numpy.positive(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'positive'>

Numerical positive, element-wise.  New in version 1.13.0.   Parameters

xarray_like or scalar

Input array.    Returns

yndarray or scalar

Returned array or scalar: y = +x. This is a scalar if x is a scalar.     Notes Equivalent to x.copy(), but only defined for types that support arithmetic. Examples >>> x1 = np.array(([1., -1.]))
>>> np.positive(x1)
array([ 1., -1.])
 The unary + operator can be used as a shorthand for np.positive on ndarrays. >>> x1 = np.array(([1., -1.]))
>>> +x1
array([ 1., -1.])


numpy.power   numpy.power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'power'>

First array elements raised to powers from second array, element-wise. Raise each base in x1 to the positionally-corresponding power in x2. x1 and x2 must be broadcastable to the same shape. An integer type raised to a negative integer power will raise a ValueError. Negative values raised to a non-integral value will return nan. To get complex results, cast the input to complex, or specify the dtype to be complex (see the example below).  Parameters

x1array_like

The bases.
x2array_like

The exponents. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

yndarray

The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.      See also  float_power

power function that promotes integers to float    Examples Cube each element in an array. >>> x1 = np.arange(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([  0,   1,   8,  27,  64, 125])
 Raise the bases to different exponents. >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])
 The effect of broadcasting. >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
       [ 0,  1,  8, 27, 16,  5]])
 The ** operator can be used as a shorthand for np.power on ndarrays. >>> x2 = np.array([1, 2, 3, 3, 2, 1])
>>> x1 = np.arange(6)
>>> x1 ** x2
array([ 0,  1,  8, 27, 16,  5])
 Negative values raised to a non-integral value will result in nan (and a warning will be generated). >>> x3 = np.array([-1.0, -4.0])
>>> with np.errstate(invalid='ignore'):
...     p = np.power(x3, 1.5)
...
>>> p
array([nan, nan])
 To get complex results, give the argument dtype=complex. >>> np.power(x3, 1.5, dtype=complex)
array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])


numpy.printoptions   numpy.printoptions(*args, **kwargs)[source]

Context manager for setting print options. Set print options for the scope of the with block, and restore the old options at the end. See set_printoptions for the full description of available options.  See also
set_printoptions, get_printoptions

  Examples >>> from numpy.testing import assert_equal
>>> with np.printoptions(precision=2):
...     np.array([2.0]) / 3
array([0.67])
 The as-clause of the with-statement gives the current print options: >>> with np.printoptions(precision=2) as opts:
...      assert_equal(opts, np.get_printoptions())


numpy.prod   numpy.prod(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]

Return the product of array elements over a given axis.  Parameters

aarray_like

Input data.
axisNone or int or tuple of ints, optional

Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.  New in version 1.7.0.  If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
dtypedtype, optional

The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
outndarray, optional

Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the prod method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
initialscalar, optional

The starting value for this product. See reduce for details.  New in version 1.15.0.
wherearray_like of bool, optional

Elements to include in the product. See reduce for details.  New in version 1.17.0.     Returns

product_along_axisndarray, see dtype parameter above.

An array shaped as a but with the specified axis removed. Returns a reference to out if specified.      See also  ndarray.prod

equivalent method  Output type determination
  Notes Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit platform: >>> x = np.array([536870910, 536870910, 536870910, 536870910])
>>> np.prod(x)
16 # may vary
 The product of an empty array is the neutral element 1: >>> np.prod([])
1.0
 Examples By default, calculate the product of all elements: >>> np.prod([1.,2.])
2.0
 Even when the input array is two-dimensional: >>> np.prod([[1.,2.],[3.,4.]])
24.0
 But we can also specify the axis over which to multiply: >>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([  2.,  12.])
 Or select specific elements to include: >>> np.prod([1., np.nan, 3.], where=[True, False, True])
3.0
 If the type of x is unsigned, then the output type is the unsigned platform integer: >>> x = np.array([1, 2, 3], dtype=np.uint8)
>>> np.prod(x).dtype == np.uint
True
 If x is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8)
>>> np.prod(x).dtype == int
True
 You can also start the product with a value other than one: >>> np.prod([1, 2], initial=5)
10


numpy.promote_types   numpy.promote_types(type1, type2)

Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 may be safely cast. The returned data type is always in native byte order. This function is symmetric, but rarely associative.  Parameters

type1dtype or dtype specifier

First data type.
type2dtype or dtype specifier

Second data type.    Returns

outdtype

The promoted data type.      See also
result_type, dtype, can_cast

  Notes  New in version 1.6.0.  Starting in NumPy 1.9, promote_types function now returns a valid string length when given an integer or float dtype as one argument and a string dtype as another argument. Previously it always returned the input string dtype, even if it wasn’t long enough to store the max integer/float value converted to a string. Examples >>> np.promote_types('f4', 'f8')
dtype('float64')
 >>> np.promote_types('i8', 'f4')
dtype('float64')
 >>> np.promote_types('>i8', '<c8')
dtype('complex128')
 >>> np.promote_types('i4', 'S8')
dtype('S11')
 An example of a non-associative case: >>> p = np.promote_types
>>> p('S', p('i1', 'u1'))
dtype('S6')
>>> p(p('S', 'i1'), 'u1')
dtype('S4')


numpy.ptp   numpy.ptp(a, axis=None, out=None, keepdims=<no value>)[source]

Range of values (maximum - minimum) along an axis. The name of the function comes from the acronym for ‘peak to peak’.  Warning ptp preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. np.int8, np.int16, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than 2**(n-1)-1 will be returned as negative values. An example with a work-around is shown below.   Parameters

aarray_like

Input values.
axisNone or int or tuple of ints, optional

Axis along which to find the peaks. By default, flatten the array. axis may be negative, in which case it counts from the last to the first axis.  New in version 1.15.0.  If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.
outarray_like

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type of the output values will be cast if necessary.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the ptp method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.    Returns

ptpndarray

A new array holding the result, unless out was specified, in which case a reference to out is returned.     Examples >>> x = np.array([[4, 9, 2, 10],
...               [6, 9, 7, 12]])
 >>> np.ptp(x, axis=1)
array([8, 6])
 >>> np.ptp(x, axis=0)
array([2, 0, 5, 2])
 >>> np.ptp(x)
10
 This example shows that a negative value can be returned when the input is an array of signed integers. >>> y = np.array([[1, 127],
...               [0, 127],
...               [-1, 127],
...               [-2, 127]], dtype=np.int8)
>>> np.ptp(y, axis=1)
array([ 126,  127, -128, -127], dtype=int8)
 A work-around is to use the view() method to view the result as unsigned integers with the same bit width: >>> np.ptp(y, axis=1).view(np.uint8)
array([126, 127, 128, 129], dtype=uint8)


numpy.put   numpy.put(a, ind, v, mode='raise')[source]

Replaces specified elements of an array with given values. The indexing works on the flattened target array. put is roughly equivalent to: a.flat[ind] = v
  Parameters

andarray

Target array.
indarray_like

Target indices, interpreted as integers.
varray_like

Values to place in a at target indices. If v is shorter than ind it will be repeated as necessary.
mode{‘raise’, ‘wrap’, ‘clip’}, optional

Specifies how out-of-bounds indices will behave.  ‘raise’ – raise an error (default) ‘wrap’ – wrap around ‘clip’ – clip to the range  ‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. In ‘raise’ mode, if an exception occurs the target array may still be modified.      See also
putmask, place

put_along_axis

Put elements by matching the array and the index arrays    Examples >>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44,   1, -55,   3,   4])
 >>> a = np.arange(5)
>>> np.put(a, 22, -5, mode='clip')
>>> a
array([ 0,  1,  2,  3, -5])


numpy.put_along_axis   numpy.put_along_axis(arr, indices, values, axis)[source]

Put values into the destination array by matching 1d index and data slices. This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to place values into the latter. These slices can be different lengths. Functions returning an index along an axis, like argsort and argpartition, produce suitable indices for this function.  New in version 1.15.0.   Parameters

arrndarray (Ni…, M, Nk…)

Destination array.
indicesndarray (Ni…, J, Nk…)

Indices to change along each 1d slice of arr. This must match the dimension of arr, but dimensions in Ni and Nj may be 1 to broadcast against arr.
valuesarray_like (Ni…, J, Nk…)

values to insert at those indices. Its shape and dimension are broadcast to match that of indices.
axisint

The axis to take 1d slices along. If axis is None, the destination array is treated as if a flattened 1d view had been created of it.      See also  take_along_axis

Take values from the input array by matching 1d index and data slices    Notes This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii and kk to a tuple of indices: Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
J = indices.shape[axis]  # Need not equal M

for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        a_1d       = a      [ii + s_[:,] + kk]
        indices_1d = indices[ii + s_[:,] + kk]
        values_1d  = values [ii + s_[:,] + kk]
        for j in range(J):
            a_1d[indices_1d[j]] = values_1d[j]
 Equivalently, eliminating the inner loop, the last two lines would be: a_1d[indices_1d] = values_1d
 Examples For this sample array >>> a = np.array([[10, 30, 20], [60, 40, 50]])
 We can replace the maximum values with: >>> ai = np.expand_dims(np.argmax(a, axis=1), axis=1)
>>> ai
array([[1],
       [0]])
>>> np.put_along_axis(a, ai, 99, axis=1)
>>> a
array([[10, 99, 20],
       [99, 40, 50]])


numpy.putmask   numpy.putmask(a, mask, values)

Changes elements of an array based on conditional and input values. Sets a.flat[n] = values[n] for each n where mask.flat[n]==True. If values is not the same size as a and mask then it will repeat. This gives behavior different from a[mask] = values.  Parameters

andarray

Target array.
maskarray_like

Boolean mask array. It has to be the same shape as a.
valuesarray_like

Values to put into a where mask is True. If values is smaller than a it will be repeated.      See also
place, put, take, copyto

  Examples >>> x = np.arange(6).reshape(2, 3)
>>> np.putmask(x, x>2, x**2)
>>> x
array([[ 0,  1,  2],
       [ 9, 16, 25]])
 If values is smaller than a it is repeated: >>> x = np.arange(5)
>>> np.putmask(x, x>1, [-33, -44])
>>> x
array([  0,   1, -33, -44, -33])


numpy.PZERO

IEEE 754 floating point representation of positive zero. Returns  yfloat

A floating point representation of positive zero.   See Also NZERO : Defines negative zero. isinf : Shows which elements are positive or negative infinity. isposinf : Shows which elements are positive infinity. isneginf : Shows which elements are negative infinity. isnan : Shows which elements are Not a Number.  isfiniteShows which elements are finite - not one of

Not a Number, positive infinity and negative infinity.   Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Positive zero is considered to be a finite number. Examples >>> np.PZERO
0.0
>>> np.NZERO
-0.0
 >>> np.isfinite([np.PZERO])
array([ True])
>>> np.isnan([np.PZERO])
array([False])
>>> np.isinf([np.PZERO])
array([False])


numpy.quantile   numpy.quantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, interpolation=None)[source]

Compute the q-th quantile of the data along the specified axis.  New in version 1.15.0.   Parameters

aarray_like

Input array or object that can be converted to an array.
qarray_like of float

Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive.
axis{int, tuple of int, None}, optional

Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array.
outndarray, optional

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.
overwrite_inputbool, optional

If True, then allow the input array a to be modified by intermediate calculations, to save memory. In this case, the contents of the input a after this function completes is undefined.
methodstr, optional

This parameter specifies the method to use for estimating the quantile. There are many different methods, some unique to NumPy. See the notes for explanation. The options sorted by their R type as summarized in the H&F paper [1] are:  ‘inverted_cdf’ ‘averaged_inverted_cdf’ ‘closest_observation’ ‘interpolated_inverted_cdf’ ‘hazen’ ‘weibull’ ‘linear’ (default) ‘median_unbiased’ ‘normal_unbiased’  The first three methods are discontiuous. NumPy further defines the following discontinuous variations of the default ‘linear’ (7.) option:  ‘lower’ ‘higher’, ‘midpoint’ ‘nearest’   Changed in version 1.22.0: This argument was previously called “interpolation” and only offered the “linear” default and last four options.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.
interpolationstr, optional

Deprecated name for the method keyword argument.  Deprecated since version 1.22.0.     Returns

quantilescalar or ndarray

If q is a single quantile and axis=None, then the result is a scalar. If multiple quantiles are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.      See also  mean
percentile

equivalent to quantile, but with q in the range [0, 100].  median

equivalent to quantile(..., 0.5)  nanquantile
  Notes Given a vector V of length N, the q-th quantile of V is the value q of the way from the minimum to the maximum in a sorted copy of V. The values and distances of the two nearest neighbors as well as the method parameter will determine the quantile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=0.5, the same as the minimum if q=0.0 and the same as the maximum if q=1.0. This optional method parameter specifies the method to use when the desired quantile lies between two data points i < j. If g is the fractional part of the index surrounded by i and alpha and beta are correction constants modifying i and j.  \[i + g = (q - alpha) / ( n - alpha - beta + 1 )\] The different methods then work as follows  inverted_cdf:

method 1 of H&F [1]. This method gives discontinuous results: * if g > 0 ; then take j * if g = 0 ; then take i  averaged_inverted_cdf:

method 2 of H&F [1]. This method give discontinuous results: * if g > 0 ; then take j * if g = 0 ; then average between bounds  closest_observation:

method 3 of H&F [1]. This method give discontinuous results: * if g > 0 ; then take j * if g = 0 and index is odd ; then take j * if g = 0 and index is even ; then take i  interpolated_inverted_cdf:

method 4 of H&F [1]. This method give continuous results using: * alpha = 0 * beta = 1  hazen:

method 5 of H&F [1]. This method give continuous results using: * alpha = 1/2 * beta = 1/2  weibull:

method 6 of H&F [1]. This method give continuous results using: * alpha = 0 * beta = 0  linear:

method 7 of H&F [1]. This method give continuous results using: * alpha = 1 * beta = 1  median_unbiased:

method 8 of H&F [1]. This method is probably the best method if the sample distribution function is unknown (see reference). This method give continuous results using: * alpha = 1/3 * beta = 1/3  normal_unbiased:

method 9 of H&F [1]. This method is probably the best method if the sample distribution function is known to be normal. This method give continuous results using: * alpha = 3/8 * beta = 3/8  lower:

NumPy method kept for backwards compatibility. Takes i as the interpolation point.  higher:

NumPy method kept for backwards compatibility. Takes j as the interpolation point.  nearest:

NumPy method kept for backwards compatibility. Takes i or j, whichever is nearest.  midpoint:

NumPy method kept for backwards compatibility. Uses (i + j) / 2.   References
1(1,2,3,4,5,6,7,8,9,10)

R. J. Hyndman and Y. Fan, “Sample quantiles in statistical packages,” The American Statistician, 50(4), pp. 361-365, 1996   Examples >>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10,  7,  4],
       [ 3,  2,  1]])
>>> np.quantile(a, 0.5)
3.5
>>> np.quantile(a, 0.5, axis=0)
array([6.5, 4.5, 2.5])
>>> np.quantile(a, 0.5, axis=1)
array([7.,  2.])
>>> np.quantile(a, 0.5, axis=1, keepdims=True)
array([[7.],
       [2.]])
>>> m = np.quantile(a, 0.5, axis=0)
>>> out = np.zeros_like(m)
>>> np.quantile(a, 0.5, axis=0, out=out)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])
>>> b = a.copy()
>>> np.quantile(b, 0.5, axis=1, overwrite_input=True)
array([7.,  2.])
>>> assert not np.all(a == b)
 See also numpy.percentile for a visualization of most methods.


numpy.r_   numpy.r_ = <numpy.lib.index_tricks.RClass object>

Translates slice objects to concatenation along the first axis. This is a simple way to build up arrays quickly. There are two use cases.  If the index expression contains comma separated arrays, then stack them along their first axis. If the index expression contains slice notation or scalars then create a 1-D array with a range indicated by the slice notation.  If slice notation is used, the syntax start:stop:step is equivalent to np.arange(start, stop, step) inside of the brackets. However, if step is an imaginary number (i.e. 100j) then its integer portion is interpreted as a number-of-points desired and the start and stop are inclusive. In other words start:stop:stepj is interpreted as np.linspace(start, stop, step, endpoint=1) inside of the brackets. After expansion of slice notation, all comma separated sequences are concatenated together. Optional character strings placed as the first element of the index expression can be used to change the output. The strings ‘r’ or ‘c’ result in matrix output. If the result is 1-D and ‘r’ is specified a 1 x N (row) matrix is produced. If the result is 1-D and ‘c’ is specified, then a N x 1 (column) matrix is produced. If the result is 2-D then both provide the same matrix result. A string integer specifies which axis to stack multiple comma separated arrays along. A string of two comma-separated integers allows indication of the minimum number of dimensions to force each entry into as the second integer (the axis to concatenate along is still the first integer). A string with three comma-separated integers allows specification of the axis to concatenate along, the minimum number of dimensions to force the entries to, and which axis should contain the start of the arrays which are less than the specified number of dimensions. In other words the third integer allows you to specify where the 1’s should be placed in the shape of the arrays that have their shapes upgraded. By default, they are placed in the front of the shape tuple. The third argument allows you to specify where the start of the array should be instead. Thus, a third argument of ‘0’ would place the 1’s at the end of the array shape. Negative integers specify where in the new shape tuple the last dimension of upgraded arrays should be placed, so the default is ‘-1’.  Parameters
 Not a function, so takes no parameters
  Returns
 A concatenated ndarray or matrix.
    See also  concatenate

Join a sequence of arrays along an existing axis.  c_

Translates slice objects to concatenation along the second axis.    Examples >>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])]
array([1, 2, 3, ..., 4, 5, 6])
>>> np.r_[-1:1:6j, [0]*3, 5, 6]
array([-1. , -0.6, -0.2,  0.2,  0.6,  1. ,  0. ,  0. ,  0. ,  5. ,  6. ])
 String integers specify the axis to concatenate along or the minimum number of dimensions to force entries into. >>> a = np.array([[0, 1, 2], [3, 4, 5]])
>>> np.r_['-1', a, a] # concatenate along last axis
array([[0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5]])
>>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2
array([[1, 2, 3],
       [4, 5, 6]])
 >>> np.r_['0,2,0', [1,2,3], [4,5,6]]
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
>>> np.r_['1,2,0', [1,2,3], [4,5,6]]
array([[1, 4],
       [2, 5],
       [3, 6]])
 Using ‘r’ or ‘c’ as a first string argument creates a matrix. >>> np.r_['r',[1,2,3], [4,5,6]]
matrix([[1, 2, 3, 4, 5, 6]])


numpy.rad2deg   numpy.rad2deg(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'rad2deg'>

Convert angles from radians to degrees.  Parameters

xarray_like

Angle in radians.
outndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

yndarray

The corresponding angle in degrees. This is a scalar if x is a scalar.      See also  deg2rad

Convert angles from degrees to radians.  unwrap

Remove large jumps in angle by wrapping.    Notes  New in version 1.3.0.  rad2deg(x) is 180 * x / pi. Examples >>> np.rad2deg(np.pi/2)
90.0


numpy.radians   numpy.radians(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'radians'>

Convert angles from degrees to radians.  Parameters

xarray_like

Input array in degrees.
outndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

yndarray

The corresponding radian values. This is a scalar if x is a scalar.      See also  deg2rad

equivalent function    Examples Convert a degree array to radians >>> deg = np.arange(12.) * 30.
>>> np.radians(deg)
array([ 0.        ,  0.52359878,  1.04719755,  1.57079633,  2.0943951 ,
        2.61799388,  3.14159265,  3.66519143,  4.1887902 ,  4.71238898,
        5.23598776,  5.75958653])
 >>> out = np.zeros((deg.shape))
>>> ret = np.radians(deg, out)
>>> ret is out
True


numpy.random.BitGenerator   class numpy.random.BitGenerator(seed=None)

Base Class for generic BitGenerators, which provide a stream of random bits based on different algorithms. Must be overridden.  Parameters

seed{None, int, array_like[ints], SeedSequence}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to ~`numpy.random.SeedSequence` to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.      See also  SeedSequence
   Attributes

lockthreading.Lock

Lock instance that is shared so that the same BitGenerator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock.     Methods
random_raw(self[, size]) Return randoms as generated by the underlying BitGenerator


Random Generator The Generator provides access to a wide range of distributions, and served as a replacement for RandomState. The main difference between the two is that Generator relies on an additional BitGenerator to manage state and generate the random bits, which are then transformed into random values from useful distributions. The default BitGenerator used by Generator is PCG64. The BitGenerator can be changed by passing an instantized BitGenerator to Generator.   numpy.random.default_rng()

Construct a new Generator with the default BitGenerator (PCG64).  Parameters

seed{None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Additionally, when passed a BitGenerator, it will be wrapped by Generator. If passed a Generator, it will be returned unaltered.    Returns
 Generator

The initialized generator object.     Notes If seed is not a BitGenerator or a Generator, a new BitGenerator is instantiated. This function does not manage a default global instance. Examples default_rng is the recommended constructor for the random number class Generator. Here are several ways we can construct a random number generator using default_rng and the Generator class. Here we use default_rng to generate a random float: >>> import numpy as np
>>> rng = np.random.default_rng(12345)
>>> print(rng)
Generator(PCG64)
>>> rfloat = rng.random()
>>> rfloat
0.22733602246716966
>>> type(rfloat)
<class 'float'>
 Here we use default_rng to generate 3 random integers between 0 (inclusive) and 10 (exclusive): >>> import numpy as np
>>> rng = np.random.default_rng(12345)
>>> rints = rng.integers(low=0, high=10, size=3)
>>> rints
array([6, 2, 7])
>>> type(rints[0])
<class 'numpy.int64'>
 Here we specify a seed so that we have reproducible results: >>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> print(rng)
Generator(PCG64)
>>> arr1 = rng.random((3, 3))
>>> arr1
array([[0.77395605, 0.43887844, 0.85859792],
       [0.69736803, 0.09417735, 0.97562235],
       [0.7611397 , 0.78606431, 0.12811363]])
 If we exit and restart our Python interpreter, we’ll see that we generate the same random numbers again: >>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> arr2 = rng.random((3, 3))
>>> arr2
array([[0.77395605, 0.43887844, 0.85859792],
       [0.69736803, 0.09417735, 0.97562235],
       [0.7611397 , 0.78606431, 0.12811363]])

   class numpy.random.Generator(bit_generator)

Container for the BitGenerators. Generator exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned. The function numpy.random.default_rng will instantiate a Generator with numpy’s default BitGenerator. No Compatibility Guarantee Generator does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change.  Parameters

bit_generatorBitGenerator

BitGenerator to use as the core generator.      See also  default_rng

Recommended constructor for Generator.    Notes The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator. It uses Mersenne Twister, and this bit generator can be accessed using MT19937. Generator, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from. Examples >>> from numpy.random import Generator, PCG64
>>> rng = Generator(PCG64())
>>> rng.standard_normal()
-0.203  # random

  Accessing the BitGenerator
bit_generator Gets the bit generator instance used by the generator     Simple random data
integers(low[, high, size, dtype, endpoint]) Return random integers from low (inclusive) to high (exclusive), or if endpoint=True, low (inclusive) to high (inclusive).
random([size, dtype, out]) Return random floats in the half-open interval [0.0, 1.0).
choice(a[, size, replace, p, axis, shuffle]) Generates a random sample from a given array
bytes(length) Return random bytes.     Permutations The methods for randomly permuting a sequence are
shuffle(x[, axis]) Modify an array or sequence in-place by shuffling its contents.
permutation(x[, axis]) Randomly permute a sequence, or return a permuted range.
permuted(x[, axis, out]) Randomly permute x along axis axis.   The following table summarizes the behaviors of the methods.
method copy/in-place axis handling
shuffle in-place as if 1d
permutation copy as if 1d
permuted either (use ‘out’ for in-place) axis independent   The following subsections provide more details about the differences.  In-place vs. copy The main difference between Generator.shuffle and Generator.permutation is that Generator.shuffle operates in-place, while Generator.permutation returns a copy. By default, Generator.permuted returns a copy. To operate in-place with Generator.permuted, pass the same array as the first argument and as the value of the out parameter. For example, >>> rng = np.random.default_rng()
>>> x = np.arange(0, 15).reshape(3, 5)
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> y = rng.permuted(x, axis=1, out=x)
>>> x
array([[ 1,  0,  2,  4,  3],  # random
       [ 6,  7,  8,  9,  5],
       [10, 14, 11, 13, 12]])
 Note that when out is given, the return value is out: >>> y is x
True
   Handling the axis parameter An important distinction for these methods is how they handle the axis parameter. Both Generator.shuffle and Generator.permutation treat the input as a one-dimensional sequence, and the axis parameter determines which dimension of the input array to use as the sequence. In the case of a two-dimensional array, axis=0 will, in effect, rearrange the rows of the array, and axis=1 will rearrange the columns. For example >>> rng = np.random.default_rng()
>>> x = np.arange(0, 15).reshape(3, 5)
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> rng.permutation(x, axis=1)
array([[ 1,  3,  2,  0,  4],  # random
       [ 6,  8,  7,  5,  9],
       [11, 13, 12, 10, 14]])
 Note that the columns have been rearranged “in bulk”: the values within each column have not changed. The method Generator.permuted treats the axis parameter similar to how numpy.sort treats it. Each slice along the given axis is shuffled independently of the others. Compare the following example of the use of Generator.permuted to the above example of Generator.permutation: >>> rng.permuted(x, axis=1)
array([[ 1,  0,  2,  4,  3],  # random
       [ 5,  7,  6,  9,  8],
       [10, 14, 12, 13, 11]])
 In this example, the values within each row (i.e. the values along axis=1) have been shuffled independently. This is not a “bulk” shuffle of the columns.   Shuffling non-NumPy sequences Generator.shuffle works on non-NumPy sequences. That is, if it is given a sequence that is not a NumPy array, it shuffles that sequence in-place. For example, >>> rng = np.random.default_rng()
>>> a = ['A', 'B', 'C', 'D', 'E']
>>> rng.shuffle(a)  # shuffle the list in-place
>>> a
['B', 'D', 'A', 'E', 'C']  # random
    Distributions
beta(a, b[, size]) Draw samples from a Beta distribution.
binomial(n, p[, size]) Draw samples from a binomial distribution.
chisquare(df[, size]) Draw samples from a chi-square distribution.
dirichlet(alpha[, size]) Draw samples from the Dirichlet distribution.
exponential([scale, size]) Draw samples from an exponential distribution.
f(dfnum, dfden[, size]) Draw samples from an F distribution.
gamma(shape[, scale, size]) Draw samples from a Gamma distribution.
geometric(p[, size]) Draw samples from the geometric distribution.
gumbel([loc, scale, size]) Draw samples from a Gumbel distribution.
hypergeometric(ngood, nbad, nsample[, size]) Draw samples from a Hypergeometric distribution.
laplace([loc, scale, size]) Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).
logistic([loc, scale, size]) Draw samples from a logistic distribution.
lognormal([mean, sigma, size]) Draw samples from a log-normal distribution.
logseries(p[, size]) Draw samples from a logarithmic series distribution.
multinomial(n, pvals[, size]) Draw samples from a multinomial distribution.
multivariate_hypergeometric(colors, nsample) Generate variates from a multivariate hypergeometric distribution.
multivariate_normal(mean, cov[, size, ...]) Draw random samples from a multivariate normal distribution.
negative_binomial(n, p[, size]) Draw samples from a negative binomial distribution.
noncentral_chisquare(df, nonc[, size]) Draw samples from a noncentral chi-square distribution.
noncentral_f(dfnum, dfden, nonc[, size]) Draw samples from the noncentral F distribution.
normal([loc, scale, size]) Draw random samples from a normal (Gaussian) distribution.
pareto(a[, size]) Draw samples from a Pareto II or Lomax distribution with specified shape.
poisson([lam, size]) Draw samples from a Poisson distribution.
power(a[, size]) Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
rayleigh([scale, size]) Draw samples from a Rayleigh distribution.
standard_cauchy([size]) Draw samples from a standard Cauchy distribution with mode = 0.
standard_exponential([size, dtype, method, out]) Draw samples from the standard exponential distribution.
standard_gamma(shape[, size, dtype, out]) Draw samples from a standard Gamma distribution.
standard_normal([size, dtype, out]) Draw samples from a standard Normal distribution (mean=0, stdev=1).
standard_t(df[, size]) Draw samples from a standard Student's t distribution with df degrees of freedom.
triangular(left, mode, right[, size]) Draw samples from the triangular distribution over the interval [left, right].
uniform([low, high, size]) Draw samples from a uniform distribution.
vonmises(mu, kappa[, size]) Draw samples from a von Mises distribution.
wald(mean, scale[, size]) Draw samples from a Wald, or inverse Gaussian, distribution.
weibull(a[, size]) Draw samples from a Weibull distribution.
zipf(a[, size]) Draw samples from a Zipf distribution.


class numpy.random.Generator(bit_generator)

Container for the BitGenerators. Generator exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned. The function numpy.random.default_rng will instantiate a Generator with numpy’s default BitGenerator. No Compatibility Guarantee Generator does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change.  Parameters

bit_generatorBitGenerator

BitGenerator to use as the core generator.      See also  default_rng

Recommended constructor for Generator.    Notes The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator. It uses Mersenne Twister, and this bit generator can be accessed using MT19937. Generator, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from. Examples >>> from numpy.random import Generator, PCG64
>>> rng = Generator(PCG64())
>>> rng.standard_normal()
-0.203  # random


Mersenne Twister (MT19937)   class numpy.random.MT19937(seed=None)

Container for the Mersenne Twister pseudo-random number generator.  Parameters

seed{None, int, array_like[ints], SeedSequence}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.     Notes MT19937 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers [1]. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. The Python stdlib module “random” also contains a Mersenne Twister pseudo-random number generator. State and Seeding The MT19937 state vector consists of a 624-element array of 32-bit unsigned integers plus a single integer value between 0 and 624 that indexes the current position within the main array. The input seed is processed by SeedSequence to fill the whole state. The first element is reset such that only its most significant bit is set. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, MT19937, SeedSequence
>>> sg = SeedSequence(1234)
>>> rg = [Generator(MT19937(s)) for s in sg.spawn(10)]
 Another method is to use MT19937.jumped which advances the state as-if \(2^{128}\) random numbers have been generated ([1], [2]). This allows the original sequence to be split so that distinct segments can be used in each worker process. All generators should be chained to ensure that the segments come from the same sequence. >>> from numpy.random import Generator, MT19937, SeedSequence
>>> sg = SeedSequence(1234)
>>> bit_generator = MT19937(sg)
>>> rg = []
>>> for _ in range(10):
...    rg.append(Generator(bit_generator))
...    # Chain the BitGenerators
...    bit_generator = bit_generator.jumped()
 Compatibility Guarantee MT19937 makes a guarantee that a fixed seed and will always produce the same random integer stream. References
1(1,2)

Hiroshi Haramoto, Makoto Matsumoto, and Pierre L’Ecuyer, “A Fast Jump Ahead Algorithm for Linear Recurrences in a Polynomial Space”, Sequences and Their Applications - SETA, 290–298, 2008.  2
Hiroshi Haramoto, Makoto Matsumoto, Takuji Nishimura, François Panneton, Pierre L’Ecuyer, “Efficient Jump Ahead for F2-Linear Random Number Generators”, INFORMS JOURNAL ON COMPUTING, Vol. 20, No. 3, Summer 2008, pp. 385-390.    Attributes
 lock: threading.Lock

Lock instance that is shared so that the same bit git generator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock.
  State
state Get or set the PRNG state     Parallel generation
jumped([jumps]) Returns a new bit generator with the state jumped     Extending
cffi CFFI interface
ctypes ctypes interface


Permuted Congruential Generator (64-bit, PCG64)   class numpy.random.PCG64(seed=None)

BitGenerator for the PCG-64 pseudo-random number generator.  Parameters

seed{None, int, array_like[ints], SeedSequence}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.     Notes PCG-64 is a 128-bit implementation of O’Neill’s permutation congruential generator ([1], [2]). PCG-64 has a period of \(2^{128}\) and supports advancing an arbitrary number of steps as well as \(2^{127}\) streams. The specific member of the PCG family that we use is PCG XSL RR 128/64 as described in the paper ([2]). PCG64 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. Supports the method advance to advance the RNG an arbitrary number of steps. The state of the PCG-64 RNG is represented by 2 128-bit unsigned integers. State and Seeding The PCG64 state vector consists of 2 unsigned 128-bit values, which are represented externally as Python ints. One is the state of the PRNG, which is advanced by a linear congruential generator (LCG). The second is a fixed odd increment used in the LCG. The input seed is processed by SeedSequence to generate both values. The increment is not independently settable. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, PCG64, SeedSequence
>>> sg = SeedSequence(1234)
>>> rg = [Generator(PCG64(s)) for s in sg.spawn(10)]
 Compatibility Guarantee PCG64 makes a guarantee that a fixed seed will always produce the same random integer stream. References  1
“PCG, A Family of Better Random Number Generators”
2(1,2)

O’Neill, Melissa E. “PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation”
  State
state Get or set the PRNG state     Parallel generation
advance(delta) Advance the underlying RNG as-if delta draws have occurred.
jumped([jumps]) Returns a new bit generator with the state jumped.     Extending
cffi CFFI interface
ctypes ctypes interface


Permuted Congruential Generator (64-bit, PCG64 DXSM)   class numpy.random.PCG64DXSM(seed=None)

BitGenerator for the PCG-64 DXSM pseudo-random number generator.  Parameters

seed{None, int, array_like[ints], SeedSequence}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.     Notes PCG-64 DXSM is a 128-bit implementation of O’Neill’s permutation congruential generator ([1], [2]). PCG-64 DXSM has a period of \(2^{128}\) and supports advancing an arbitrary number of steps as well as \(2^{127}\) streams. The specific member of the PCG family that we use is PCG CM DXSM 128/64. It differs from PCG64 in that it uses the stronger DXSM output function, a 64-bit “cheap multiplier” in the LCG, and outputs from the state before advancing it rather than advance-then-output. PCG64DXSM provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. Supports the method advance to advance the RNG an arbitrary number of steps. The state of the PCG-64 DXSM RNG is represented by 2 128-bit unsigned integers. State and Seeding The PCG64DXSM state vector consists of 2 unsigned 128-bit values, which are represented externally as Python ints. One is the state of the PRNG, which is advanced by a linear congruential generator (LCG). The second is a fixed odd increment used in the LCG. The input seed is processed by SeedSequence to generate both values. The increment is not independently settable. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, PCG64DXSM, SeedSequence
>>> sg = SeedSequence(1234)
>>> rg = [Generator(PCG64DXSM(s)) for s in sg.spawn(10)]
 Compatibility Guarantee PCG64DXSM makes a guarantee that a fixed seed will always produce the same random integer stream. References  1
“PCG, A Family of Better Random Number Generators”  2
O’Neill, Melissa E. “PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation”
  State
state Get or set the PRNG state     Parallel generation
advance(delta) Advance the underlying RNG as-if delta draws have occurred.
jumped([jumps]) Returns a new bit generator with the state jumped.     Extending
cffi CFFI interface
ctypes ctypes interface


Philox Counter-based RNG   class numpy.random.Philox(seed=None, counter=None, key=None)

Container for the Philox (4x64) pseudo-random number generator.  Parameters

seed{None, int, array_like[ints], SeedSequence}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.
counter{None, int, array_like}, optional

Counter to use in the Philox state. Can be either a Python int (long in 2.x) in [0, 2**256) or a 4-element uint64 array. If not provided, the RNG is initialized at 0.
key{None, int, array_like}, optional

Key to use in the Philox state. Unlike seed, the value in key is directly set. Can be either a Python int in [0, 2**128) or a 2-element uint64 array. key and seed cannot both be used.     Notes Philox is a 64-bit PRNG that uses a counter-based design based on weaker (and faster) versions of cryptographic functions [1]. Instances using different values of the key produce independent sequences. Philox has a period of \(2^{256} - 1\) and supports arbitrary advancing and jumping the sequence in increments of \(2^{128}\). These features allow multiple non-overlapping sequences to be generated. Philox provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. State and Seeding The Philox state vector consists of a 256-bit value encoded as a 4-element uint64 array and a 128-bit value encoded as a 2-element uint64 array. The former is a counter which is incremented by 1 for every 4 64-bit randoms produced. The second is a key which determined the sequence produced. Using different keys produces independent sequences. The input seed is processed by SeedSequence to generate the key. The counter is set to 0. Alternately, one can omit the seed parameter and set the key and counter directly. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, Philox, SeedSequence
>>> sg = SeedSequence(1234)
>>> rg = [Generator(Philox(s)) for s in sg.spawn(10)]
 Philox can be used in parallel applications by calling the jumped method to advances the state as-if \(2^{128}\) random numbers have been generated. Alternatively, advance can be used to advance the counter for any positive step in [0, 2**256). When using jumped, all generators should be chained to ensure that the segments come from the same sequence. >>> from numpy.random import Generator, Philox
>>> bit_generator = Philox(1234)
>>> rg = []
>>> for _ in range(10):
...    rg.append(Generator(bit_generator))
...    bit_generator = bit_generator.jumped()
 Alternatively, Philox can be used in parallel applications by using a sequence of distinct keys where each instance uses different key. >>> key = 2**96 + 2**33 + 2**17 + 2**9
>>> rg = [Generator(Philox(key=key+i)) for i in range(10)]
 Compatibility Guarantee Philox makes a guarantee that a fixed seed will always produce the same random integer stream. References  1
John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, “Parallel Random Numbers: As Easy as 1, 2, 3,” Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011.   Examples >>> from numpy.random import Generator, Philox
>>> rg = Generator(Philox(1234))
>>> rg.standard_normal()
0.123  # random
  Attributes
 lock: threading.Lock

Lock instance that is shared so that the same bit git generator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock.
  State
state Get or set the PRNG state     Parallel generation
advance(delta) Advance the underlying RNG as-if delta draws have occurred.
jumped([jumps]) Returns a new bit generator with the state jumped     Extending
cffi CFFI interface
ctypes ctypes interface


Legacy Random Generation The RandomState provides access to legacy generators. This generator is considered frozen and will have no further improvements. It is guaranteed to produce the same values as the final point release of NumPy v1.16. These all depend on Box-Muller normals or inverse CDF exponentials or gammas. This class should only be used if it is essential to have randoms that are identical to what would have been produced by previous versions of NumPy. RandomState adds additional information to the state which is required when using Box-Muller normals since these are produced in pairs. It is important to use RandomState.get_state, and not the underlying bit generators state, when accessing the state so that these extra values are saved. Although we provide the MT19937 BitGenerator for use independent of RandomState, note that its default seeding uses SeedSequence rather than the legacy seeding algorithm. RandomState will use the legacy seeding algorithm. The methods to use the legacy seeding algorithm are currently private as the main reason to use them is just to implement RandomState. However, one can reset the state of MT19937 using the state of the RandomState: from numpy.random import MT19937
from numpy.random import RandomState

rs = RandomState(12345)
mt19937 = MT19937()
mt19937.state = rs.get_state()
rs2 = RandomState(mt19937)

# Same output
rs.standard_normal()
rs2.standard_normal()

rs.random()
rs2.random()

rs.standard_exponential()
rs2.standard_exponential()
   class numpy.random.RandomState(seed=None)

Container for the slow Mersenne Twister pseudo-random number generator. Consider using a different BitGenerator with the Generator container instead. RandomState and Generator expose a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned. Compatibility Guarantee A fixed bit generator using a fixed seed and a fixed series of calls to ‘RandomState’ methods using the same parameters will always produce the same results up to roundoff error except when the values were incorrect. RandomState is effectively frozen and will only receive updates that are required by changes in the the internals of Numpy. More substantial changes, including algorithmic improvements, are reserved for Generator.  Parameters

seed{None, int, array_like, BitGenerator}, optional

Random seed used to initialize the pseudo-random number generator or an instantized BitGenerator. If an integer or array, used as a seed for the MT19937 BitGenerator. Values can be any integer between 0 and 2**32 - 1 inclusive, an array (or other sequence) of such integers, or None (the default). If seed is None, then the MT19937 BitGenerator is initialized by reading data from /dev/urandom (or the Windows analogue) if available or seed from the clock otherwise.      See also  Generator
MT19937
numpy.random.BitGenerator
  Notes The Python stdlib module “random” also contains a Mersenne Twister pseudo-random number generator with a number of methods that are similar to the ones available in RandomState. RandomState, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from.
  Seeding and State
get_state() Return a tuple representing the internal state of the generator.
set_state(state) Set the internal state of the generator from a tuple.
seed(self[, seed]) Reseed a legacy MT19937 BitGenerator     Simple random data
rand(d0, d1, ..., dn) Random values in a given shape.
randn(d0, d1, ..., dn) Return a sample (or samples) from the "standard normal" distribution.
randint(low[, high, size, dtype]) Return random integers from low (inclusive) to high (exclusive).
random_integers(low[, high, size]) Random integers of type np.int_ between low and high, inclusive.
random_sample([size]) Return random floats in the half-open interval [0.0, 1.0).
choice(a[, size, replace, p]) Generates a random sample from a given 1-D array
bytes(length) Return random bytes.     Permutations
shuffle(x) Modify a sequence in-place by shuffling its contents.
permutation(x) Randomly permute a sequence, or return a permuted range.     Distributions
beta(a, b[, size]) Draw samples from a Beta distribution.
binomial(n, p[, size]) Draw samples from a binomial distribution.
chisquare(df[, size]) Draw samples from a chi-square distribution.
dirichlet(alpha[, size]) Draw samples from the Dirichlet distribution.
exponential([scale, size]) Draw samples from an exponential distribution.
f(dfnum, dfden[, size]) Draw samples from an F distribution.
gamma(shape[, scale, size]) Draw samples from a Gamma distribution.
geometric(p[, size]) Draw samples from the geometric distribution.
gumbel([loc, scale, size]) Draw samples from a Gumbel distribution.
hypergeometric(ngood, nbad, nsample[, size]) Draw samples from a Hypergeometric distribution.
laplace([loc, scale, size]) Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).
logistic([loc, scale, size]) Draw samples from a logistic distribution.
lognormal([mean, sigma, size]) Draw samples from a log-normal distribution.
logseries(p[, size]) Draw samples from a logarithmic series distribution.
multinomial(n, pvals[, size]) Draw samples from a multinomial distribution.
multivariate_normal(mean, cov[, size, ...]) Draw random samples from a multivariate normal distribution.
negative_binomial(n, p[, size]) Draw samples from a negative binomial distribution.
noncentral_chisquare(df, nonc[, size]) Draw samples from a noncentral chi-square distribution.
noncentral_f(dfnum, dfden, nonc[, size]) Draw samples from the noncentral F distribution.
normal([loc, scale, size]) Draw random samples from a normal (Gaussian) distribution.
pareto(a[, size]) Draw samples from a Pareto II or Lomax distribution with specified shape.
poisson([lam, size]) Draw samples from a Poisson distribution.
power(a[, size]) Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
rayleigh([scale, size]) Draw samples from a Rayleigh distribution.
standard_cauchy([size]) Draw samples from a standard Cauchy distribution with mode = 0.
standard_exponential([size]) Draw samples from the standard exponential distribution.
standard_gamma(shape[, size]) Draw samples from a standard Gamma distribution.
standard_normal([size]) Draw samples from a standard Normal distribution (mean=0, stdev=1).
standard_t(df[, size]) Draw samples from a standard Student's t distribution with df degrees of freedom.
triangular(left, mode, right[, size]) Draw samples from the triangular distribution over the interval [left, right].
uniform([low, high, size]) Draw samples from a uniform distribution.
vonmises(mu, kappa[, size]) Draw samples from a von Mises distribution.
wald(mean, scale[, size]) Draw samples from a Wald, or inverse Gaussian, distribution.
weibull(a[, size]) Draw samples from a Weibull distribution.
zipf(a[, size]) Draw samples from a Zipf distribution.     Functions in numpy.random Many of the RandomState methods above are exported as functions in numpy.random This usage is discouraged, as it is implemented via a global RandomState instance which is not advised on two counts:  It uses global state, which means results will change as the code changes It uses a RandomState rather than the more modern Generator.  For backward compatible legacy reasons, we cannot change this. See Quick Start.
beta(a, b[, size]) Draw samples from a Beta distribution.
binomial(n, p[, size]) Draw samples from a binomial distribution.
bytes(length) Return random bytes.
chisquare(df[, size]) Draw samples from a chi-square distribution.
choice(a[, size, replace, p]) Generates a random sample from a given 1-D array
dirichlet(alpha[, size]) Draw samples from the Dirichlet distribution.
exponential([scale, size]) Draw samples from an exponential distribution.
f(dfnum, dfden[, size]) Draw samples from an F distribution.
gamma(shape[, scale, size]) Draw samples from a Gamma distribution.
geometric(p[, size]) Draw samples from the geometric distribution.
get_state() Return a tuple representing the internal state of the generator.
gumbel([loc, scale, size]) Draw samples from a Gumbel distribution.
hypergeometric(ngood, nbad, nsample[, size]) Draw samples from a Hypergeometric distribution.
laplace([loc, scale, size]) Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).
logistic([loc, scale, size]) Draw samples from a logistic distribution.
lognormal([mean, sigma, size]) Draw samples from a log-normal distribution.
logseries(p[, size]) Draw samples from a logarithmic series distribution.
multinomial(n, pvals[, size]) Draw samples from a multinomial distribution.
multivariate_normal(mean, cov[, size, ...]) Draw random samples from a multivariate normal distribution.
negative_binomial(n, p[, size]) Draw samples from a negative binomial distribution.
noncentral_chisquare(df, nonc[, size]) Draw samples from a noncentral chi-square distribution.
noncentral_f(dfnum, dfden, nonc[, size]) Draw samples from the noncentral F distribution.
normal([loc, scale, size]) Draw random samples from a normal (Gaussian) distribution.
pareto(a[, size]) Draw samples from a Pareto II or Lomax distribution with specified shape.
permutation(x) Randomly permute a sequence, or return a permuted range.
poisson([lam, size]) Draw samples from a Poisson distribution.
power(a[, size]) Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
rand(d0, d1, ..., dn) Random values in a given shape.
randint(low[, high, size, dtype]) Return random integers from low (inclusive) to high (exclusive).
randn(d0, d1, ..., dn) Return a sample (or samples) from the "standard normal" distribution.
random([size]) Return random floats in the half-open interval [0.0, 1.0).
random_integers(low[, high, size]) Random integers of type np.int_ between low and high, inclusive.
random_sample([size]) Return random floats in the half-open interval [0.0, 1.0).
ranf This is an alias of random_sample.
rayleigh([scale, size]) Draw samples from a Rayleigh distribution.
sample This is an alias of random_sample.
seed(self[, seed]) Reseed a legacy MT19937 BitGenerator
set_state(state) Set the internal state of the generator from a tuple.
shuffle(x) Modify a sequence in-place by shuffling its contents.
standard_cauchy([size]) Draw samples from a standard Cauchy distribution with mode = 0.
standard_exponential([size]) Draw samples from the standard exponential distribution.
standard_gamma(shape[, size]) Draw samples from a standard Gamma distribution.
standard_normal([size]) Draw samples from a standard Normal distribution (mean=0, stdev=1).
standard_t(df[, size]) Draw samples from a standard Student's t distribution with df degrees of freedom.
triangular(left, mode, right[, size]) Draw samples from the triangular distribution over the interval [left, right].
uniform([low, high, size]) Draw samples from a uniform distribution.
vonmises(mu, kappa[, size]) Draw samples from a von Mises distribution.
wald(mean, scale[, size]) Draw samples from a Wald, or inverse Gaussian, distribution.
weibull(a[, size]) Draw samples from a Weibull distribution.
zipf(a[, size]) Draw samples from a Zipf distribution.


numpy.random.SeedSequence   class numpy.random.SeedSequence(entropy=None, *, spawn_key=(), pool_size=4)

SeedSequence mixes sources of entropy in a reproducible way to set the initial state for independent and very probably non-overlapping BitGenerators. Once the SeedSequence is instantiated, you can call the generate_state method to get an appropriately sized seed. Calling spawn(n) will create n SeedSequences that can be used to seed independent BitGenerators, i.e. for different threads.  Parameters

entropy{None, int, sequence[int]}, optional

The entropy for creating a SeedSequence.
spawn_key{(), sequence[int]}, optional

A third source of entropy, used internally when calling SeedSequence.spawn
pool_size{int}, optional

Size of the pooled entropy to store. Default is 4 to give a 128-bit entropy pool. 8 (for 256 bits) is another reasonable choice if working with larger PRNGs, but there is very little to be gained by selecting another value.
n_children_spawned{int}, optional

The number of children already spawned. Only pass this if reconstructing a SeedSequence from a serialized form.     Notes Best practice for achieving reproducible bit streams is to use the default None for the initial entropy, and then use SeedSequence.entropy to log/pickle the entropy for reproducibility: >>> sq1 = np.random.SeedSequence()
>>> sq1.entropy
243799254704924441050048792905230269161  # random
>>> sq2 = np.random.SeedSequence(sq1.entropy)
>>> np.all(sq1.generate_state(10) == sq2.generate_state(10))
True
  Attributes
 entropy
n_children_spawned
pool
pool_size
spawn_key
state
   Methods
generate_state(n_words[, dtype]) Return the requested number of words for PRNG seeding.
spawn(n_children) Spawn a number of child SeedSequence s by extending the spawn_key.


SFC64 Small Fast Chaotic PRNG   class numpy.random.SFC64(seed=None)

BitGenerator for Chris Doty-Humphrey’s Small Fast Chaotic PRNG.  Parameters

seed{None, int, array_like[ints], SeedSequence}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.     Notes SFC64 is a 256-bit implementation of Chris Doty-Humphrey’s Small Fast Chaotic PRNG ([1]). SFC64 has a few different cycles that one might be on, depending on the seed; the expected period will be about \(2^{255}\) ([2]). SFC64 incorporates a 64-bit counter which means that the absolute minimum cycle length is \(2^{64}\) and that distinct seeds will not run into each other for at least \(2^{64}\) iterations. SFC64 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. State and Seeding The SFC64 state vector consists of 4 unsigned 64-bit values. The last is a 64-bit counter that increments by 1 each iteration. The input seed is processed by SeedSequence to generate the first 3 values, then the SFC64 algorithm is iterated a small number of times to mix. Compatibility Guarantee SFC64 makes a guarantee that a fixed seed will always produce the same random integer stream. References  1
“PractRand”  2
“Random Invertible Mapping Statistics”
  State
state Get or set the PRNG state     Extending
cffi CFFI interface
ctypes ctypes interface


numpy.RankWarning   exception numpy.RankWarning[source]

Issued by polyfit when the Vandermonde matrix is rank deficient. For more information, a way to suppress the warning, and an example of RankWarning being issued, see polyfit.


numpy.ravel   numpy.ravel(a, order='C')[source]

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned. A copy is made only if needed. As of NumPy 1.10, the returned array will have the same type as the input array. (for example, a masked array will be returned for a masked array input)  Parameters

aarray_like

Input array. The elements in a are read in the order specified by order, and packed as a 1-D array.
order{‘C’,’F’, ‘A’, ‘K’}, optional

The elements of a are read using this index order. ‘C’ means to index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. ‘A’ means to read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used.    Returns

yarray_like

y is an array of the same subtype as a, with shape (a.size,). Note that matrices are special cased for backward compatibility, if a is a matrix, then y is a 1-D ndarray.      See also  ndarray.flat

1-D iterator over an array.  ndarray.flatten

1-D array copy of the elements of an array in row-major order.  ndarray.reshape

Change the shape of an array without changing its data.    Notes In row-major, C-style order, in two dimensions, the row index varies the slowest, and the column index the quickest. This can be generalized to multiple dimensions, where row-major order implies that the index along the first axis varies slowest, and the index along the last quickest. The opposite holds for column-major, Fortran-style index ordering. When a view is desired in as many cases as possible, arr.reshape(-1) may be preferable. Examples It is equivalent to reshape(-1, order=order). >>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.ravel(x)
array([1, 2, 3, 4, 5, 6])
 >>> x.reshape(-1)
array([1, 2, 3, 4, 5, 6])
 >>> np.ravel(x, order='F')
array([1, 4, 2, 5, 3, 6])
 When order is ‘A’, it will preserve the array’s ‘C’ or ‘F’ ordering: >>> np.ravel(x.T)
array([1, 4, 2, 5, 3, 6])
>>> np.ravel(x.T, order='A')
array([1, 2, 3, 4, 5, 6])
 When order is ‘K’, it will preserve orderings that are neither ‘C’ nor ‘F’, but won’t reverse axes: >>> a = np.arange(3)[::-1]; a
array([2, 1, 0])
>>> a.ravel(order='C')
array([2, 1, 0])
>>> a.ravel(order='K')
array([2, 1, 0])
 >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
array([[[ 0,  2,  4],
        [ 1,  3,  5]],
       [[ 6,  8, 10],
        [ 7,  9, 11]]])
>>> a.ravel(order='C')
array([ 0,  2,  4,  1,  3,  5,  6,  8, 10,  7,  9, 11])
>>> a.ravel(order='K')
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])


numpy.ravel_multi_index   numpy.ravel_multi_index(multi_index, dims, mode='raise', order='C')

Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.  Parameters

multi_indextuple of array_like

A tuple of integer arrays, one array for each dimension.
dimstuple of ints

The shape of array into which the indices from multi_index apply.
mode{‘raise’, ‘wrap’, ‘clip’}, optional

Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index.  ‘raise’ – raise an error (default) ‘wrap’ – wrap around ‘clip’ – clip to the range  In ‘clip’ mode, a negative index which would normally wrap will clip to 0 instead.
order{‘C’, ‘F’}, optional

Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.    Returns

raveled_indicesndarray

An array of indices into the flattened version of an array of dimensions dims.      See also  unravel_index
  Notes  New in version 1.6.0.  Examples >>> arr = np.array([[3,6,6],[4,5,1]])
>>> np.ravel_multi_index(arr, (7,6))
array([22, 41, 37])
>>> np.ravel_multi_index(arr, (7,6), order='F')
array([31, 41, 13])
>>> np.ravel_multi_index(arr, (4,6), mode='clip')
array([22, 23, 19])
>>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
array([12, 13, 13])
 >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
1621


numpy.real   numpy.real(val)[source]

Return the real part of the complex argument.  Parameters

valarray_like

Input array.    Returns

outndarray or scalar

The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.      See also
real_if_close, imag, angle

  Examples >>> a = np.array([1+2j, 3+4j, 5+6j])
>>> a.real
array([1.,  3.,  5.])
>>> a.real = 9
>>> a
array([9.+2.j,  9.+4.j,  9.+6.j])
>>> a.real = np.array([9, 8, 7])
>>> a
array([9.+2.j,  8.+4.j,  7.+6.j])
>>> np.real(1 + 1j)
1.0


numpy.real_if_close   numpy.real_if_close(a, tol=100)[source]

If input is complex with all imaginary parts close to zero, return real parts. “Close to zero” is defined as tol * (machine epsilon of the type for a).  Parameters

aarray_like

Input array.
tolfloat

Tolerance in machine epsilons for the complex part of the elements in the array.    Returns

outndarray

If a is real, the type of a is used for the output. If a has complex elements, the returned type is float.      See also
real, imag, angle

  Notes Machine epsilon varies from machine to machine and between data types but Python floats on most platforms have a machine epsilon equal to 2.2204460492503131e-16. You can use ‘np.finfo(float).eps’ to print out the machine epsilon for floats. Examples >>> np.finfo(float).eps
2.2204460492503131e-16 # may vary
 >>> np.real_if_close([2.1 + 4e-14j, 5.2 + 3e-15j], tol=1000)
array([2.1, 5.2])
>>> np.real_if_close([2.1 + 4e-13j, 5.2 + 3e-15j], tol=1000)
array([2.1+4.e-13j, 5.2 + 3e-15j])


numpy.recarray   class numpy.recarray(shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, order='C')[source]

Construct an ndarray that allows field access using attributes. Arrays may have a data-types containing fields, analogous to columns in a spread sheet. An example is [(x, int), (y, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['x'] and arr['y']. Record arrays allow the fields to be accessed as members of the array, using arr.x and arr.y.  Parameters

shapetuple

Shape of output array.
dtypedata-type, optional

The desired data-type. By default, the data-type is determined from formats, names, titles, aligned and byteorder.
formatslist of data-types, optional

A list containing the data-types for the different columns, e.g. ['i4', 'f8', 'i4']. formats does not support the new convention of using types directly, i.e. (int, float, int). Note that formats must be a list, not a tuple. Given that formats is somewhat limited, we recommend specifying dtype instead.
namestuple of str, optional

The name of each column, e.g. ('x', 'y', 'z').
bufbuffer, optional

By default, a new array is created of the given shape and data-type. If buf is specified and is an object exposing the buffer interface, the array will use the memory from the existing buffer. In this case, the offset and strides keywords are available.    Returns

recrecarray

Empty array of the given shape and type.    Other Parameters

titlestuple of str, optional

Aliases for column names. For example, if names were ('x', 'y', 'z') and titles is ('x_coordinate', 'y_coordinate', 'z_coordinate'), then arr['x'] is equivalent to both arr.x and arr.x_coordinate.
byteorder{‘<’, ‘>’, ‘=’}, optional

Byte-order for all fields.
alignedbool, optional

Align the fields in memory as the C-compiler would.
stridestuple of ints, optional

Buffer (buf) is interpreted according to these strides (strides define how many bytes each array element, row, column, etc. occupy in memory).
offsetint, optional

Start reading buffer (buf) from this offset onwards.
order{‘C’, ‘F’}, optional

Row-major (C-style) or column-major (Fortran-style) order.      See also  core.records.fromrecords

Construct a record array from data.  record

fundamental data-type for recarray.  format_parser

determine a data-type from formats, names, titles.    Notes This constructor can be compared to empty: it creates a new record array but does not fill it with data. To create a record array from data, use one of the following methods:  Create a standard ndarray and convert it to a record array, using arr.view(np.recarray)
 Use the buf keyword. Use np.rec.fromrecords.  Examples Create an array with two fields, x and y: >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', '<f8'), ('y', '<i8')])
>>> x
array([(1., 2), (3., 4)], dtype=[('x', '<f8'), ('y', '<i8')])
 >>> x['x']
array([1., 3.])
 View the array as a record array: >>> x = x.view(np.recarray)
 >>> x.x
array([1., 3.])
 >>> x.y
array([2, 4])
 Create a new, empty record array: >>> np.recarray((2,),
... dtype=[('x', int), ('y', float), ('z', int)])
rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
       (3471280, 1.2134086255804012e-316, 0)],
      dtype=[('x', '<i4'), ('y', '<f8'), ('z', '<i4')])
  Attributes
 T

The transposed array.  base

Base object if memory is from some other object.  ctypes

An object to simplify the interaction of the array with the ctypes module.  data

Python buffer object pointing to the start of the array’s data.  dtype

Data-type of the array’s elements.  flags

Information about the memory layout of the array.  flat

A 1-D iterator over the array.  imag

The imaginary part of the array.  itemsize

Length of one array element in bytes.  nbytes

Total bytes consumed by the elements of the array.  ndim

Number of array dimensions.  real

The real part of the array.  shape

Tuple of array dimensions.  size

Number of elements in the array.  strides

Tuple of bytes to step in each dimension when traversing an array.     Methods
all([axis, out, keepdims, where]) Returns True if all elements evaluate to True.
any([axis, out, keepdims, where]) Returns True if any of the elements of a evaluate to True.
argmax([axis, out]) Return indices of the maximum values along the given axis.
argmin([axis, out]) Return indices of the minimum values along the given axis.
argpartition(kth[, axis, kind, order]) Returns the indices that would partition this array.
argsort([axis, kind, order]) Returns the indices that would sort this array.
astype(dtype[, order, casting, subok, copy]) Copy of the array, cast to a specified type.
byteswap([inplace]) Swap the bytes of the array elements
choose(choices[, out, mode]) Use an index array to construct a new array from a set of choices.
clip([min, max, out]) Return an array whose values are limited to [min, max].
compress(condition[, axis, out]) Return selected slices of this array along given axis.
conj() Complex-conjugate all elements.
conjugate() Return the complex conjugate, element-wise.
copy([order]) Return a copy of the array.
cumprod([axis, dtype, out]) Return the cumulative product of the elements along the given axis.
cumsum([axis, dtype, out]) Return the cumulative sum of the elements along the given axis.
diagonal([offset, axis1, axis2]) Return specified diagonals.
dump(file) Dump a pickle of the array to the specified file.
dumps() Returns the pickle of the array as a string.
fill(value) Fill the array with a scalar value.
flatten([order]) Return a copy of the array collapsed into one dimension.
getfield(dtype[, offset]) Returns a field of the given array as a certain type.
item(*args) Copy an element of an array to a standard Python scalar and return it.
itemset(*args) Insert scalar into an array (scalar is cast to array's dtype, if possible)
max([axis, out, keepdims, initial, where]) Return the maximum along a given axis.
mean([axis, dtype, out, keepdims, where]) Returns the average of the array elements along given axis.
min([axis, out, keepdims, initial, where]) Return the minimum along a given axis.
newbyteorder([new_order]) Return the array with the same data viewed with a different byte order.
nonzero() Return the indices of the elements that are non-zero.
partition(kth[, axis, kind, order]) Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.
prod([axis, dtype, out, keepdims, initial, ...]) Return the product of the array elements over the given axis
ptp([axis, out, keepdims]) Peak to peak (maximum - minimum) value along a given axis.
put(indices, values[, mode]) Set a.flat[n] = values[n] for all n in indices.
ravel([order]) Return a flattened array.
repeat(repeats[, axis]) Repeat elements of an array.
reshape(shape[, order]) Returns an array containing the same data with a new shape.
resize(new_shape[, refcheck]) Change shape and size of array in-place.
round([decimals, out]) Return a with each element rounded to the given number of decimals.
searchsorted(v[, side, sorter]) Find indices where elements of v should be inserted in a to maintain order.
setfield(val, dtype[, offset]) Put a value into a specified place in a field defined by a data-type.
setflags([write, align, uic]) Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
sort([axis, kind, order]) Sort an array in-place.
squeeze([axis]) Remove axes of length one from a.
std([axis, dtype, out, ddof, keepdims, where]) Returns the standard deviation of the array elements along given axis.
sum([axis, dtype, out, keepdims, initial, where]) Return the sum of the array elements over the given axis.
swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged.
take(indices[, axis, out, mode]) Return an array formed from the elements of a at the given indices.
tobytes([order]) Construct Python bytes containing the raw data bytes in the array.
tofile(fid[, sep, format]) Write array to a file as text or binary (default).
tolist() Return the array as an a.ndim-levels deep nested list of Python scalars.
tostring([order]) A compatibility alias for tobytes, with exactly the same behavior.
trace([offset, axis1, axis2, dtype, out]) Return the sum along diagonals of the array.
transpose(*axes) Returns a view of the array with axes transposed.
var([axis, dtype, out, ddof, keepdims, where]) Returns the variance of the array elements, along given axis.
view([dtype][, type]) New view of array with the same data.
dot
field


numpy.reciprocal   numpy.reciprocal(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'reciprocal'>

Return the reciprocal of the argument, element-wise. Calculates 1/x.  Parameters

xarray_like

Input array.
outndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

yndarray

Return array. This is a scalar if x is a scalar.     Notes  Note This function is not designed to work with integers.  For integer arguments with absolute value larger than 1 the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow. Examples >>> np.reciprocal(2.)
0.5
>>> np.reciprocal([1, 2., 3.33])
array([ 1.       ,  0.5      ,  0.3003003])