numpy.polynomial.polynomial.polypow   polynomial.polynomial.polypow(c, pow, maxpower=None)[source]

Raise a polynomial to a power. Returns the polynomial c raised to the power pow. The argument c is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series 1 + 2*x + 3*x**2.  Parameters

carray_like

1-D array of array of series coefficients ordered from low to high degree.
powinteger

Power to which the series will be raised
maxpowerinteger, optional

Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16    Returns

coefndarray

Power series of power.      See also
polyadd, polysub, polymulx, polymul, polydiv

  Examples >>> from numpy.polynomial import polynomial as P
>>> P.polypow([1,2,3], 2)
array([ 1., 4., 10., 12., 9.])


numpy.polynomial.polynomial.polyroots   polynomial.polynomial.polyroots(c)[source]

Compute the roots of a polynomial. Return the roots (a.k.a. “zeros”) of the polynomial  \[p(x) = \sum_i c[i] * x^i.\]  Parameters

c1-D array_like

1-D array of polynomial coefficients.    Returns

outndarray

Array of the roots of the polynomial. If all the roots are real, then out is also real, otherwise it is complex.      See also  numpy.polynomial.chebyshev.chebroots
numpy.polynomial.legendre.legroots
numpy.polynomial.laguerre.lagroots
numpy.polynomial.hermite.hermroots
numpy.polynomial.hermite_e.hermeroots
  Notes The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the power series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton’s method. Examples >>> import numpy.polynomial.polynomial as poly
>>> poly.polyroots(poly.polyfromroots((-1,0,1)))
array([-1.,  0.,  1.])
>>> poly.polyroots(poly.polyfromroots((-1,0,1))).dtype
dtype('float64')
>>> j = complex(0,1)
>>> poly.polyroots(poly.polyfromroots((-j,0,j)))
array([  0.00000000e+00+0.j,   0.00000000e+00+1.j,   2.77555756e-17-1.j]) # may vary


numpy.polynomial.polynomial.polysub   polynomial.polynomial.polysub(c1, c2)[source]

Subtract one polynomial from another. Returns the difference of two polynomials c1 - c2. The arguments are sequences of coefficients from lowest order term to highest, i.e., [1,2,3] represents the polynomial 1 + 2*x + 3*x**2.  Parameters

c1, c2array_like

1-D arrays of polynomial coefficients ordered from low to high.    Returns

outndarray

Of coefficients representing their difference.      See also
polyadd, polymulx, polymul, polydiv, polypow

  Examples >>> from numpy.polynomial import polynomial as P
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> P.polysub(c1,c2)
array([-2.,  0.,  2.])
>>> P.polysub(c2,c1) # -P.polysub(c1,c2)
array([ 2.,  0., -2.])


numpy.polynomial.polynomial.polytrim   polynomial.polynomial.polytrim(c, tol=0)[source]

Remove “small” “trailing” coefficients from a polynomial. “Small” means “small in absolute value” and is controlled by the parameter tol; “trailing” means highest order coefficient(s), e.g., in [0, 1, 1, 0, 0] (which represents 0 + x + x**2 + 0*x**3 + 0*x**4) both the 3-rd and 4-th order coefficients would be “trimmed.”  Parameters

carray_like

1-d array of coefficients, ordered from lowest order to highest.
tolnumber, optional

Trailing (i.e., highest order) elements with absolute value less than or equal to tol (default value is zero) are removed.    Returns

trimmedndarray

1-d array with trailing zeros removed. If the resulting series would be empty, a series containing a single zero is returned.    Raises
 ValueError

If tol < 0      See also  trimseq
  Examples >>> from numpy.polynomial import polyutils as pu
>>> pu.trimcoef((0,0,3,0,5,0,0))
array([0.,  0.,  3.,  0.,  5.])
>>> pu.trimcoef((0,0,1e-3,0,1e-5,0,0),1e-3) # item == tol is trimmed
array([0.])
>>> i = complex(0,1) # works for complex
>>> pu.trimcoef((3e-4,1e-3*(1-i),5e-4,2e-5*(1+i)), 1e-3)
array([0.0003+0.j   , 0.001 -0.001j])


numpy.polynomial.polynomial.polyval   polynomial.polynomial.polyval(x, c, tensor=True)[source]

Evaluate a polynomial at points x. If c is of length n + 1, this function returns the value  \[p(x) = c_0 + c_1 * x + ... + c_n * x^n\] The parameter x is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either x or its elements must support multiplication and addition both with themselves and with the elements of c. If c is a 1-D array, then p(x) will have the same shape as x. If c is multidimensional, then the shape of the result depends on the value of tensor. If tensor is true the shape will be c.shape[1:] + x.shape. If tensor is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern.  Parameters

xarray_like, compatible object

If x is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, x or its elements must support addition and multiplication with with themselves and with the elements of c.
carray_like

Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If c is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of c.
tensorboolean, optional

If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of x. Scalars have dimension 0 for this action. The result is that every column of coefficients in c is evaluated for every element of x. If False, x is broadcast over the columns of c for the evaluation. This keyword is useful when c is multidimensional. The default value is True.  New in version 1.7.0.     Returns

valuesndarray, compatible object

The shape of the returned array is described above.      See also
polyval2d, polygrid2d, polyval3d, polygrid3d

  Notes The evaluation uses Horner’s method. Examples >>> from numpy.polynomial.polynomial import polyval
>>> polyval(1, [1,2,3])
6.0
>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> polyval(a, [1,2,3])
array([[ 1.,   6.],
       [17.,  34.]])
>>> coef = np.arange(4).reshape(2,2) # multidimensional coefficients
>>> coef
array([[0, 1],
       [2, 3]])
>>> polyval([1,2], coef, tensor=True)
array([[2.,  4.],
       [4.,  7.]])
>>> polyval([1,2], coef, tensor=False)
array([2.,  7.])


numpy.polynomial.polynomial.polyval2d   polynomial.polynomial.polyval2d(x, y, c)[source]

Evaluate a 2-D polynomial at points (x, y). This function returns the value  \[p(x,y) = \sum_{i,j} c_{i,j} * x^i * y^j\] The parameters x and y are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either x and y or their elements must support multiplication and addition both with themselves and with the elements of c. If c has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape.  Parameters

x, yarray_like, compatible objects

The two dimensional series is evaluated at the points (x, y), where x and y must have the same shape. If x or y is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn’t an ndarray, it is treated as a scalar.
carray_like

Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in c[i,j]. If c has dimension greater than two the remaining indices enumerate multiple sets of coefficients.    Returns

valuesndarray, compatible object

The values of the two dimensional polynomial at points formed with pairs of corresponding values from x and y.      See also
polyval, polygrid2d, polyval3d, polygrid3d

  Notes  New in version 1.7.0.


numpy.polynomial.polynomial.polyval3d   polynomial.polynomial.polyval3d(x, y, z, c)[source]

Evaluate a 3-D polynomial at points (x, y, z). This function returns the values:  \[p(x,y,z) = \sum_{i,j,k} c_{i,j,k} * x^i * y^j * z^k\] The parameters x, y, and z are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either x, y, and z or their elements must support multiplication and addition both with themselves and with the elements of c. If c has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape.  Parameters

x, y, zarray_like, compatible object

The three dimensional series is evaluated at the points (x, y, z), where x, y, and z must have the same shape. If any of x, y, or z is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn’t an ndarray it is treated as a scalar.
carray_like

Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in c[i,j,k]. If c has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients.    Returns

valuesndarray, compatible object

The values of the multidimensional polynomial on points formed with triples of corresponding values from x, y, and z.      See also
polyval, polyval2d, polygrid2d, polygrid3d

  Notes  New in version 1.7.0.


numpy.polynomial.polynomial.polyvalfromroots   polynomial.polynomial.polyvalfromroots(x, r, tensor=True)[source]

Evaluate a polynomial specified by its roots at points x. If r is of length N, this function returns the value  \[p(x) = \prod_{n=1}^{N} (x - r_n)\] The parameter x is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either x or its elements must support multiplication and addition both with themselves and with the elements of r. If r is a 1-D array, then p(x) will have the same shape as x. If r is multidimensional, then the shape of the result depends on the value of tensor. If tensor is ``True` the shape will be r.shape[1:] + x.shape; that is, each polynomial is evaluated at every value of x. If tensor is False, the shape will be r.shape[1:]; that is, each polynomial is evaluated only for the corresponding broadcast value of x. Note that scalars have shape (,).  New in version 1.12.   Parameters

xarray_like, compatible object

If x is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, x or its elements must support addition and multiplication with with themselves and with the elements of r.
rarray_like

Array of roots. If r is multidimensional the first index is the root index, while the remaining indices enumerate multiple polynomials. For instance, in the two dimensional case the roots of each polynomial may be thought of as stored in the columns of r.
tensorboolean, optional

If True, the shape of the roots array is extended with ones on the right, one for each dimension of x. Scalars have dimension 0 for this action. The result is that every column of coefficients in r is evaluated for every element of x. If False, x is broadcast over the columns of r for the evaluation. This keyword is useful when r is multidimensional. The default value is True.    Returns

valuesndarray, compatible object

The shape of the returned array is described above.      See also
polyroots, polyfromroots, polyval

  Examples >>> from numpy.polynomial.polynomial import polyvalfromroots
>>> polyvalfromroots(1, [1,2,3])
0.0
>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> polyvalfromroots(a, [-1, 0, 1])
array([[-0.,   0.],
       [ 6.,  24.]])
>>> r = np.arange(-2, 2).reshape(2,2) # multidimensional coefficients
>>> r # each column of r defines one polynomial
array([[-2, -1],
       [ 0,  1]])
>>> b = [-2, 1]
>>> polyvalfromroots(b, r, tensor=True)
array([[-0.,  3.],
       [ 3., 0.]])
>>> polyvalfromroots(b, r, tensor=False)
array([-0.,  0.])


numpy.polynomial.polynomial.polyvander   polynomial.polynomial.polyvander(x, deg)[source]

Vandermonde matrix of given degree. Returns the Vandermonde matrix of degree deg and sample points x. The Vandermonde matrix is defined by  \[V[..., i] = x^i,\] where 0 <= i <= deg. The leading indices of V index the elements of x and the last index is the power of x. If c is a 1-D array of coefficients of length n + 1 and V is the matrix V = polyvander(x, n), then np.dot(V, c) and polyval(x, c) are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of polynomials of the same degree and sample points.  Parameters

xarray_like

Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If x is scalar it is converted to a 1-D array.
degint

Degree of the resulting matrix.    Returns

vanderndarray.

The Vandermonde matrix. The shape of the returned matrix is x.shape + (deg + 1,), where the last index is the power of x. The dtype will be the same as the converted x.      See also
polyvander2d, polyvander3d


numpy.polynomial.polynomial.polyvander2d   polynomial.polynomial.polyvander2d(x, y, deg)[source]

Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees deg and sample points (x, y). The pseudo-Vandermonde matrix is defined by  \[V[..., (deg[1] + 1)*i + j] = x^i * y^j,\] where 0 <= i <= deg[0] and 0 <= j <= deg[1]. The leading indices of V index the points (x, y) and the last index encodes the powers of x and y. If V = polyvander2d(x, y, [xdeg, ydeg]), then the columns of V correspond to the elements of a 2-D coefficient array c of shape (xdeg + 1, ydeg + 1) in the order  \[c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\] and np.dot(V, c.flat) and polyval2d(x, y, c) will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D polynomials of the same degrees and sample points.  Parameters

x, yarray_like

Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays.
deglist of ints

List of maximum degrees of the form [x_deg, y_deg].    Returns

vander2dndarray

The shape of the returned matrix is x.shape + (order,), where \(order = (deg[0]+1)*(deg([1]+1)\). The dtype will be the same as the converted x and y.      See also
polyvander, polyvander3d, polyval2d, polyval3d


numpy.polynomial.polynomial.polyvander3d   polynomial.polynomial.polyvander3d(x, y, z, deg)[source]

Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees deg and sample points (x, y, z). If l, m, n are the given degrees in x, y, z, then The pseudo-Vandermonde matrix is defined by  \[V[..., (m+1)(n+1)i + (n+1)j + k] = x^i * y^j * z^k,\] where 0 <= i <= l, 0 <= j <= m, and 0 <= j <= n. The leading indices of V index the points (x, y, z) and the last index encodes the powers of x, y, and z. If V = polyvander3d(x, y, z, [xdeg, ydeg, zdeg]), then the columns of V correspond to the elements of a 3-D coefficient array c of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order  \[c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\] and np.dot(V, c.flat) and polyval3d(x, y, z, c) will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 3-D polynomials of the same degrees and sample points.  Parameters

x, y, zarray_like

Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays.
deglist of ints

List of maximum degrees of the form [x_deg, y_deg, z_deg].    Returns

vander3dndarray

The shape of the returned matrix is x.shape + (order,), where \(order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)\). The dtype will be the same as the converted x, y, and z.      See also
polyvander, polyvander3d, polyval2d, polyval3d

  Notes  New in version 1.7.0.


numpy.polynomial.polynomial.polyx   polynomial.polynomial.polyx = array([0, 1])

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array.  Parameters
 (for the __new__ method; see Notes below)

shapetuple of ints

Shape of created array.
dtypedata-type, optional

Any object that can be interpreted as a numpy data type.
bufferobject exposing buffer interface, optional

Used to fill the array with data.
offsetint, optional

Offset of array data in buffer.
stridestuple of ints, optional

Strides of data in memory.
order{‘C’, ‘F’}, optional

Row-major (C-style) or column-major (Fortran-style) order.      See also  array

Construct an array.  zeros

Create an array, each element of which is zero.  empty

Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”).  dtype

Create a data-type.  numpy.typing.NDArray

An ndarray alias generic w.r.t. its dtype.type.    Notes There are two modes of creating an array using __new__:  If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted.  No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
       [     nan, 2.5e-323]])
 Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])
  Attributes

Tndarray

Transpose of the array.
databuffer

The array’s elements, in memory.
dtypedtype object

Describes the format of the elements in the array.
flagsdict

Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
flatnumpy.flatiter object

Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO).
imagndarray

Imaginary part of the array.
realndarray

Real part of the array.
sizeint

Number of elements in the array.
itemsizeint

The memory use of each array element in bytes.
nbytesint

The total number of bytes required to store the array data, i.e., itemsize * size.
ndimint

The array’s number of dimensions.
shapetuple of ints

Shape of the array.
stridestuple of ints

The step-size required to move from one element to the next in memory. For example, a contiguous (3, 4) array of type int16 in C-order has strides (8, 2). This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (2 * 4).
ctypesctypes object

Class containing properties of the array needed for interaction with ctypes.
basendarray

If the array is a view into another array, that array is its base (unless that array is also a view). The base array is where the array data is actually stored.


numpy.polynomial.polynomial.polyzero   polynomial.polynomial.polyzero = array([0])

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array.  Parameters
 (for the __new__ method; see Notes below)

shapetuple of ints

Shape of created array.
dtypedata-type, optional

Any object that can be interpreted as a numpy data type.
bufferobject exposing buffer interface, optional

Used to fill the array with data.
offsetint, optional

Offset of array data in buffer.
stridestuple of ints, optional

Strides of data in memory.
order{‘C’, ‘F’}, optional

Row-major (C-style) or column-major (Fortran-style) order.      See also  array

Construct an array.  zeros

Create an array, each element of which is zero.  empty

Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”).  dtype

Create a data-type.  numpy.typing.NDArray

An ndarray alias generic w.r.t. its dtype.type.    Notes There are two modes of creating an array using __new__:  If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted.  No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
       [     nan, 2.5e-323]])
 Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])
  Attributes

Tndarray

Transpose of the array.
databuffer

The array’s elements, in memory.
dtypedtype object

Describes the format of the elements in the array.
flagsdict

Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
flatnumpy.flatiter object

Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO).
imagndarray

Imaginary part of the array.
realndarray

Real part of the array.
sizeint

Number of elements in the array.
itemsizeint

The memory use of each array element in bytes.
nbytesint

The total number of bytes required to store the array data, i.e., itemsize * size.
ndimint

The array’s number of dimensions.
shapetuple of ints

Shape of the array.
stridestuple of ints

The step-size required to move from one element to the next in memory. For example, a contiguous (3, 4) array of type int16 in C-order has strides (8, 2). This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (2 * 4).
ctypesctypes object

Class containing properties of the array needed for interaction with ctypes.
basendarray

If the array is a view into another array, that array is its base (unless that array is also a view). The base array is where the array data is actually stored.


numpy.polynomial.polyutils.as_series   polynomial.polyutils.as_series(alist, trim=True)[source]

Return argument as a list of 1-d arrays. The returned list contains array(s) of dtype double, complex double, or object. A 1-d argument of shape (N,) is parsed into N arrays of size one; a 2-d argument of shape (M,N) is parsed into M arrays of size N (i.e., is “parsed by row”); and a higher dimensional array raises a Value Error if it is not first reshaped into either a 1-d or 2-d array.  Parameters

alistarray_like

A 1- or 2-d array_like
trimboolean, optional

When True, trailing zeros are removed from the inputs. When False, the inputs are passed through intact.    Returns

[a1, a2,…]list of 1-D arrays

A copy of the input data as a list of 1-d arrays.    Raises
 ValueError

Raised when as_series cannot convert its input to 1-d arrays, or at least one of the resulting arrays is empty.     Examples >>> from numpy.polynomial import polyutils as pu
>>> a = np.arange(4)
>>> pu.as_series(a)
[array([0.]), array([1.]), array([2.]), array([3.])]
>>> b = np.arange(6).reshape((2,3))
>>> pu.as_series(b)
[array([0., 1., 2.]), array([3., 4., 5.])]
 >>> pu.as_series((1, np.arange(3), np.arange(2, dtype=np.float16)))
[array([1.]), array([0., 1., 2.]), array([0., 1.])]
 >>> pu.as_series([2, [1.1, 0.]])
[array([2.]), array([1.1])]
 >>> pu.as_series([2, [1.1, 0.]], trim=False)
[array([2.]), array([1.1, 0. ])]


numpy.polynomial.polyutils.getdomain   polynomial.polyutils.getdomain(x)[source]

Return a domain suitable for given abscissae. Find a domain suitable for a polynomial or Chebyshev series defined at the values supplied.  Parameters

xarray_like

1-d array of abscissae whose domain will be determined.    Returns

domainndarray

1-d array containing two values. If the inputs are complex, then the two returned points are the lower left and upper right corners of the smallest rectangle (aligned with the axes) in the complex plane containing the points x. If the inputs are real, then the two points are the ends of the smallest interval containing the points x.      See also
mapparms, mapdomain

  Examples >>> from numpy.polynomial import polyutils as pu
>>> points = np.arange(4)**2 - 5; points
array([-5, -4, -1,  4])
>>> pu.getdomain(points)
array([-5.,  4.])
>>> c = np.exp(complex(0,1)*np.pi*np.arange(12)/6) # unit circle
>>> pu.getdomain(c)
array([-1.-1.j,  1.+1.j])


numpy.polynomial.polyutils.mapdomain   polynomial.polyutils.mapdomain(x, old, new)[source]

Apply linear map to input points. The linear map offset + scale*x that maps the domain old to the domain new is applied to the points x.  Parameters

xarray_like

Points to be mapped. If x is a subtype of ndarray the subtype will be preserved.
old, newarray_like

The two domains that determine the map. Each must (successfully) convert to 1-d arrays containing precisely two values.    Returns

x_outndarray

Array of points of the same shape as x, after application of the linear map between the two domains.      See also
getdomain, mapparms

  Notes Effectively, this implements:  \[x\_out = new[0] + m(x - old[0])\] where  \[m = \frac{new[1]-new[0]}{old[1]-old[0]}\] Examples >>> from numpy.polynomial import polyutils as pu
>>> old_domain = (-1,1)
>>> new_domain = (0,2*np.pi)
>>> x = np.linspace(-1,1,6); x
array([-1. , -0.6, -0.2,  0.2,  0.6,  1. ])
>>> x_out = pu.mapdomain(x, old_domain, new_domain); x_out
array([ 0.        ,  1.25663706,  2.51327412,  3.76991118,  5.02654825, # may vary
        6.28318531])
>>> x - pu.mapdomain(x_out, new_domain, old_domain)
array([0., 0., 0., 0., 0., 0.])
 Also works for complex numbers (and thus can be used to map any line in the complex plane to any other line therein). >>> i = complex(0,1)
>>> old = (-1 - i, 1 + i)
>>> new = (-1 + i, 1 - i)
>>> z = np.linspace(old[0], old[1], 6); z
array([-1. -1.j , -0.6-0.6j, -0.2-0.2j,  0.2+0.2j,  0.6+0.6j,  1. +1.j ])
>>> new_z = pu.mapdomain(z, old, new); new_z
array([-1.0+1.j , -0.6+0.6j, -0.2+0.2j,  0.2-0.2j,  0.6-0.6j,  1.0-1.j ]) # may vary


numpy.polynomial.polyutils.mapparms   polynomial.polyutils.mapparms(old, new)[source]

Linear map parameters between domains. Return the parameters of the linear map offset + scale*x that maps old to new such that old[i] -> new[i], i = 0, 1.  Parameters

old, newarray_like

Domains. Each domain must (successfully) convert to a 1-d array containing precisely two values.    Returns

offset, scalescalars

The map L(x) = offset + scale*x maps the first domain to the second.      See also
getdomain, mapdomain

  Notes Also works for complex numbers, and thus can be used to calculate the parameters required to map any line in the complex plane to any other line therein. Examples >>> from numpy.polynomial import polyutils as pu
>>> pu.mapparms((-1,1),(-1,1))
(0.0, 1.0)
>>> pu.mapparms((1,-1),(-1,1))
(-0.0, -1.0)
>>> i = complex(0,1)
>>> pu.mapparms((-i,-1),(1,i))
((1+1j), (1-0j))


numpy.polynomial.polyutils.RankWarning   exception polynomial.polyutils.RankWarning[source]

Issued by chebfit when the design matrix is rank deficient.


numpy.polynomial.polyutils.trimcoef   polynomial.polyutils.trimcoef(c, tol=0)[source]

Remove “small” “trailing” coefficients from a polynomial. “Small” means “small in absolute value” and is controlled by the parameter tol; “trailing” means highest order coefficient(s), e.g., in [0, 1, 1, 0, 0] (which represents 0 + x + x**2 + 0*x**3 + 0*x**4) both the 3-rd and 4-th order coefficients would be “trimmed.”  Parameters

carray_like

1-d array of coefficients, ordered from lowest order to highest.
tolnumber, optional

Trailing (i.e., highest order) elements with absolute value less than or equal to tol (default value is zero) are removed.    Returns

trimmedndarray

1-d array with trailing zeros removed. If the resulting series would be empty, a series containing a single zero is returned.    Raises
 ValueError

If tol < 0      See also  trimseq
  Examples >>> from numpy.polynomial import polyutils as pu
>>> pu.trimcoef((0,0,3,0,5,0,0))
array([0.,  0.,  3.,  0.,  5.])
>>> pu.trimcoef((0,0,1e-3,0,1e-5,0,0),1e-3) # item == tol is trimmed
array([0.])
>>> i = complex(0,1) # works for complex
>>> pu.trimcoef((3e-4,1e-3*(1-i),5e-4,2e-5*(1+i)), 1e-3)
array([0.0003+0.j   , 0.001 -0.001j])


numpy.polynomial.polyutils.trimseq   polynomial.polyutils.trimseq(seq)[source]

Remove small Poly series coefficients.  Parameters

seqsequence

Sequence of Poly series coefficients. This routine fails for empty sequences.    Returns

seriessequence

Subsequence with trailing zeros removed. If the resulting sequence would be empty, return the first element. The returned sequence may or may not be a view.     Notes Do not lose the type info if the sequence contains unknown objects.


numpy.polynomial.set_default_printstyle   polynomial.set_default_printstyle(style)[source]

Set the default format for the string representation of polynomials. Values for style must be valid inputs to __format__, i.e. ‘ascii’ or ‘unicode’.  Parameters

stylestr

Format string for default printing style. Must be either ‘ascii’ or ‘unicode’.     Notes The default format depends on the platform: ‘unicode’ is used on Unix-based systems and ‘ascii’ on Windows. This determination is based on default font support for the unicode superscript and subscript ranges. Examples >>> p = np.polynomial.Polynomial([1, 2, 3])
>>> c = np.polynomial.Chebyshev([1, 2, 3])
>>> np.polynomial.set_default_printstyle('unicode')
>>> print(p)
1.0 + 2.0·x¹ + 3.0·x²
>>> print(c)
1.0 + 2.0·T₁(x) + 3.0·T₂(x)
>>> np.polynomial.set_default_printstyle('ascii')
>>> print(p)
1.0 + 2.0 x**1 + 3.0 x**2
>>> print(c)
1.0 + 2.0 T_1(x) + 3.0 T_2(x)
>>> # Formatting supersedes all class/package-level defaults
>>> print(f"{p:unicode}")
1.0 + 2.0·x¹ + 3.0·x²


Polyutils Utility classes and functions for the polynomial modules. This module provides: error and warning objects; a polynomial base class; and some routines used in both the polynomial and chebyshev modules.  Warning objects
RankWarning Issued by chebfit when the design matrix is rank deficient.     Functions
as_series(alist[, trim]) Return argument as a list of 1-d arrays.
trimseq(seq) Remove small Poly series coefficients.
trimcoef(c[, tol]) Remove "small" "trailing" coefficients from a polynomial.
getdomain(x) Return a domain suitable for given abscissae.
mapdomain(x, old, new) Apply linear map to input points.
mapparms(old, new) Linear map parameters between domains.


numpy.random.beta   random.beta(a, b, size=None)

Draw samples from a Beta distribution. The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution. It has the probability distribution function  \[f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha - 1} (1 - x)^{\beta - 1},\] where the normalization, B, is the beta function,  \[B(\alpha, \beta) = \int_0^1 t^{\alpha - 1} (1 - t)^{\beta - 1} dt.\] It is often seen in Bayesian inference and order statistics.  Note New code should use the beta method of a default_rng() instance instead; please see the Quick Start.   Parameters

afloat or array_like of floats

Alpha, positive (>0).
bfloat or array_like of floats

Beta, positive (>0).
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if a and b are both scalars. Otherwise, np.broadcast(a, b).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized beta distribution.      See also  Generator.beta

which should be used for new code.


numpy.random.binomial   random.binomial(n, p, size=None)

Draw samples from a binomial distribution. Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval [0,1]. (n may be input as a float, but it is truncated to an integer in use)  Note New code should use the binomial method of a default_rng() instance instead; please see the Quick Start.   Parameters

nint or array_like of ints

Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.
pfloat or array_like of floats

Parameter of the distribution, >= 0 and <=1.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if n and p are both scalars. Otherwise, np.broadcast(n, p).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.      See also  scipy.stats.binom

probability density function, distribution or cumulative density function, etc.  Generator.binomial

which should be used for new code.    Notes The probability density for the binomial distribution is  \[P(N) = \binom{n}{N}p^N(1-p)^{n-N},\] where \(n\) is the number of trials, \(p\) is the probability of success, and \(N\) is the number of successes. When estimating the standard error of a proportion in a population by using a random sample, the normal distribution works well unless the product p*n <=5, where p = population proportion estimate, and n = number of samples, in which case the binomial distribution is used instead. For example, a sample of 15 people shows 4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so the binomial distribution should be used in this case. References  1
Dalgaard, Peter, “Introductory Statistics with R”, Springer-Verlag, 2002.  2
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.  3
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.  4
Weisstein, Eric W. “Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html  5
Wikipedia, “Binomial distribution”, https://en.wikipedia.org/wiki/Binomial_distribution   Examples Draw samples from the distribution: >>> n, p = 10, .5  # number of trials, probability of each trial
>>> s = np.random.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.
 A real world example. A company drills 9 wild-cat oil exploration wells, each with an estimated probability of success of 0.1. All nine wells fail. What is the probability of that happening? Let’s do 20,000 trials of the model, and count the number that generate zero positive results. >>> sum(np.random.binomial(9, 0.1, 20000) == 0)/20000.
# answer = 0.38885, or 38%.


numpy.random.BitGenerator.cffi attribute   random.BitGenerator.cffi

CFFI interface  Returns

interfacenamedtuple

Named tuple containing CFFI wrapper  state_address - Memory address of the state struct state - pointer to the state struct next_uint64 - function pointer to produce 64 bit integers next_uint32 - function pointer to produce 32 bit integers next_double - function pointer to produce doubles bitgen - pointer to the bit generator struct


numpy.random.BitGenerator.random_raw method   random.BitGenerator.random_raw(self, size=None)

Return randoms as generated by the underlying BitGenerator  Parameters

sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
outputbool, optional

Output values. Used for performance testing since the generated values are not returned.    Returns

outuint or ndarray

Drawn samples.     Notes This method directly exposes the the raw underlying pseudo-random number generator. All values are returned as unsigned 64-bit values irrespective of the number of bits produced by the PRNG. See the class docstring for the number of bits returned.


numpy.random.bytes   random.bytes(length)

Return random bytes.  Note New code should use the bytes method of a default_rng() instance instead; please see the Quick Start.   Parameters

lengthint

Number of random bytes.    Returns

outbytes

String of length length.      See also  Generator.bytes

which should be used for new code.    Examples >>> np.random.bytes(10)
b' eh\x85\x022SZ\xbf\xa4' #random


numpy.random.chisquare   random.chisquare(df, size=None)

Draw samples from a chi-square distribution. When df independent random variables, each with standard normal distributions (mean 0, variance 1), are squared and summed, the resulting distribution is chi-square (see Notes). This distribution is often used in hypothesis testing.  Note New code should use the chisquare method of a default_rng() instance instead; please see the Quick Start.   Parameters

dffloat or array_like of floats

Number of degrees of freedom, must be > 0.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if df is a scalar. Otherwise, np.array(df).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized chi-square distribution.    Raises
 ValueError

When df <= 0 or when an inappropriate size (e.g. size=-1) is given.      See also  Generator.chisquare

which should be used for new code.    Notes The variable obtained by summing the squares of df independent, standard normally distributed random variables:  \[Q = \sum_{i=0}^{\mathtt{df}} X^2_i\] is chi-square distributed, denoted  \[Q \sim \chi^2_k.\] The probability density function of the chi-squared distribution is  \[p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)} x^{k/2 - 1} e^{-x/2},\] where \(\Gamma\) is the gamma function,  \[\Gamma(x) = \int_0^{-\infty} t^{x - 1} e^{-t} dt.\] References  1
NIST “Engineering Statistics Handbook” https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm   Examples >>> np.random.chisquare(2,4)
array([ 1.89920014,  9.00867716,  3.13710533,  5.62318272]) # random


numpy.random.choice   random.choice(a, size=None, replace=True, p=None)

Generates a random sample from a given 1-D array  New in version 1.7.0.   Note New code should use the choice method of a default_rng() instance instead; please see the Quick Start.   Parameters

a1-D array-like or int

If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if it were np.arange(a)
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
replaceboolean, optional

Whether the sample is with or without replacement. Default is True, meaning that a value of a can be selected multiple times.
p1-D array-like, optional

The probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in a.    Returns

samplessingle item or ndarray

The generated random samples    Raises
 ValueError

If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size      See also
randint, shuffle, permutation

Generator.choice

which should be used in new code    Notes Setting user-specified probabilities through p uses a more general but less efficient sampler than the default. The general sampler produces a different sample than the optimized sampler even if each element of p is 1 / len(a). Sampling random rows from a 2-D array is not possible with this function, but is possible with Generator.choice through its axis keyword. Examples Generate a uniform random sample from np.arange(5) of size 3: >>> np.random.choice(5, 3)
array([0, 3, 4]) # random
>>> #This is equivalent to np.random.randint(0,5,3)
 Generate a non-uniform random sample from np.arange(5) of size 3: >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0]) # random
 Generate a uniform random sample from np.arange(5) of size 3 without replacement: >>> np.random.choice(5, 3, replace=False)
array([3,1,0]) # random
>>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
 Generate a non-uniform random sample from np.arange(5) of size 3 without replacement: >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
array([2, 3, 0]) # random
 Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance: >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random
      dtype='<U11')


numpy.random.dirichlet   random.dirichlet(alpha, size=None)

Draw samples from the Dirichlet distribution. Draw size samples of dimension k from a Dirichlet distribution. A Dirichlet-distributed random variable can be seen as a multivariate generalization of a Beta distribution. The Dirichlet distribution is a conjugate prior of a multinomial distribution in Bayesian inference.  Note New code should use the dirichlet method of a default_rng() instance instead; please see the Quick Start.   Parameters

alphasequence of floats, length k

Parameter of the distribution (length k for sample of length k).
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n), then m * n * k samples are drawn. Default is None, in which case a vector of length k is returned.    Returns

samplesndarray,

The drawn samples, of shape (size, k).    Raises
 ValueError

If any value in alpha is less than or equal to zero      See also  Generator.dirichlet

which should be used for new code.    Notes The Dirichlet distribution is a distribution over vectors \(x\) that fulfil the conditions \(x_i>0\) and \(\sum_{i=1}^k x_i = 1\). The probability density function \(p\) of a Dirichlet-distributed random vector \(X\) is proportional to  \[p(x) \propto \prod_{i=1}^{k}{x^{\alpha_i-1}_i},\] where \(\alpha\) is a vector containing the positive concentration parameters. The method uses the following property for computation: let \(Y\) be a random vector which has components that follow a standard gamma distribution, then \(X = \frac{1}{\sum_{i=1}^k{Y_i}} Y\) is Dirichlet-distributed References  1
David McKay, “Information Theory, Inference and Learning Algorithms,” chapter 23, http://www.inference.org.uk/mackay/itila/  2
Wikipedia, “Dirichlet distribution”, https://en.wikipedia.org/wiki/Dirichlet_distribution   Examples Taking an example cited in Wikipedia, this distribution can be used if one wanted to cut strings (each of initial length 1.0) into K pieces with different lengths, where each piece had, on average, a designated average length, but allowing some variation in the relative sizes of the pieces. >>> s = np.random.dirichlet((10, 5, 3), 20).transpose()
 >>> import matplotlib.pyplot as plt
>>> plt.barh(range(20), s[0])
>>> plt.barh(range(20), s[1], left=s[0], color='g')
>>> plt.barh(range(20), s[2], left=s[0]+s[1], color='r')
>>> plt.title("Lengths of Strings")


numpy.random.exponential   random.exponential(scale=1.0, size=None)

Draw samples from an exponential distribution. Its probability density function is  \[f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}),\] for x > 0 and 0 elsewhere. \(\beta\) is the scale parameter, which is the inverse of the rate parameter \(\lambda = 1/\beta\). The rate parameter is an alternative, widely used parameterization of the exponential distribution [3]. The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms [1], or the time between page requests to Wikipedia [2].  Note New code should use the exponential method of a default_rng() instance instead; please see the Quick Start.   Parameters

scalefloat or array_like of floats

The scale parameter, \(\beta = 1/\lambda\). Must be non-negative.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if scale is a scalar. Otherwise, np.array(scale).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized exponential distribution.      See also  Generator.exponential

which should be used for new code.    References  1
Peyton Z. Peebles Jr., “Probability, Random Variables and Random Signal Principles”, 4th ed, 2001, p. 57.  2
Wikipedia, “Poisson process”, https://en.wikipedia.org/wiki/Poisson_process  3
Wikipedia, “Exponential distribution”, https://en.wikipedia.org/wiki/Exponential_distribution


numpy.random.f   random.f(dfnum, dfden, size=None)

Draw samples from an F distribution. Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in numerator) and dfden (degrees of freedom in denominator), where both parameters must be greater than zero. The random variate of the F distribution (also known as the Fisher distribution) is a continuous probability distribution that arises in ANOVA tests, and is the ratio of two chi-square variates.  Note New code should use the f method of a default_rng() instance instead; please see the Quick Start.   Parameters

dfnumfloat or array_like of floats

Degrees of freedom in numerator, must be > 0.
dfdenfloat or array_like of float

Degrees of freedom in denominator, must be > 0.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if dfnum and dfden are both scalars. Otherwise, np.broadcast(dfnum, dfden).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized Fisher distribution.      See also  scipy.stats.f

probability density function, distribution or cumulative density function, etc.  Generator.f

which should be used for new code.    Notes The F statistic is used to compare in-group variances to between-group variances. Calculating the distribution depends on the sampling, and so it is a function of the respective degrees of freedom in the problem. The variable dfnum is the number of samples minus one, the between-groups degrees of freedom, while dfden is the within-groups degrees of freedom, the sum of the number of samples in each group minus the number of groups. References  1
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.  2
Wikipedia, “F-distribution”, https://en.wikipedia.org/wiki/F-distribution   Examples An example from Glantz[1], pp 47-40: Two groups, children of diabetics (25 people) and children from people without diabetes (25 controls). Fasting blood glucose was measured, case group had a mean value of 86.1, controls had a mean value of 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these data consistent with the null hypothesis that the parents diabetic status does not affect their children’s blood glucose levels? Calculating the F statistic from the data gives a value of 36.01. Draw samples from the distribution: >>> dfnum = 1. # between group degrees of freedom
>>> dfden = 48. # within groups degrees of freedom
>>> s = np.random.f(dfnum, dfden, 1000)
 The lower bound for the top 1% of the samples is : >>> np.sort(s)[-10]
7.61988120985 # random
 So there is about a 1% chance that the F statistic will exceed 7.62, the measured value is 36, so the null hypothesis is rejected at the 1% level.


numpy.random.gamma   random.gamma(shape, scale=1.0, size=None)

Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale (sometimes designated “theta”), where both parameters are > 0.  Note New code should use the gamma method of a default_rng() instance instead; please see the Quick Start.   Parameters

shapefloat or array_like of floats

The shape of the gamma distribution. Must be non-negative.
scalefloat or array_like of floats, optional

The scale of the gamma distribution. Must be non-negative. Default is equal to 1.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if shape and scale are both scalars. Otherwise, np.broadcast(shape, scale).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized gamma distribution.      See also  scipy.stats.gamma

probability density function, distribution or cumulative density function, etc.  Generator.gamma

which should be used for new code.    Notes The probability density for the Gamma distribution is  \[p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},\] where \(k\) is the shape and \(\theta\) the scale, and \(\Gamma\) is the Gamma function. The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant. References  1
Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html  2
Wikipedia, “Gamma distribution”, https://en.wikipedia.org/wiki/Gamma_distribution   Examples Draw samples from the distribution: >>> shape, scale = 2., 2.  # mean=4, std=2*sqrt(2)
>>> s = np.random.gamma(shape, scale, 1000)
 Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt
>>> import scipy.special as sps
>>> count, bins, ignored = plt.hist(s, 50, density=True)
>>> y = bins**(shape-1)*(np.exp(-bins/scale) /
...                      (sps.gamma(shape)*scale**shape))
>>> plt.plot(bins, y, linewidth=2, color='r')
>>> plt.show()


numpy.random.Generator.beta method   random.Generator.beta(a, b, size=None)

Draw samples from a Beta distribution. The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution. It has the probability distribution function  \[f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha - 1} (1 - x)^{\beta - 1},\] where the normalization, B, is the beta function,  \[B(\alpha, \beta) = \int_0^1 t^{\alpha - 1} (1 - t)^{\beta - 1} dt.\] It is often seen in Bayesian inference and order statistics.  Parameters

afloat or array_like of floats

Alpha, positive (>0).
bfloat or array_like of floats

Beta, positive (>0).
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if a and b are both scalars. Otherwise, np.broadcast(a, b).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized beta distribution.


numpy.random.Generator.binomial method   random.Generator.binomial(n, p, size=None)

Draw samples from a binomial distribution. Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval [0,1]. (n may be input as a float, but it is truncated to an integer in use)  Parameters

nint or array_like of ints

Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.
pfloat or array_like of floats

Parameter of the distribution, >= 0 and <=1.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if n and p are both scalars. Otherwise, np.broadcast(n, p).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.      See also  scipy.stats.binom

probability density function, distribution or cumulative density function, etc.    Notes The probability density for the binomial distribution is  \[P(N) = \binom{n}{N}p^N(1-p)^{n-N},\] where \(n\) is the number of trials, \(p\) is the probability of success, and \(N\) is the number of successes. When estimating the standard error of a proportion in a population by using a random sample, the normal distribution works well unless the product p*n <=5, where p = population proportion estimate, and n = number of samples, in which case the binomial distribution is used instead. For example, a sample of 15 people shows 4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so the binomial distribution should be used in this case. References  1
Dalgaard, Peter, “Introductory Statistics with R”, Springer-Verlag, 2002.  2
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.  3
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.  4
Weisstein, Eric W. “Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html  5
Wikipedia, “Binomial distribution”, https://en.wikipedia.org/wiki/Binomial_distribution   Examples Draw samples from the distribution: >>> rng = np.random.default_rng()
>>> n, p = 10, .5  # number of trials, probability of each trial
>>> s = rng.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.
 A real world example. A company drills 9 wild-cat oil exploration wells, each with an estimated probability of success of 0.1. All nine wells fail. What is the probability of that happening? Let’s do 20,000 trials of the model, and count the number that generate zero positive results. >>> sum(rng.binomial(9, 0.1, 20000) == 0)/20000.
# answer = 0.38885, or 39%.


numpy.random.Generator.bit_generator attribute   random.Generator.bit_generator

Gets the bit generator instance used by the generator  Returns

bit_generatorBitGenerator

The bit generator instance used by the generator


numpy.random.Generator.bytes method   random.Generator.bytes(length)

Return random bytes.  Parameters

lengthint

Number of random bytes.    Returns

outbytes

String of length length.     Examples >>> np.random.default_rng().bytes(10)
b'\xfeC\x9b\x86\x17\xf2\xa1\xafcp' # random


numpy.random.Generator.chisquare method   random.Generator.chisquare(df, size=None)

Draw samples from a chi-square distribution. When df independent random variables, each with standard normal distributions (mean 0, variance 1), are squared and summed, the resulting distribution is chi-square (see Notes). This distribution is often used in hypothesis testing.  Parameters

dffloat or array_like of floats

Number of degrees of freedom, must be > 0.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if df is a scalar. Otherwise, np.array(df).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized chi-square distribution.    Raises
 ValueError

When df <= 0 or when an inappropriate size (e.g. size=-1) is given.     Notes The variable obtained by summing the squares of df independent, standard normally distributed random variables:  \[Q = \sum_{i=0}^{\mathtt{df}} X^2_i\] is chi-square distributed, denoted  \[Q \sim \chi^2_k.\] The probability density function of the chi-squared distribution is  \[p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)} x^{k/2 - 1} e^{-x/2},\] where \(\Gamma\) is the gamma function,  \[\Gamma(x) = \int_0^{-\infty} t^{x - 1} e^{-t} dt.\] References  1
NIST “Engineering Statistics Handbook” https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm   Examples >>> np.random.default_rng().chisquare(2,4)
array([ 1.89920014,  9.00867716,  3.13710533,  5.62318272]) # random


numpy.random.Generator.choice method   random.Generator.choice(a, size=None, replace=True, p=None, axis=0, shuffle=True)

Generates a random sample from a given array  Parameters

a{array_like, int}

If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated from np.arange(a).
size{int, tuple[int]}, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn from the 1-d a. If a has more than one dimension, the size shape will be inserted into the axis dimension, so the output ndim will be a.ndim - 1 +
len(size). Default is None, in which case a single value is returned.
replacebool, optional

Whether the sample is with or without replacement. Default is True, meaning that a value of a can be selected multiple times.
p1-D array_like, optional

The probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in a.
axisint, optional

The axis along which the selection is performed. The default, 0, selects by row.
shufflebool, optional

Whether the sample is shuffled when sampling without replacement. Default is True, False provides a speedup.    Returns

samplessingle item or ndarray

The generated random samples    Raises
 ValueError

If a is an int and less than zero, if p is not 1-dimensional, if a is array-like with a size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size.      See also
integers, shuffle, permutation

  Notes Setting user-specified probabilities through p uses a more general but less efficient sampler than the default. The general sampler produces a different sample than the optimized sampler even if each element of p is 1 / len(a). Examples Generate a uniform random sample from np.arange(5) of size 3: >>> rng = np.random.default_rng()
>>> rng.choice(5, 3)
array([0, 3, 4]) # random
>>> #This is equivalent to rng.integers(0,5,3)
 Generate a non-uniform random sample from np.arange(5) of size 3: >>> rng.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0]) # random
 Generate a uniform random sample from np.arange(5) of size 3 without replacement: >>> rng.choice(5, 3, replace=False)
array([3,1,0]) # random
>>> #This is equivalent to rng.permutation(np.arange(5))[:3]
 Generate a uniform random sample from a 2-D array along the first axis (the default), without replacement: >>> rng.choice([[0, 1, 2], [3, 4, 5], [6, 7, 8]], 2, replace=False)
array([[3, 4, 5], # random
       [0, 1, 2]])
 Generate a non-uniform random sample from np.arange(5) of size 3 without replacement: >>> rng.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
array([2, 3, 0]) # random
 Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance: >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> rng.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random
      dtype='<U11')


numpy.random.Generator.dirichlet method   random.Generator.dirichlet(alpha, size=None)

Draw samples from the Dirichlet distribution. Draw size samples of dimension k from a Dirichlet distribution. A Dirichlet-distributed random variable can be seen as a multivariate generalization of a Beta distribution. The Dirichlet distribution is a conjugate prior of a multinomial distribution in Bayesian inference.  Parameters

alphasequence of floats, length k

Parameter of the distribution (length k for sample of length k).
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n), then m * n * k samples are drawn. Default is None, in which case a vector of length k is returned.    Returns

samplesndarray,

The drawn samples, of shape (size, k).    Raises
 ValueError

If any value in alpha is less than or equal to zero     Notes The Dirichlet distribution is a distribution over vectors \(x\) that fulfil the conditions \(x_i>0\) and \(\sum_{i=1}^k x_i = 1\). The probability density function \(p\) of a Dirichlet-distributed random vector \(X\) is proportional to  \[p(x) \propto \prod_{i=1}^{k}{x^{\alpha_i-1}_i},\] where \(\alpha\) is a vector containing the positive concentration parameters. The method uses the following property for computation: let \(Y\) be a random vector which has components that follow a standard gamma distribution, then \(X = \frac{1}{\sum_{i=1}^k{Y_i}} Y\) is Dirichlet-distributed References  1
David McKay, “Information Theory, Inference and Learning Algorithms,” chapter 23, http://www.inference.org.uk/mackay/itila/  2
Wikipedia, “Dirichlet distribution”, https://en.wikipedia.org/wiki/Dirichlet_distribution   Examples Taking an example cited in Wikipedia, this distribution can be used if one wanted to cut strings (each of initial length 1.0) into K pieces with different lengths, where each piece had, on average, a designated average length, but allowing some variation in the relative sizes of the pieces. >>> s = np.random.default_rng().dirichlet((10, 5, 3), 20).transpose()
 >>> import matplotlib.pyplot as plt
>>> plt.barh(range(20), s[0])
>>> plt.barh(range(20), s[1], left=s[0], color='g')
>>> plt.barh(range(20), s[2], left=s[0]+s[1], color='r')
>>> plt.title("Lengths of Strings")


numpy.random.Generator.exponential method   random.Generator.exponential(scale=1.0, size=None)

Draw samples from an exponential distribution. Its probability density function is  \[f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}),\] for x > 0 and 0 elsewhere. \(\beta\) is the scale parameter, which is the inverse of the rate parameter \(\lambda = 1/\beta\). The rate parameter is an alternative, widely used parameterization of the exponential distribution [3]. The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms [1], or the time between page requests to Wikipedia [2].  Parameters

scalefloat or array_like of floats

The scale parameter, \(\beta = 1/\lambda\). Must be non-negative.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if scale is a scalar. Otherwise, np.array(scale).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized exponential distribution.     References  1
Peyton Z. Peebles Jr., “Probability, Random Variables and Random Signal Principles”, 4th ed, 2001, p. 57.  2
Wikipedia, “Poisson process”, https://en.wikipedia.org/wiki/Poisson_process  3
Wikipedia, “Exponential distribution”, https://en.wikipedia.org/wiki/Exponential_distribution


numpy.random.Generator.f method   random.Generator.f(dfnum, dfden, size=None)

Draw samples from an F distribution. Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in numerator) and dfden (degrees of freedom in denominator), where both parameters must be greater than zero. The random variate of the F distribution (also known as the Fisher distribution) is a continuous probability distribution that arises in ANOVA tests, and is the ratio of two chi-square variates.  Parameters

dfnumfloat or array_like of floats

Degrees of freedom in numerator, must be > 0.
dfdenfloat or array_like of float

Degrees of freedom in denominator, must be > 0.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if dfnum and dfden are both scalars. Otherwise, np.broadcast(dfnum, dfden).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized Fisher distribution.      See also  scipy.stats.f

probability density function, distribution or cumulative density function, etc.    Notes The F statistic is used to compare in-group variances to between-group variances. Calculating the distribution depends on the sampling, and so it is a function of the respective degrees of freedom in the problem. The variable dfnum is the number of samples minus one, the between-groups degrees of freedom, while dfden is the within-groups degrees of freedom, the sum of the number of samples in each group minus the number of groups. References  1
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.  2
Wikipedia, “F-distribution”, https://en.wikipedia.org/wiki/F-distribution   Examples An example from Glantz[1], pp 47-40: Two groups, children of diabetics (25 people) and children from people without diabetes (25 controls). Fasting blood glucose was measured, case group had a mean value of 86.1, controls had a mean value of 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these data consistent with the null hypothesis that the parents diabetic status does not affect their children’s blood glucose levels? Calculating the F statistic from the data gives a value of 36.01. Draw samples from the distribution: >>> dfnum = 1. # between group degrees of freedom
>>> dfden = 48. # within groups degrees of freedom
>>> s = np.random.default_rng().f(dfnum, dfden, 1000)
 The lower bound for the top 1% of the samples is : >>> np.sort(s)[-10]
7.61988120985 # random
 So there is about a 1% chance that the F statistic will exceed 7.62, the measured value is 36, so the null hypothesis is rejected at the 1% level.


numpy.random.Generator.gamma method   random.Generator.gamma(shape, scale=1.0, size=None)

Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale (sometimes designated “theta”), where both parameters are > 0.  Parameters

shapefloat or array_like of floats

The shape of the gamma distribution. Must be non-negative.
scalefloat or array_like of floats, optional

The scale of the gamma distribution. Must be non-negative. Default is equal to 1.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if shape and scale are both scalars. Otherwise, np.broadcast(shape, scale).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized gamma distribution.      See also  scipy.stats.gamma

probability density function, distribution or cumulative density function, etc.    Notes The probability density for the Gamma distribution is  \[p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},\] where \(k\) is the shape and \(\theta\) the scale, and \(\Gamma\) is the Gamma function. The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant. References  1
Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html  2
Wikipedia, “Gamma distribution”, https://en.wikipedia.org/wiki/Gamma_distribution   Examples Draw samples from the distribution: >>> shape, scale = 2., 2.  # mean=4, std=2*sqrt(2)
>>> s = np.random.default_rng().gamma(shape, scale, 1000)
 Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt
>>> import scipy.special as sps
>>> count, bins, ignored = plt.hist(s, 50, density=True)
>>> y = bins**(shape-1)*(np.exp(-bins/scale) /
...                      (sps.gamma(shape)*scale**shape))
>>> plt.plot(bins, y, linewidth=2, color='r')
>>> plt.show()


numpy.random.Generator.geometric method   random.Generator.geometric(p, size=None)

Draw samples from the geometric distribution. Bernoulli trials are experiments with one of two outcomes: success or failure (an example of such an experiment is flipping a coin). The geometric distribution models the number of trials that must be run in order to achieve success. It is therefore supported on the positive integers, k = 1, 2, .... The probability mass function of the geometric distribution is  \[f(k) = (1 - p)^{k - 1} p\] where p is the probability of success of an individual trial.  Parameters

pfloat or array_like of floats

The probability of success of an individual trial.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if p is a scalar. Otherwise, np.array(p).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized geometric distribution.     Examples Draw ten thousand values from the geometric distribution, with the probability of an individual success equal to 0.35: >>> z = np.random.default_rng().geometric(p=0.35, size=10000)
 How many trials succeeded after a single run? >>> (z == 1).sum() / 10000.
0.34889999999999999 # random


numpy.random.Generator.gumbel method   random.Generator.gumbel(loc=0.0, scale=1.0, size=None)

Draw samples from a Gumbel distribution. Draw samples from a Gumbel distribution with specified location and scale. For more information on the Gumbel distribution, see Notes and References below.  Parameters

locfloat or array_like of floats, optional

The location of the mode of the distribution. Default is 0.
scalefloat or array_like of floats, optional

The scale parameter of the distribution. Default is 1. Must be non- negative.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized Gumbel distribution.      See also  scipy.stats.gumbel_l
scipy.stats.gumbel_r
scipy.stats.genextreme
weibull
  Notes The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value Type I) distribution is one of a class of Generalized Extreme Value (GEV) distributions used in modeling extreme value problems. The Gumbel is a special case of the Extreme Value Type I distribution for maximums from distributions with “exponential-like” tails. The probability density for the Gumbel distribution is  \[p(x) = \frac{e^{-(x - \mu)/ \beta}}{\beta} e^{ -e^{-(x - \mu)/ \beta}},\] where \(\mu\) is the mode, a location parameter, and \(\beta\) is the scale parameter. The Gumbel (named for German mathematician Emil Julius Gumbel) was used very early in the hydrology literature, for modeling the occurrence of flood events. It is also used for modeling maximum wind speed and rainfall rates. It is a “fat-tailed” distribution - the probability of an event in the tail of the distribution is larger than if one used a Gaussian, hence the surprisingly frequent occurrence of 100-year floods. Floods were initially modeled as a Gaussian process, which underestimated the frequency of extreme events. It is one of a class of extreme value distributions, the Generalized Extreme Value (GEV) distributions, which also includes the Weibull and Frechet. The function has a mean of \(\mu + 0.57721\beta\) and a variance of \(\frac{\pi^2}{6}\beta^2\). References  1
Gumbel, E. J., “Statistics of Extremes,” New York: Columbia University Press, 1958.  2
Reiss, R.-D. and Thomas, M., “Statistical Analysis of Extreme Values from Insurance, Finance, Hydrology and Other Fields,” Basel: Birkhauser Verlag, 2001.   Examples Draw samples from the distribution: >>> rng = np.random.default_rng()
>>> mu, beta = 0, 0.1 # location and scale
>>> s = rng.gumbel(mu, beta, 1000)
 Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
...          * np.exp( -np.exp( -(bins - mu) /beta) ),
...          linewidth=2, color='r')
>>> plt.show()
    Show how an extreme value distribution can arise from a Gaussian process and compare to a Gaussian: >>> means = []
>>> maxima = []
>>> for i in range(0,1000) :
...    a = rng.normal(mu, beta, 1000)
...    means.append(a.mean())
...    maxima.append(a.max())
>>> count, bins, ignored = plt.hist(maxima, 30, density=True)
>>> beta = np.std(maxima) * np.sqrt(6) / np.pi
>>> mu = np.mean(maxima) - 0.57721*beta
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
...          * np.exp(-np.exp(-(bins - mu)/beta)),
...          linewidth=2, color='r')
>>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))
...          * np.exp(-(bins - mu)**2 / (2 * beta**2)),
...          linewidth=2, color='g')
>>> plt.show()


numpy.random.Generator.hypergeometric method   random.Generator.hypergeometric(ngood, nbad, nsample, size=None)

Draw samples from a Hypergeometric distribution. Samples are drawn from a hypergeometric distribution with specified parameters, ngood (ways to make a good selection), nbad (ways to make a bad selection), and nsample (number of items sampled, which is less than or equal to the sum ngood + nbad).  Parameters

ngoodint or array_like of ints

Number of ways to make a good selection. Must be nonnegative and less than 10**9.
nbadint or array_like of ints

Number of ways to make a bad selection. Must be nonnegative and less than 10**9.
nsampleint or array_like of ints

Number of items sampled. Must be nonnegative and less than ngood + nbad.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if ngood, nbad, and nsample are all scalars. Otherwise, np.broadcast(ngood, nbad, nsample).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized hypergeometric distribution. Each sample is the number of good items within a randomly selected subset of size nsample taken from a set of ngood good items and nbad bad items.      See also  multivariate_hypergeometric

Draw samples from the multivariate hypergeometric distribution.  scipy.stats.hypergeom

probability density function, distribution or cumulative density function, etc.    Notes The probability density for the Hypergeometric distribution is  \[P(x) = \frac{\binom{g}{x}\binom{b}{n-x}}{\binom{g+b}{n}},\] where \(0 \le x \le n\) and \(n-b \le x \le g\) for P(x) the probability of x good results in the drawn sample, g = ngood, b = nbad, and n = nsample. Consider an urn with black and white marbles in it, ngood of them are black and nbad are white. If you draw nsample balls without replacement, then the hypergeometric distribution describes the distribution of black balls in the drawn sample. Note that this distribution is very similar to the binomial distribution, except that in this case, samples are drawn without replacement, whereas in the Binomial case samples are drawn with replacement (or the sample space is infinite). As the sample space becomes large, this distribution approaches the binomial. The arguments ngood and nbad each must be less than 10**9. For extremely large arguments, the algorithm that is used to compute the samples [4] breaks down because of loss of precision in floating point calculations. For such large values, if nsample is not also large, the distribution can be approximated with the binomial distribution, binomial(n=nsample, p=ngood/(ngood + nbad)). References  1
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.  2
Weisstein, Eric W. “Hypergeometric Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/HypergeometricDistribution.html  3
Wikipedia, “Hypergeometric distribution”, https://en.wikipedia.org/wiki/Hypergeometric_distribution  4
Stadlober, Ernst, “The ratio of uniforms approach for generating discrete random variates”, Journal of Computational and Applied Mathematics, 31, pp. 181-189 (1990).   Examples Draw samples from the distribution: >>> rng = np.random.default_rng()
>>> ngood, nbad, nsamp = 100, 2, 10
# number of good, number of bad, and number of samples
>>> s = rng.hypergeometric(ngood, nbad, nsamp, 1000)
>>> from matplotlib.pyplot import hist
>>> hist(s)
#   note that it is very unlikely to grab both bad items
 Suppose you have an urn with 15 white and 15 black marbles. If you pull 15 marbles at random, how likely is it that 12 or more of them are one color? >>> s = rng.hypergeometric(15, 15, 15, 100000)
>>> sum(s>=12)/100000. + sum(s<=3)/100000.
#   answer = 0.003 ... pretty unlikely!


numpy.random.Generator.integers method   random.Generator.integers(low, high=None, size=None, dtype=np.int64, endpoint=False)

Return random integers from low (inclusive) to high (exclusive), or if endpoint=True, low (inclusive) to high (inclusive). Replaces RandomState.randint (with endpoint=False) and RandomState.random_integers (with endpoint=True) Return random integers from the “discrete uniform” distribution of the specified dtype. If high is None (the default), then results are from 0 to low.  Parameters

lowint or array-like of ints

Lowest (signed) integers to be drawn from the distribution (unless high=None, in which case this parameter is 0 and this value is used for high).
highint or array-like of ints, optional

If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if high=None). If array-like, must contain integer values
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
dtypedtype, optional

Desired dtype of the result. Byteorder must be native. The default value is np.int64.
endpointbool, optional

If true, sample from the interval [low, high] instead of the default [low, high) Defaults to False    Returns

outint or ndarray of ints

size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.     Notes When using broadcasting with uint64 dtypes, the maximum value (2**64) cannot be represented as a standard integer type. The high array (or low if high is None) must have object dtype, e.g., array([2**64]). References  1
Daniel Lemire., “Fast Random Integer Generation in an Interval”, ACM Transactions on Modeling and Computer Simulation 29 (1), 2019, http://arxiv.org/abs/1805.10941.   Examples >>> rng = np.random.default_rng()
>>> rng.integers(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])  # random
>>> rng.integers(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
 Generate a 2 x 4 array of ints between 0 and 4, inclusive: >>> rng.integers(5, size=(2, 4))
array([[4, 0, 2, 1],
       [3, 2, 2, 0]])  # random
 Generate a 1 x 3 array with 3 different upper bounds >>> rng.integers(1, [3, 5, 10])
array([2, 2, 9])  # random
 Generate a 1 by 3 array with 3 different lower bounds >>> rng.integers([1, 5, 7], 10)
array([9, 8, 7])  # random
 Generate a 2 by 4 array using broadcasting with dtype of uint8 >>> rng.integers([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
array([[ 8,  6,  9,  7],
       [ 1, 16,  9, 12]], dtype=uint8)  # random


numpy.random.Generator.laplace method   random.Generator.laplace(loc=0.0, scale=1.0, size=None)

Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay). The Laplace distribution is similar to the Gaussian/normal distribution, but is sharper at the peak and has fatter tails. It represents the difference between two independent, identically distributed exponential random variables.  Parameters

locfloat or array_like of floats, optional

The position, \(\mu\), of the distribution peak. Default is 0.
scalefloat or array_like of floats, optional

\(\lambda\), the exponential decay. Default is 1. Must be non- negative.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized Laplace distribution.     Notes It has the probability density function  \[f(x; \mu, \lambda) = \frac{1}{2\lambda} \exp\left(-\frac{|x - \mu|}{\lambda}\right).\] The first law of Laplace, from 1774, states that the frequency of an error can be expressed as an exponential function of the absolute magnitude of the error, which leads to the Laplace distribution. For many problems in economics and health sciences, this distribution seems to model the data better than the standard Gaussian distribution. References  1
Abramowitz, M. and Stegun, I. A. (Eds.). “Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables, 9th printing,” New York: Dover, 1972.  2
Kotz, Samuel, et. al. “The Laplace Distribution and Generalizations, ” Birkhauser, 2001.  3
Weisstein, Eric W. “Laplace Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LaplaceDistribution.html  4
Wikipedia, “Laplace distribution”, https://en.wikipedia.org/wiki/Laplace_distribution   Examples Draw samples from the distribution >>> loc, scale = 0., 1.
>>> s = np.random.default_rng().laplace(loc, scale, 1000)
 Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> x = np.arange(-8., 8., .01)
>>> pdf = np.exp(-abs(x-loc)/scale)/(2.*scale)
>>> plt.plot(x, pdf)
 Plot Gaussian for comparison: >>> g = (1/(scale * np.sqrt(2 * np.pi)) *
...      np.exp(-(x - loc)**2 / (2 * scale**2)))
>>> plt.plot(x,g)


numpy.random.Generator.logistic method   random.Generator.logistic(loc=0.0, scale=1.0, size=None)

Draw samples from a logistic distribution. Samples are drawn from a logistic distribution with specified parameters, loc (location or mean, also median), and scale (>0).  Parameters

locfloat or array_like of floats, optional

Parameter of the distribution. Default is 0.
scalefloat or array_like of floats, optional

Parameter of the distribution. Must be non-negative. Default is 1.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized logistic distribution.      See also  scipy.stats.logistic

probability density function, distribution or cumulative density function, etc.    Notes The probability density for the Logistic distribution is  \[P(x) = P(x) = \frac{e^{-(x-\mu)/s}}{s(1+e^{-(x-\mu)/s})^2},\] where \(\mu\) = location and \(s\) = scale. The Logistic distribution is used in Extreme Value problems where it can act as a mixture of Gumbel distributions, in Epidemiology, and by the World Chess Federation (FIDE) where it is used in the Elo ranking system, assuming the performance of each player is a logistically distributed random variable. References  1
Reiss, R.-D. and Thomas M. (2001), “Statistical Analysis of Extreme Values, from Insurance, Finance, Hydrology and Other Fields,” Birkhauser Verlag, Basel, pp 132-133.  2
Weisstein, Eric W. “Logistic Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LogisticDistribution.html  3
Wikipedia, “Logistic-distribution”, https://en.wikipedia.org/wiki/Logistic_distribution   Examples Draw samples from the distribution: >>> loc, scale = 10, 1
>>> s = np.random.default_rng().logistic(loc, scale, 10000)
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, bins=50)
 # plot against distribution >>> def logist(x, loc, scale):
...     return np.exp((loc-x)/scale)/(scale*(1+np.exp((loc-x)/scale))**2)
>>> lgst_val = logist(bins, loc, scale)
>>> plt.plot(bins, lgst_val * count.max() / lgst_val.max())
>>> plt.show()


numpy.random.Generator.lognormal method   random.Generator.lognormal(mean=0.0, sigma=1.0, size=None)

Draw samples from a log-normal distribution. Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from.  Parameters

meanfloat or array_like of floats, optional

Mean value of the underlying normal distribution. Default is 0.
sigmafloat or array_like of floats, optional

Standard deviation of the underlying normal distribution. Must be non-negative. Default is 1.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if mean and sigma are both scalars. Otherwise, np.broadcast(mean, sigma).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized log-normal distribution.      See also  scipy.stats.lognorm

probability density function, distribution, cumulative density function, etc.    Notes A variable x has a log-normal distribution if log(x) is normally distributed. The probability density function for the log-normal distribution is:  \[p(x) = \frac{1}{\sigma x \sqrt{2\pi}} e^{(-\frac{(ln(x)-\mu)^2}{2\sigma^2})}\] where \(\mu\) is the mean and \(\sigma\) is the standard deviation of the normally distributed logarithm of the variable. A log-normal distribution results if a random variable is the product of a large number of independent, identically-distributed variables in the same way that a normal distribution results if the variable is the sum of a large number of independent, identically-distributed variables. References  1
Limpert, E., Stahel, W. A., and Abbt, M., “Log-normal Distributions across the Sciences: Keys and Clues,” BioScience, Vol. 51, No. 5, May, 2001. https://stat.ethz.ch/~stahel/lognormal/bioscience.pdf  2
Reiss, R.D. and Thomas, M., “Statistical Analysis of Extreme Values,” Basel: Birkhauser Verlag, 2001, pp. 31-32.   Examples Draw samples from the distribution: >>> rng = np.random.default_rng()
>>> mu, sigma = 3., 1. # mean and standard deviation
>>> s = rng.lognormal(mu, sigma, 1000)
 Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 100, density=True, align='mid')
 >>> x = np.linspace(min(bins), max(bins), 10000)
>>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
...        / (x * sigma * np.sqrt(2 * np.pi)))
 >>> plt.plot(x, pdf, linewidth=2, color='r')
>>> plt.axis('tight')
>>> plt.show()
    Demonstrate that taking the products of random samples from a uniform distribution can be fit well by a log-normal probability density function. >>> # Generate a thousand samples: each is the product of 100 random
>>> # values, drawn from a normal distribution.
>>> rng = rng
>>> b = []
>>> for i in range(1000):
...    a = 10. + rng.standard_normal(100)
...    b.append(np.product(a))
 >>> b = np.array(b) / np.min(b) # scale values to be positive
>>> count, bins, ignored = plt.hist(b, 100, density=True, align='mid')
>>> sigma = np.std(np.log(b))
>>> mu = np.mean(np.log(b))
 >>> x = np.linspace(min(bins), max(bins), 10000)
>>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
...        / (x * sigma * np.sqrt(2 * np.pi)))
 >>> plt.plot(x, pdf, color='r', linewidth=2)
>>> plt.show()


numpy.random.Generator.logseries method   random.Generator.logseries(p, size=None)

Draw samples from a logarithmic series distribution. Samples are drawn from a log series distribution with specified shape parameter, 0 < p < 1.  Parameters

pfloat or array_like of floats

Shape parameter for the distribution. Must be in the range (0, 1).
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if p is a scalar. Otherwise, np.array(p).size samples are drawn.    Returns

outndarray or scalar

Drawn samples from the parameterized logarithmic series distribution.      See also  scipy.stats.logser

probability density function, distribution or cumulative density function, etc.    Notes The probability mass function for the Log Series distribution is  \[P(k) = \frac{-p^k}{k \ln(1-p)},\] where p = probability. The log series distribution is frequently used to represent species richness and occurrence, first proposed by Fisher, Corbet, and Williams in 1943 [2]. It may also be used to model the numbers of occupants seen in cars [3]. References  1
Buzas, Martin A.; Culver, Stephen J., Understanding regional species diversity through the log series distribution of occurrences: BIODIVERSITY RESEARCH Diversity & Distributions, Volume 5, Number 5, September 1999 , pp. 187-195(9).  2
Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The relation between the number of species and the number of individuals in a random sample of an animal population. Journal of Animal Ecology, 12:42-58.  3
D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small Data Sets, CRC Press, 1994.  4
Wikipedia, “Logarithmic distribution”, https://en.wikipedia.org/wiki/Logarithmic_distribution   Examples Draw samples from the distribution: >>> a = .6
>>> s = np.random.default_rng().logseries(a, 10000)
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s)
 # plot against distribution >>> def logseries(k, p):
...     return -p**k/(k*np.log(1-p))
>>> plt.plot(bins, logseries(bins, a) * count.max()/
...          logseries(bins, a).max(), 'r')
>>> plt.show()


numpy.random.Generator.multinomial method   random.Generator.multinomial(n, pvals, size=None)

Draw samples from a multinomial distribution. The multinomial distribution is a multivariate generalization of the binomial distribution. Take an experiment with one of p possible outcomes. An example of such an experiment is throwing a dice, where the outcome can be 1 through 6. Each sample drawn from the distribution represents n such experiments. Its values, X_i = [X_0, X_1, ..., X_p], represent the number of times the outcome was i.  Parameters

nint or array-like of ints

Number of experiments.
pvalsarray-like of floats

Probabilities of each of the p different outcomes with shape (k0, k1, ..., kn, p). Each element pvals[i,j,...,:] must sum to 1 (however, the last element is always assumed to account for the remaining probability, as long as sum(pvals[..., :-1], axis=-1) <= 1.0. Must have at least 1 dimension where pvals.shape[-1] > 0.
sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn each with p elements. Default is None where the output size is determined by the broadcast shape of n and all by the final dimension of pvals, which is denoted as b=(b0, b1, ..., bq). If size is not None, then it must be compatible with the broadcast shape b. Specifically, size must have q or more elements and size[-(q-j):] must equal bj.    Returns

outndarray

The drawn samples, of shape size, if provided. When size is provided, the output shape is size + (p,) If not specified, the shape is determined by the broadcast shape of n and pvals, (b0, b1, ..., bq) augmented with the dimension of the multinomial, p, so that that output shape is (b0, b1, ..., bq, p). Each entry out[i,j,...,:] is a p-dimensional value drawn from the distribution.     Examples Throw a dice 20 times: >>> rng = np.random.default_rng()
>>> rng.multinomial(20, [1/6.]*6, size=1)
array([[4, 1, 7, 5, 2, 1]])  # random
 It landed 4 times on 1, once on 2, etc. Now, throw the dice 20 times, and 20 times again: >>> rng.multinomial(20, [1/6.]*6, size=2)
array([[3, 4, 3, 3, 4, 3],
       [2, 4, 3, 4, 0, 7]])  # random
 For the first run, we threw 3 times 1, 4 times 2, etc. For the second, we threw 2 times 1, 4 times 2, etc. Now, do one experiment throwing the dice 10 time, and 10 times again, and another throwing the dice 20 times, and 20 times again: >>> rng.multinomial([[10], [20]], [1/6.]*6, size=(2, 2))
array([[[2, 4, 0, 1, 2, 1],
        [1, 3, 0, 3, 1, 2]],
       [[1, 4, 4, 4, 4, 3],
        [3, 3, 2, 5, 5, 2]]])  # random
 The first array shows the outcomes of throwing the dice 10 times, and the second shows the outcomes from throwing the dice 20 times. A loaded die is more likely to land on number 6: >>> rng.multinomial(100, [1/7.]*5 + [2/7.])
array([11, 16, 14, 17, 16, 26])  # random
 Simulate 10 throws of a 4-sided die and 20 throws of a 6-sided die >>> rng.multinomial([10, 20],[[1/4]*4 + [0]*2, [1/6]*6])
array([[2, 1, 4, 3, 0, 0],
       [3, 3, 3, 6, 1, 4]], dtype=int64)  # random
 Generate categorical random variates from two categories where the first has 3 outcomes and the second has 2. >>> rng.multinomial(1, [[.1, .5, .4 ], [.3, .7, .0]])
array([[0, 0, 1],
       [0, 1, 0]], dtype=int64)  # random
 argmax(axis=-1) is then used to return the categories. >>> pvals = [[.1, .5, .4 ], [.3, .7, .0]]
>>> rvs = rng.multinomial(1, pvals, size=(4,2))
>>> rvs.argmax(axis=-1)
array([[0, 1],
       [2, 0],
       [2, 1],
       [2, 0]], dtype=int64)  # random
 The same output dimension can be produced using broadcasting. >>> rvs = rng.multinomial([[1]] * 4, pvals)
>>> rvs.argmax(axis=-1)
array([[0, 1],
       [2, 0],
       [2, 1],
       [2, 0]], dtype=int64)  # random
 The probability inputs should be normalized. As an implementation detail, the value of the last entry is ignored and assumed to take up any leftover probability mass, but this should not be relied on. A biased coin which has twice as much weight on one side as on the other should be sampled like so: >>> rng.multinomial(100, [1.0 / 3, 2.0 / 3])  # RIGHT
array([38, 62])  # random
 not like: >>> rng.multinomial(100, [1.0, 2.0])  # WRONG
Traceback (most recent call last):
ValueError: pvals < 0, pvals > 1 or pvals contains NaNs