doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.polynomial.legendre.legx polynomial.legendre.legx = 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.reference.generated.numpy.polynomial.legendre.legx
numpy.polynomial.legendre.legzero polynomial.legendre.legzero = 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.reference.generated.numpy.polynomial.legendre.legzero
numpy.polynomial.legendre.poly2leg polynomial.legendre.poly2leg(pol)[source] Convert a polynomial to a Legendre series. Convert an array representing the coefficients of a polynomial (relative to the “standard” basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Legendre series, ordered from lowest to highest degree. Parameters polarray_like 1-D array containing the polynomial coefficients Returns cndarray 1-D array containing the coefficients of the equivalent Legendre series. See also leg2poly Notes The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples >>> from numpy import polynomial as P >>> p = P.Polynomial(np.arange(4)) >>> p Polynomial([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1]) >>> c = P.Legendre(P.legendre.poly2leg(p.coef)) >>> c Legendre([ 1. , 3.25, 1. , 0.75], domain=[-1, 1], window=[-1, 1]) # may vary
numpy.reference.generated.numpy.polynomial.legendre.poly2leg
numpy.polynomial.polynomial.polyadd polynomial.polynomial.polyadd(c1, c2)[source] Add one polynomial to another. Returns the sum 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 The coefficient array representing their sum. See also polysub, polymulx, polymul, polydiv, polypow Examples >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> sum = P.polyadd(c1,c2); sum array([4., 4., 4.]) >>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2) 28.0
numpy.reference.generated.numpy.polynomial.polynomial.polyadd
numpy.polynomial.polynomial.polycompanion polynomial.polynomial.polycompanion(c)[source] Return the companion matrix of c. The companion matrix for power series cannot be made symmetric by scaling the basis, so this function differs from those for the orthogonal polynomials. Parameters carray_like 1-D array of polynomial coefficients ordered from low to high degree. Returns matndarray Companion matrix of dimensions (deg, deg). Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.polynomial.polycompanion
numpy.polynomial.polynomial.polyder polynomial.polynomial.polyder(c, m=1, scl=1, axis=0)[source] Differentiate a polynomial. Returns the polynomial coefficients c differentiated m times along axis. At each iteration the result is multiplied by scl (the scaling factor is for use in a linear change of variable). The argument c is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the polynomial 1 + 2*x + 3*x**2 while [[1,2],[1,2]] represents 1 + 1*x + 2*y + 2*x*y if axis=0 is x and axis=1 is y. Parameters carray_like Array of polynomial coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. mint, optional Number of derivatives taken, must be non-negative. (Default: 1) sclscalar, optional Each differentiation is multiplied by scl. The end result is multiplication by scl**m. This is for use in a linear change of variable. (Default: 1) axisint, optional Axis over which the derivative is taken. (Default: 0). New in version 1.7.0. Returns derndarray Polynomial coefficients of the derivative. See also polyint Examples >>> from numpy.polynomial import polynomial as P >>> c = (1,2,3,4) # 1 + 2x + 3x**2 + 4x**3 >>> P.polyder(c) # (d/dx)(c) = 2 + 6x + 12x**2 array([ 2., 6., 12.]) >>> P.polyder(c,3) # (d**3/dx**3)(c) = 24 array([24.]) >>> P.polyder(c,scl=-1) # (d/d(-x))(c) = -2 - 6x - 12x**2 array([ -2., -6., -12.]) >>> P.polyder(c,2,-1) # (d**2/d(-x)**2)(c) = 6 + 24x array([ 6., 24.])
numpy.reference.generated.numpy.polynomial.polynomial.polyder
numpy.polynomial.polynomial.polydiv polynomial.polynomial.polydiv(c1, c2)[source] Divide one polynomial by another. Returns the quotient-with-remainder of two polynomials c1 / c2. The arguments are sequences of coefficients, from lowest order term to highest, e.g., [1,2,3] represents 1 + 2*x + 3*x**2. Parameters c1, c2array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns [quo, rem]ndarrays Of coefficient series representing the quotient and remainder. See also polyadd, polysub, polymulx, polymul, polypow Examples >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polydiv(c1,c2) (array([3.]), array([-8., -4.])) >>> P.polydiv(c2,c1) (array([ 0.33333333]), array([ 2.66666667, 1.33333333])) # may vary
numpy.reference.generated.numpy.polynomial.polynomial.polydiv
numpy.polynomial.polynomial.polydomain polynomial.polynomial.polydomain = array([-1, 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.reference.generated.numpy.polynomial.polynomial.polydomain
numpy.polynomial.polynomial.polyfit polynomial.polynomial.polyfit(x, y, deg, rcond=None, full=False, w=None)[source] Least-squares fit of a polynomial to data. Return the coefficients of a polynomial of degree deg that is the least squares fit to the data values y given at points x. If y is 1-D the returned coefficients will also be 1-D. If y is 2-D multiple fits are done, one for each column of y, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form \[p(x) = c_0 + c_1 * x + ... + c_n * x^n,\] where n is deg. Parameters xarray_like, shape (M,) x-coordinates of the M sample (data) points (x[i], y[i]). yarray_like, shape (M,) or (M, K) y-coordinates of the sample points. Several sets of sample points sharing the same x-coordinates can be (independently) fit with one call to polyfit by passing in for y a 2-D array that contains one data set per column. degint or 1-D array_like Degree(s) of the fitting polynomials. If deg is a single integer all terms up to and including the deg’th term are included in the fit. For NumPy versions >= 1.11.0 a list of integers specifying the degrees of the terms to include may be used instead. rcondfloat, optional Relative condition number of the fit. Singular values smaller than rcond, relative to the largest singular value, will be ignored. The default value is len(x)*eps, where eps is the relative precision of the platform’s float type, about 2e-16 in most cases. fullbool, optional Switch determining the nature of the return value. When False (the default) just the coefficients are returned; when True, diagnostic information from the singular value decomposition (used to solve the fit’s matrix equation) is also returned. warray_like, shape (M,), optional Weights. If not None, the weight w[i] applies to the unsquared residual y[i] - y_hat[i] at x[i]. Ideally the weights are chosen so that the errors of the products w[i]*y[i] all have the same variance. When using inverse-variance weighting, use w[i] = 1/sigma(y[i]). The default value is None. New in version 1.5.0. Returns coefndarray, shape (deg + 1,) or (deg + 1, K) Polynomial coefficients ordered from low to high. If y was 2-D, the coefficients in column k of coef represent the polynomial fit to the data in y’s k-th column. [residuals, rank, singular_values, rcond]list These values are only returned if full == True residuals – sum of squared residuals of the least squares fit rank – the numerical rank of the scaled Vandermonde matrix singular_values – singular values of the scaled Vandermonde matrix rcond – value of rcond. For more details, see numpy.linalg.lstsq. Raises RankWarning Raised if the matrix in the least-squares fit is rank deficient. The warning is only raised if full == False. The warnings can be turned off by: >>> import warnings >>> warnings.simplefilter('ignore', np.RankWarning) See also numpy.polynomial.chebyshev.chebfit numpy.polynomial.legendre.legfit numpy.polynomial.laguerre.lagfit numpy.polynomial.hermite.hermfit numpy.polynomial.hermite_e.hermefit polyval Evaluates a polynomial. polyvander Vandermonde matrix for powers. numpy.linalg.lstsq Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline Computes spline fits. Notes The solution is the coefficients of the polynomial p that minimizes the sum of the weighted squared errors \[E = \sum_j w_j^2 * |y_j - p(x_j)|^2,\] where the \(w_j\) are the weights. This problem is solved by setting up the (typically) over-determined matrix equation: \[V(x) * c = w * y,\] where V is the weighted pseudo Vandermonde matrix of x, c are the coefficients to be solved for, w are the weights, and y are the observed values. This equation is then solved using the singular value decomposition of V. If some of the singular values of V are so small that they are neglected (and full == False), a RankWarning will be raised. This means that the coefficient values may be poorly determined. Fitting to a lower order polynomial will usually get rid of the warning (but may not be what you want, of course; if you have independent reason(s) for choosing the degree which isn’t working, you may have to: a) reconsider those reasons, and/or b) reconsider the quality of your data). The rcond parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Polynomial fits using double precision tend to “fail” at about (polynomial) degree 20. Fits using Chebyshev or Legendre series are generally better conditioned, but much can still depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate, splines may be a good alternative. Examples >>> np.random.seed(123) >>> from numpy.polynomial import polynomial as P >>> x = np.linspace(-1,1,51) # x "data": [-1, -0.96, ..., 0.96, 1] >>> y = x**3 - x + np.random.randn(len(x)) # x^3 - x + N(0,1) "noise" >>> c, stats = P.polyfit(x,y,3,full=True) >>> np.random.seed(123) >>> c # c[0], c[2] should be approx. 0, c[1] approx. -1, c[3] approx. 1 array([ 0.01909725, -1.30598256, -0.00577963, 1.02644286]) # may vary >>> stats # note the large SSR, explaining the rather poor results [array([ 38.06116253]), 4, array([ 1.38446749, 1.32119158, 0.50443316, # may vary 0.28853036]), 1.1324274851176597e-014] Same thing without the added noise >>> y = x**3 - x >>> c, stats = P.polyfit(x,y,3,full=True) >>> c # c[0], c[2] should be "very close to 0", c[1] ~= -1, c[3] ~= 1 array([-6.36925336e-18, -1.00000000e+00, -4.08053781e-16, 1.00000000e+00]) >>> stats # note the minuscule SSR [array([ 7.46346754e-31]), 4, array([ 1.38446749, 1.32119158, # may vary 0.50443316, 0.28853036]), 1.1324274851176597e-014]
numpy.reference.generated.numpy.polynomial.polynomial.polyfit
numpy.polynomial.polynomial.polyfromroots polynomial.polynomial.polyfromroots(roots)[source] Generate a monic polynomial with given roots. Return the coefficients of the polynomial \[p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\] where the r_n are the roots specified in roots. If a zero has multiplicity n, then it must appear in roots n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then roots looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are c, then \[p(x) = c_0 + c_1 * x + ... + x^n\] The coefficient of the last term is 1 for monic polynomials in this form. Parameters rootsarray_like Sequence containing the roots. Returns outndarray 1-D array of the polynomial’s coefficients If all the roots are real, then out is also real, otherwise it is complex. (see Examples below). See also numpy.polynomial.chebyshev.chebfromroots numpy.polynomial.legendre.legfromroots numpy.polynomial.laguerre.lagfromroots numpy.polynomial.hermite.hermfromroots numpy.polynomial.hermite_e.hermefromroots Notes The coefficients are determined by multiplying together linear factors of the form (x - r_i), i.e. \[p(x) = (x - r_0) (x - r_1) ... (x - r_n)\] where n == len(roots) - 1; note that this implies that 1 is always returned for \(a_n\). Examples >>> from numpy.polynomial import polynomial as P >>> P.polyfromroots((-1,0,1)) # x(x - 1)(x + 1) = x^3 - x array([ 0., -1., 0., 1.]) >>> j = complex(0,1) >>> P.polyfromroots((-j,j)) # complex returned, though values are real array([1.+0.j, 0.+0.j, 1.+0.j])
numpy.reference.generated.numpy.polynomial.polynomial.polyfromroots
numpy.polynomial.polynomial.polygrid2d polynomial.polynomial.polygrid2d(x, y, c)[source] Evaluate a 2-D polynomial on the Cartesian product of x and y. This function returns the values: \[p(a,b) = \sum_{i,j} c_{i,j} * a^i * b^j\] where the points (a, b) consist of all pairs formed by taking a from x and b from y. The resulting points form a grid with x in the first dimension and y in the second. The parameters x and y are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. 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 + y.shape. Parameters x, yarray_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of x and y. 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 coefficients for terms of degree i,j are 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 in the Cartesian product of x and y. See also polyval, polyval2d, polyval3d, polygrid3d Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.polynomial.polygrid2d
numpy.polynomial.polynomial.polygrid3d polynomial.polynomial.polygrid3d(x, y, z, c)[source] Evaluate a 3-D polynomial on the Cartesian product of x, y and z. This function returns the values: \[p(a,b,c) = \sum_{i,j,k} c_{i,j,k} * a^i * b^j * c^k\] where the points (a, b, c) consist of all triples formed by taking a from x, b from y, and c from z. The resulting points form a grid with x in the first dimension, y in the second, and z in the third. 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. 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 three 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 + y.shape + z.shape. Parameters x, y, zarray_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of x, y, and z. If 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 coefficients for terms of degree i,j are 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 in the Cartesian product of x and y. See also polyval, polyval2d, polygrid2d, polyval3d Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.polynomial.polygrid3d
numpy.polynomial.polynomial.polyint polynomial.polynomial.polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0)[source] Integrate a polynomial. Returns the polynomial coefficients c integrated m times from lbnd along axis. At each iteration the resulting series is multiplied by scl and an integration constant, k, is added. The scaling factor is for use in a linear change of variable. (“Buyer beware”: note that, depending on what one is doing, one may want scl to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument c is an array of coefficients, from low to high degree along each axis, e.g., [1,2,3] represents the polynomial 1 + 2*x + 3*x**2 while [[1,2],[1,2]] represents 1 + 1*x + 2*y + 2*x*y if axis=0 is x and axis=1 is y. Parameters carray_like 1-D array of polynomial coefficients, ordered from low to high. mint, optional Order of integration, must be positive. (Default: 1) k{[], list, scalar}, optional Integration constant(s). The value of the first integral at zero is the first value in the list, the value of the second integral at zero is the second value, etc. If k == [] (the default), all constants are set to zero. If m == 1, a single scalar can be given instead of a list. lbndscalar, optional The lower bound of the integral. (Default: 0) sclscalar, optional Following each integration the result is multiplied by scl before the integration constant is added. (Default: 1) axisint, optional Axis over which the integral is taken. (Default: 0). New in version 1.7.0. Returns Sndarray Coefficient array of the integral. Raises ValueError If m < 1, len(k) > m, np.ndim(lbnd) != 0, or np.ndim(scl) != 0. See also polyder Notes Note that the result of each integration is multiplied by scl. Why is this important to note? Say one is making a linear change of variable \(u = ax + b\) in an integral relative to x. Then \(dx = du/a\), so one will need to set scl equal to \(1/a\) - perhaps not what one would have first thought. Examples >>> from numpy.polynomial import polynomial as P >>> c = (1,2,3) >>> P.polyint(c) # should return array([0, 1, 1, 1]) array([0., 1., 1., 1.]) >>> P.polyint(c,3) # should return array([0, 0, 0, 1/6, 1/12, 1/20]) array([ 0. , 0. , 0. , 0.16666667, 0.08333333, # may vary 0.05 ]) >>> P.polyint(c,k=3) # should return array([3, 1, 1, 1]) array([3., 1., 1., 1.]) >>> P.polyint(c,lbnd=-2) # should return array([6, 1, 1, 1]) array([6., 1., 1., 1.]) >>> P.polyint(c,scl=-2) # should return array([0, -2, -2, -2]) array([ 0., -2., -2., -2.])
numpy.reference.generated.numpy.polynomial.polynomial.polyint
numpy.polynomial.polynomial.polyline polynomial.polynomial.polyline(off, scl)[source] Returns an array representing a linear polynomial. Parameters off, sclscalars The “y-intercept” and “slope” of the line, respectively. Returns yndarray This module’s representation of the linear polynomial off + scl*x. See also numpy.polynomial.chebyshev.chebline numpy.polynomial.legendre.legline numpy.polynomial.laguerre.lagline numpy.polynomial.hermite.hermline numpy.polynomial.hermite_e.hermeline Examples >>> from numpy.polynomial import polynomial as P >>> P.polyline(1,-1) array([ 1, -1]) >>> P.polyval(1, P.polyline(1,-1)) # should be 0 0.0
numpy.reference.generated.numpy.polynomial.polynomial.polyline
numpy.polynomial.polynomial.polymul polynomial.polynomial.polymul(c1, c2)[source] Multiply one polynomial by another. Returns the product of two polynomials c1 * c2. The arguments are sequences of coefficients, from lowest order term to highest, e.g., [1,2,3] represents the polynomial 1 + 2*x + 3*x**2. Parameters c1, c2array_like 1-D arrays of coefficients representing a polynomial, relative to the “standard” basis, and ordered from lowest order term to highest. Returns outndarray Of the coefficients of their product. See also polyadd, polysub, polymulx, polydiv, polypow Examples >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polymul(c1,c2) array([ 3., 8., 14., 8., 3.])
numpy.reference.generated.numpy.polynomial.polynomial.polymul
numpy.polynomial.polynomial.polymulx polynomial.polynomial.polymulx(c)[source] Multiply a polynomial by x. Multiply the polynomial c by x, where x is the independent variable. Parameters carray_like 1-D array of polynomial coefficients ordered from low to high. Returns outndarray Array representing the result of the multiplication. See also polyadd, polysub, polymul, polydiv, polypow Notes New in version 1.5.0.
numpy.reference.generated.numpy.polynomial.polynomial.polymulx
numpy.polynomial.polynomial.Polynomial.__call__ method polynomial.polynomial.Polynomial.__call__(arg)[source] Call self as a function.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.__call__
numpy.polynomial.polynomial.Polynomial.basis method classmethod polynomial.polynomial.Polynomial.basis(deg, domain=None, window=None)[source] Series basis polynomial of degree deg. Returns the series representing the basis polynomial of degree deg. New in version 1.7.0. Parameters degint Degree of the basis polynomial for the series. Must be >= 0. domain{None, array_like}, optional If given, the array must be of the form [beg, end], where beg and end are the endpoints of the domain. If None is given then the class domain is used. The default is None. window{None, array_like}, optional If given, the resulting array must be if the form [beg, end], where beg and end are the endpoints of the window. If None is given then the class window is used. The default is None. Returns new_seriesseries A series with the coefficient of the deg term set to one and all others zero.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.basis
numpy.polynomial.polynomial.Polynomial.cast method classmethod polynomial.polynomial.Polynomial.cast(series, domain=None, window=None)[source] Convert series to series of this class. The series is expected to be an instance of some polynomial series of one of the types supported by by the numpy.polynomial module, but could be some other class that supports the convert method. New in version 1.7.0. Parameters seriesseries The series instance to be converted. domain{None, array_like}, optional If given, the array must be of the form [beg, end], where beg and end are the endpoints of the domain. If None is given then the class domain is used. The default is None. window{None, array_like}, optional If given, the resulting array must be if the form [beg, end], where beg and end are the endpoints of the window. If None is given then the class window is used. The default is None. Returns new_seriesseries A series of the same kind as the calling class and equal to series when evaluated. See also convert similar instance method
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.cast
numpy.polynomial.polynomial.Polynomial.convert method polynomial.polynomial.Polynomial.convert(domain=None, kind=None, window=None)[source] Convert series to a different kind and/or domain and/or window. Parameters domainarray_like, optional The domain of the converted series. If the value is None, the default domain of kind is used. kindclass, optional The polynomial series type class to which the current instance should be converted. If kind is None, then the class of the current instance is used. windowarray_like, optional The window of the converted series. If the value is None, the default window of kind is used. Returns new_seriesseries The returned class can be of different type than the current instance and/or have a different domain and/or different window. Notes Conversion between domains and class types can result in numerically ill defined series.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.convert
numpy.polynomial.polynomial.Polynomial.copy method polynomial.polynomial.Polynomial.copy()[source] Return a copy. Returns new_seriesseries Copy of self.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.copy
numpy.polynomial.polynomial.Polynomial.cutdeg method polynomial.polynomial.Polynomial.cutdeg(deg)[source] Truncate series to the given degree. Reduce the degree of the series to deg by discarding the high order terms. If deg is greater than the current degree a copy of the current series is returned. This can be useful in least squares where the coefficients of the high degree terms may be very small. New in version 1.5.0. Parameters degnon-negative int The series is reduced to degree deg by discarding the high order terms. The value of deg must be a non-negative integer. Returns new_seriesseries New instance of series with reduced degree.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.cutdeg
numpy.polynomial.polynomial.Polynomial.degree method polynomial.polynomial.Polynomial.degree()[source] The degree of the series. New in version 1.5.0. Returns degreeint Degree of the series, one less than the number of coefficients.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.degree
numpy.polynomial.polynomial.Polynomial.deriv method polynomial.polynomial.Polynomial.deriv(m=1)[source] Differentiate. Return a series instance of that is the derivative of the current series. Parameters mnon-negative int Find the derivative of order m. Returns new_seriesseries A new series representing the derivative. The domain is the same as the domain of the differentiated series.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.deriv
numpy.polynomial.polynomial.Polynomial.domain attribute polynomial.polynomial.Polynomial.domain = array([-1, 1])
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.domain
numpy.polynomial.polynomial.Polynomial.fit method classmethod polynomial.polynomial.Polynomial.fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=None)[source] Least squares fit to data. Return a series instance that is the least squares fit to the data y sampled at x. The domain of the returned instance can be specified and this will often result in a superior fit with less chance of ill conditioning. Parameters xarray_like, shape (M,) x-coordinates of the M sample points (x[i], y[i]). yarray_like, shape (M,) y-coordinates of the M sample points (x[i], y[i]). degint or 1-D array_like Degree(s) of the fitting polynomials. If deg is a single integer all terms up to and including the deg’th term are included in the fit. For NumPy versions >= 1.11.0 a list of integers specifying the degrees of the terms to include may be used instead. domain{None, [beg, end], []}, optional Domain to use for the returned series. If None, then a minimal domain that covers the points x is chosen. If [] the class domain is used. The default value was the class domain in NumPy 1.4 and None in later versions. The [] option was added in numpy 1.5.0. rcondfloat, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases. fullbool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. warray_like, shape (M,), optional Weights. If not None, the weight w[i] applies to the unsquared residual y[i] - y_hat[i] at x[i]. Ideally the weights are chosen so that the errors of the products w[i]*y[i] all have the same variance. When using inverse-variance weighting, use w[i] = 1/sigma(y[i]). The default value is None. New in version 1.5.0. window{[beg, end]}, optional Window to use for the returned series. The default value is the default class domain New in version 1.6.0. Returns new_seriesseries A series that represents the least squares fit to the data and has the domain and window specified in the call. If the coefficients for the unscaled and unshifted basis polynomials are of interest, do new_series.convert().coef. [resid, rank, sv, rcond]list These values are only returned if full == True resid – sum of squared residuals of the least squares fit rank – the numerical rank of the scaled Vandermonde matrix sv – singular values of the scaled Vandermonde matrix rcond – value of rcond. For more details, see linalg.lstsq.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.fit
numpy.polynomial.polynomial.Polynomial.fromroots method classmethod polynomial.polynomial.Polynomial.fromroots(roots, domain=[], window=None)[source] Return series instance that has the specified roots. Returns a series representing the product (x - r[0])*(x - r[1])*...*(x - r[n-1]), where r is a list of roots. Parameters rootsarray_like List of roots. domain{[], None, array_like}, optional Domain for the resulting series. If None the domain is the interval from the smallest root to the largest. If [] the domain is the class domain. The default is []. window{None, array_like}, optional Window for the returned series. If None the class window is used. The default is None. Returns new_seriesseries Series with the specified roots.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.fromroots
numpy.polynomial.polynomial.Polynomial.has_samecoef method polynomial.polynomial.Polynomial.has_samecoef(other)[source] Check if coefficients match. New in version 1.6.0. Parameters otherclass instance The other class must have the coef attribute. Returns boolboolean True if the coefficients are the same, False otherwise.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.has_samecoef
numpy.polynomial.polynomial.Polynomial.has_samedomain method polynomial.polynomial.Polynomial.has_samedomain(other)[source] Check if domains match. New in version 1.6.0. Parameters otherclass instance The other class must have the domain attribute. Returns boolboolean True if the domains are the same, False otherwise.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.has_samedomain
numpy.polynomial.polynomial.Polynomial.has_sametype method polynomial.polynomial.Polynomial.has_sametype(other)[source] Check if types match. New in version 1.7.0. Parameters otherobject Class instance. Returns boolboolean True if other is same class as self
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.has_sametype
numpy.polynomial.polynomial.Polynomial.has_samewindow method polynomial.polynomial.Polynomial.has_samewindow(other)[source] Check if windows match. New in version 1.6.0. Parameters otherclass instance The other class must have the window attribute. Returns boolboolean True if the windows are the same, False otherwise.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.has_samewindow
numpy.polynomial.polynomial.Polynomial.identity method classmethod polynomial.polynomial.Polynomial.identity(domain=None, window=None)[source] Identity function. If p is the returned series, then p(x) == x for all values of x. Parameters domain{None, array_like}, optional If given, the array must be of the form [beg, end], where beg and end are the endpoints of the domain. If None is given then the class domain is used. The default is None. window{None, array_like}, optional If given, the resulting array must be if the form [beg, end], where beg and end are the endpoints of the window. If None is given then the class window is used. The default is None. Returns new_seriesseries Series of representing the identity.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.identity
numpy.polynomial.polynomial.Polynomial.integ method polynomial.polynomial.Polynomial.integ(m=1, k=[], lbnd=None)[source] Integrate. Return a series instance that is the definite integral of the current series. Parameters mnon-negative int The number of integrations to perform. karray_like Integration constants. The first constant is applied to the first integration, the second to the second, and so on. The list of values must less than or equal to m in length and any missing values are set to zero. lbndScalar The lower bound of the definite integral. Returns new_seriesseries A new series representing the integral. The domain is the same as the domain of the integrated series.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.integ
numpy.polynomial.polynomial.Polynomial.linspace method polynomial.polynomial.Polynomial.linspace(n=100, domain=None)[source] Return x, y values at equally spaced points in domain. Returns the x, y values at n linearly spaced points across the domain. Here y is the value of the polynomial at the points x. By default the domain is the same as that of the series instance. This method is intended mostly as a plotting aid. New in version 1.5.0. Parameters nint, optional Number of point pairs to return. The default value is 100. domain{None, array_like}, optional If not None, the specified domain is used instead of that of the calling instance. It should be of the form [beg,end]. The default is None which case the class domain is used. Returns x, yndarray x is equal to linspace(self.domain[0], self.domain[1], n) and y is the series evaluated at element of x.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.linspace
numpy.polynomial.polynomial.Polynomial.mapparms method polynomial.polynomial.Polynomial.mapparms()[source] Return the mapping parameters. The returned values define a linear map off + scl*x that is applied to the input arguments before the series is evaluated. The map depends on the domain and window; if the current domain is equal to the window the resulting map is the identity. If the coefficients of the series instance are to be used by themselves outside this class, then the linear function must be substituted for the x in the standard representation of the base polynomials. Returns off, sclfloat or complex The mapping function is defined by off + scl*x. Notes If the current domain is the interval [l1, r1] and the window is [l2, r2], then the linear mapping function L is defined by the equations: L(l1) = l2 L(r1) = r2
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.mapparms
numpy.polynomial.polynomial.Polynomial.roots method polynomial.polynomial.Polynomial.roots()[source] Return the roots of the series polynomial. Compute the roots for the series. Note that the accuracy of the roots decrease the further outside the domain they lie. Returns rootsndarray Array containing the roots of the series.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.roots
numpy.polynomial.polynomial.Polynomial.trim method polynomial.polynomial.Polynomial.trim(tol=0)[source] Remove trailing coefficients Remove trailing coefficients until a coefficient is reached whose absolute value greater than tol or the beginning of the series is reached. If all the coefficients would be removed the series is set to [0]. A new series instance is returned with the new coefficients. The current instance remains unchanged. Parameters tolnon-negative number. All trailing coefficients less than tol will be removed. Returns new_seriesseries New instance of series with trimmed coefficients.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.trim
numpy.polynomial.polynomial.Polynomial.truncate method polynomial.polynomial.Polynomial.truncate(size)[source] Truncate series to length size. Reduce the series to length size by discarding the high degree terms. The value of size must be a positive integer. This can be useful in least squares where the coefficients of the high degree terms may be very small. Parameters sizepositive int The series is reduced to length size by discarding the high degree terms. The value of size must be a positive integer. Returns new_seriesseries New instance of series with truncated coefficients.
numpy.reference.generated.numpy.polynomial.polynomial.polynomial.truncate
numpy.polynomial.polynomial.polyone polynomial.polynomial.polyone = array([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.reference.generated.numpy.polynomial.polynomial.polyone
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.reference.generated.numpy.polynomial.polynomial.polypow
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.reference.generated.numpy.polynomial.polynomial.polyroots
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.reference.generated.numpy.polynomial.polynomial.polysub
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.reference.generated.numpy.polynomial.polynomial.polytrim
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.reference.generated.numpy.polynomial.polynomial.polyval
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.reference.generated.numpy.polynomial.polynomial.polyval2d
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.reference.generated.numpy.polynomial.polynomial.polyval3d
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.reference.generated.numpy.polynomial.polynomial.polyvalfromroots
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.reference.generated.numpy.polynomial.polynomial.polyvander
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.reference.generated.numpy.polynomial.polynomial.polyvander2d
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.reference.generated.numpy.polynomial.polynomial.polyvander3d
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.reference.generated.numpy.polynomial.polynomial.polyx
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.reference.generated.numpy.polynomial.polynomial.polyzero
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.reference.generated.numpy.polynomial.polyutils.as_series
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.reference.generated.numpy.polynomial.polyutils.getdomain
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.reference.generated.numpy.polynomial.polyutils.mapdomain
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.reference.generated.numpy.polynomial.polyutils.mapparms
numpy.polynomial.polyutils.RankWarning exception polynomial.polyutils.RankWarning[source] Issued by chebfit when the design matrix is rank deficient.
numpy.reference.generated.numpy.polynomial.polyutils.rankwarning
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.reference.generated.numpy.polynomial.polyutils.trimcoef
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.reference.generated.numpy.polynomial.polyutils.trimseq
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²
numpy.reference.generated.numpy.polynomial.set_default_printstyle
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.reference.routines.polynomials.polyutils
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.reference.random.generated.numpy.random.beta
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.reference.random.generated.numpy.random.binomial
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.reference.random.bit_generators.generated.numpy.random.bitgenerator.cffi
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.reference.random.bit_generators.generated.numpy.random.bitgenerator.random_raw
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.reference.random.generated.numpy.random.bytes
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.reference.random.generated.numpy.random.chisquare
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.reference.random.generated.numpy.random.choice
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.reference.random.generated.numpy.random.dirichlet
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.reference.random.generated.numpy.random.exponential
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.reference.random.generated.numpy.random.f
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.reference.random.generated.numpy.random.gamma
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.reference.random.generated.numpy.random.generator.beta
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.reference.random.generated.numpy.random.generator.binomial
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.reference.random.generated.numpy.random.generator.bit_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.reference.random.generated.numpy.random.generator.bytes
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.reference.random.generated.numpy.random.generator.chisquare
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.reference.random.generated.numpy.random.generator.choice
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.reference.random.generated.numpy.random.generator.dirichlet
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.reference.random.generated.numpy.random.generator.exponential
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.reference.random.generated.numpy.random.generator.f
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.reference.random.generated.numpy.random.generator.gamma
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.reference.random.generated.numpy.random.generator.geometric
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.reference.random.generated.numpy.random.generator.gumbel
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.reference.random.generated.numpy.random.generator.hypergeometric
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.reference.random.generated.numpy.random.generator.integers
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.reference.random.generated.numpy.random.generator.laplace
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.reference.random.generated.numpy.random.generator.logistic
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.reference.random.generated.numpy.random.generator.lognormal
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.reference.random.generated.numpy.random.generator.logseries
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
numpy.reference.random.generated.numpy.random.generator.multinomial
numpy.random.Generator.multivariate_hypergeometric method random.Generator.multivariate_hypergeometric(colors, nsample, size=None, method='marginals') Generate variates from a multivariate hypergeometric distribution. The multivariate hypergeometric distribution is a generalization of the hypergeometric distribution. Choose nsample items at random without replacement from a collection with N distinct types. N is the length of colors, and the values in colors are the number of occurrences of that type in the collection. The total number of items in the collection is sum(colors). Each random variate generated by this function is a vector of length N holding the counts of the different types that occurred in the nsample items. The name colors comes from a common description of the distribution: it is the probability distribution of the number of marbles of each color selected without replacement from an urn containing marbles of different colors; colors[i] is the number of marbles in the urn with color i. Parameters colorssequence of integers The number of each type of item in the collection from which a sample is drawn. The values in colors must be nonnegative. To avoid loss of precision in the algorithm, sum(colors) must be less than 10**9 when method is “marginals”. nsampleint The number of items selected. nsample must not be greater than sum(colors). sizeint or tuple of ints, optional The number of variates to generate, either an integer or a tuple holding the shape of the array of variates. If the given size is, e.g., (k, m), then k * m variates are drawn, where one variate is a vector of length len(colors), and the return value has shape (k, m, len(colors)). If size is an integer, the output has shape (size, len(colors)). Default is None, in which case a single variate is returned as an array with shape (len(colors),). methodstring, optional Specify the algorithm that is used to generate the variates. Must be ‘count’ or ‘marginals’ (the default). See the Notes for a description of the methods. Returns variatesndarray Array of variates drawn from the multivariate hypergeometric distribution. See also hypergeometric Draw samples from the (univariate) hypergeometric distribution. Notes The two methods do not return the same sequence of variates. The “count” algorithm is roughly equivalent to the following numpy code: choices = np.repeat(np.arange(len(colors)), colors) selection = np.random.choice(choices, nsample, replace=False) variate = np.bincount(selection, minlength=len(colors)) The “count” algorithm uses a temporary array of integers with length sum(colors). The “marginals” algorithm generates a variate by using repeated calls to the univariate hypergeometric sampler. It is roughly equivalent to: variate = np.zeros(len(colors), dtype=np.int64) # `remaining` is the cumulative sum of `colors` from the last # element to the first; e.g. if `colors` is [3, 1, 5], then # `remaining` is [9, 6, 5]. remaining = np.cumsum(colors[::-1])[::-1] for i in range(len(colors)-1): if nsample < 1: break variate[i] = hypergeometric(colors[i], remaining[i+1], nsample) nsample -= variate[i] variate[-1] = nsample The default method is “marginals”. For some cases (e.g. when colors contains relatively small integers), the “count” method can be significantly faster than the “marginals” method. If performance of the algorithm is important, test the two methods with typical inputs to decide which works best. New in version 1.18.0. Examples >>> colors = [16, 8, 4] >>> seed = 4861946401452 >>> gen = np.random.Generator(np.random.PCG64(seed)) >>> gen.multivariate_hypergeometric(colors, 6) array([5, 0, 1]) >>> gen.multivariate_hypergeometric(colors, 6, size=3) array([[5, 0, 1], [2, 2, 2], [3, 3, 0]]) >>> gen.multivariate_hypergeometric(colors, 6, size=(2, 2)) array([[[3, 2, 1], [3, 2, 1]], [[4, 1, 1], [3, 2, 1]]])
numpy.reference.random.generated.numpy.random.generator.multivariate_hypergeometric
numpy.random.Generator.multivariate_normal method random.Generator.multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8, *, method='svd') Draw random samples from a multivariate normal distribution. The multivariate normal, multinormal or Gaussian distribution is a generalization of the one-dimensional normal distribution to higher dimensions. Such a distribution is specified by its mean and covariance matrix. These parameters are analogous to the mean (average or “center”) and variance (standard deviation, or “width,” squared) of the one-dimensional normal distribution. Parameters mean1-D array_like, of length N Mean of the N-dimensional distribution. cov2-D array_like, of shape (N, N) Covariance matrix of the distribution. It must be symmetric and positive-semidefinite for proper sampling. sizeint or tuple of ints, optional Given a shape of, for example, (m,n,k), m*n*k samples are generated, and packed in an m-by-n-by-k arrangement. Because each sample is N-dimensional, the output shape is (m,n,k,N). If no shape is specified, a single (N-D) sample is returned. check_valid{ ‘warn’, ‘raise’, ‘ignore’ }, optional Behavior when the covariance matrix is not positive semidefinite. tolfloat, optional Tolerance when checking the singular values in covariance matrix. cov is cast to double before the check. method{ ‘svd’, ‘eigh’, ‘cholesky’}, optional The cov input is used to compute a factor matrix A such that A @ A.T = cov. This argument is used to select the method used to compute the factor matrix A. The default method ‘svd’ is the slowest, while ‘cholesky’ is the fastest but less robust than the slowest method. The method eigh uses eigen decomposition to compute A and is faster than svd but slower than cholesky. New in version 1.18.0. Returns outndarray The drawn samples, of shape size, if that was provided. If not, the shape is (N,). In other words, each entry out[i,j,...,:] is an N-dimensional value drawn from the distribution. Notes The mean is a coordinate in N-dimensional space, which represents the location where samples are most likely to be generated. This is analogous to the peak of the bell curve for the one-dimensional or univariate normal distribution. Covariance indicates the level to which two variables vary together. From the multivariate normal distribution, we draw N-dimensional samples, \(X = [x_1, x_2, ... x_N]\). The covariance matrix element \(C_{ij}\) is the covariance of \(x_i\) and \(x_j\). The element \(C_{ii}\) is the variance of \(x_i\) (i.e. its “spread”). Instead of specifying the full covariance matrix, popular approximations include: Spherical covariance (cov is a multiple of the identity matrix) Diagonal covariance (cov has non-negative elements, and only on the diagonal) This geometrical property can be seen in two dimensions by plotting generated data-points: >>> mean = [0, 0] >>> cov = [[1, 0], [0, 100]] # diagonal covariance Diagonal covariance means that points are oriented along x or y-axis: >>> import matplotlib.pyplot as plt >>> x, y = np.random.default_rng().multivariate_normal(mean, cov, 5000).T >>> plt.plot(x, y, 'x') >>> plt.axis('equal') >>> plt.show() Note that the covariance matrix must be positive semidefinite (a.k.a. nonnegative-definite). Otherwise, the behavior of this method is undefined and backwards compatibility is not guaranteed. References 1 Papoulis, A., “Probability, Random Variables, and Stochastic Processes,” 3rd ed., New York: McGraw-Hill, 1991. 2 Duda, R. O., Hart, P. E., and Stork, D. G., “Pattern Classification,” 2nd ed., New York: Wiley, 2001. Examples >>> mean = (1, 2) >>> cov = [[1, 0], [0, 1]] >>> rng = np.random.default_rng() >>> x = rng.multivariate_normal(mean, cov, (3, 3)) >>> x.shape (3, 3, 2) We can use a different method other than the default to factorize cov: >>> y = rng.multivariate_normal(mean, cov, (3, 3), method='cholesky') >>> y.shape (3, 3, 2) The following is probably true, given that 0.6 is roughly twice the standard deviation: >>> list((x[0,0,:] - mean) < 0.6) [True, True] # random
numpy.reference.random.generated.numpy.random.generator.multivariate_normal
numpy.random.Generator.negative_binomial method random.Generator.negative_binomial(n, p, size=None) Draw samples from a negative binomial distribution. Samples are drawn from a negative binomial distribution with specified parameters, n successes and p probability of success where n is > 0 and p is in the interval (0, 1]. Parameters nfloat or array_like of floats Parameter of the distribution, > 0. pfloat or array_like of floats Parameter of the distribution. Must satisfy 0 < p <= 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 negative binomial distribution, where each sample is equal to N, the number of failures that occurred before a total of n successes was reached. Notes The probability mass function of the negative binomial distribution is \[P(N;n,p) = \frac{\Gamma(N+n)}{N!\Gamma(n)}p^{n}(1-p)^{N},\] where \(n\) is the number of successes, \(p\) is the probability of success, \(N+n\) is the number of trials, and \(\Gamma\) is the gamma function. When \(n\) is an integer, \(\frac{\Gamma(N+n)}{N!\Gamma(n)} = \binom{N+n-1}{N}\), which is the more common form of this term in the the pmf. The negative binomial distribution gives the probability of N failures given n successes, with a success on the last trial. If one throws a die repeatedly until the third time a “1” appears, then the probability distribution of the number of non-“1”s that appear before the third “1” is a negative binomial distribution. References 1 Weisstein, Eric W. “Negative Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/NegativeBinomialDistribution.html 2 Wikipedia, “Negative binomial distribution”, https://en.wikipedia.org/wiki/Negative_binomial_distribution Examples Draw samples from the distribution: A real world example. A company drills wild-cat oil exploration wells, each with an estimated probability of success of 0.1. What is the probability of having one success for each successive well, that is what is the probability of a single success after drilling 5 wells, after 6 wells, etc.? >>> s = np.random.default_rng().negative_binomial(1, 0.1, 100000) >>> for i in range(1, 11): ... probability = sum(s<i) / 100000. ... print(i, "wells drilled, probability of one success =", probability)
numpy.reference.random.generated.numpy.random.generator.negative_binomial
numpy.random.Generator.noncentral_chisquare method random.Generator.noncentral_chisquare(df, nonc, size=None) Draw samples from a noncentral chi-square distribution. The noncentral \(\chi^2\) distribution is a generalization of the \(\chi^2\) distribution. Parameters dffloat or array_like of floats Degrees of freedom, must be > 0. Changed in version 1.10.0: Earlier NumPy versions required dfnum > 1. noncfloat or array_like of floats Non-centrality, 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 df and nonc are both scalars. Otherwise, np.broadcast(df, nonc).size samples are drawn. Returns outndarray or scalar Drawn samples from the parameterized noncentral chi-square distribution. Notes The probability density function for the noncentral Chi-square distribution is \[P(x;df,nonc) = \sum^{\infty}_{i=0} \frac{e^{-nonc/2}(nonc/2)^{i}}{i!} P_{Y_{df+2i}}(x),\] where \(Y_{q}\) is the Chi-square with q degrees of freedom. References 1 Wikipedia, “Noncentral chi-squared distribution” https://en.wikipedia.org/wiki/Noncentral_chi-squared_distribution Examples Draw values from the distribution and plot the histogram >>> rng = np.random.default_rng() >>> import matplotlib.pyplot as plt >>> values = plt.hist(rng.noncentral_chisquare(3, 20, 100000), ... bins=200, density=True) >>> plt.show() Draw values from a noncentral chisquare with very small noncentrality, and compare to a chisquare. >>> plt.figure() >>> values = plt.hist(rng.noncentral_chisquare(3, .0000001, 100000), ... bins=np.arange(0., 25, .1), density=True) >>> values2 = plt.hist(rng.chisquare(3, 100000), ... bins=np.arange(0., 25, .1), density=True) >>> plt.plot(values[1][0:-1], values[0]-values2[0], 'ob') >>> plt.show() Demonstrate how large values of non-centrality lead to a more symmetric distribution. >>> plt.figure() >>> values = plt.hist(rng.noncentral_chisquare(3, 20, 100000), ... bins=200, density=True) >>> plt.show()
numpy.reference.random.generated.numpy.random.generator.noncentral_chisquare
numpy.random.Generator.noncentral_f method random.Generator.noncentral_f(dfnum, dfden, nonc, size=None) Draw samples from the noncentral 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 > 1. nonc is the non-centrality parameter. Parameters dfnumfloat or array_like of floats Numerator degrees of freedom, must be > 0. Changed in version 1.14.0: Earlier NumPy versions required dfnum > 1. dfdenfloat or array_like of floats Denominator degrees of freedom, must be > 0. noncfloat or array_like of floats Non-centrality parameter, the sum of the squares of the numerator means, 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, dfden, and nonc are all scalars. Otherwise, np.broadcast(dfnum, dfden, nonc).size samples are drawn. Returns outndarray or scalar Drawn samples from the parameterized noncentral Fisher distribution. Notes When calculating the power of an experiment (power = probability of rejecting the null hypothesis when a specific alternative is true) the non-central F statistic becomes important. When the null hypothesis is true, the F statistic follows a central F distribution. When the null hypothesis is not true, then it follows a non-central F statistic. References 1 Weisstein, Eric W. “Noncentral F-Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/NoncentralF-Distribution.html 2 Wikipedia, “Noncentral F-distribution”, https://en.wikipedia.org/wiki/Noncentral_F-distribution Examples In a study, testing for a specific alternative to the null hypothesis requires use of the Noncentral F distribution. We need to calculate the area in the tail of the distribution that exceeds the value of the F distribution for the null hypothesis. We’ll plot the two probability distributions for comparison. >>> rng = np.random.default_rng() >>> dfnum = 3 # between group deg of freedom >>> dfden = 20 # within groups degrees of freedom >>> nonc = 3.0 >>> nc_vals = rng.noncentral_f(dfnum, dfden, nonc, 1000000) >>> NF = np.histogram(nc_vals, bins=50, density=True) >>> c_vals = rng.f(dfnum, dfden, 1000000) >>> F = np.histogram(c_vals, bins=50, density=True) >>> import matplotlib.pyplot as plt >>> plt.plot(F[1][1:], F[0]) >>> plt.plot(NF[1][1:], NF[0]) >>> plt.show()
numpy.reference.random.generated.numpy.random.generator.noncentral_f
numpy.random.Generator.normal method random.Generator.normal(loc=0.0, scale=1.0, size=None) Draw random samples from a normal (Gaussian) distribution. The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2], is often called the bell curve because of its characteristic shape (see the example below). The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2]. Parameters locfloat or array_like of floats Mean (“centre”) of the distribution. scalefloat or array_like of floats Standard deviation (spread or “width”) of the distribution. 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 normal distribution. See also scipy.stats.norm probability density function, distribution or cumulative density function, etc. Notes The probability density for the Gaussian distribution is \[p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },\] where \(\mu\) is the mean and \(\sigma\) the standard deviation. The square of the standard deviation, \(\sigma^2\), is called the variance. The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at \(x + \sigma\) and \(x - \sigma\) [2]). This implies that normal is more likely to return samples lying close to the mean, rather than those far away. References 1 Wikipedia, “Normal distribution”, https://en.wikipedia.org/wiki/Normal_distribution 2(1,2,3) P. R. Peebles Jr., “Central Limit Theorem” in “Probability, Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125. Examples Draw samples from the distribution: >>> mu, sigma = 0, 0.1 # mean and standard deviation >>> s = np.random.default_rng().normal(mu, sigma, 1000) Verify the mean and the variance: >>> abs(mu - np.mean(s)) 0.0 # may vary >>> abs(sigma - np.std(s, ddof=1)) 0.0 # may vary 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/(sigma * np.sqrt(2 * np.pi)) * ... np.exp( - (bins - mu)**2 / (2 * sigma**2) ), ... linewidth=2, color='r') >>> plt.show() Two-by-four array of samples from N(3, 6.25): >>> np.random.default_rng().normal(3, 2.5, size=(2, 4)) array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
numpy.reference.random.generated.numpy.random.generator.normal
numpy.random.Generator.pareto method random.Generator.pareto(a, size=None) Draw samples from a Pareto II or Lomax distribution with specified shape. The Lomax or Pareto II distribution is a shifted Pareto distribution. The classical Pareto distribution can be obtained from the Lomax distribution by adding 1 and multiplying by the scale parameter m (see Notes). The smallest value of the Lomax distribution is zero while for the classical Pareto distribution it is mu, where the standard Pareto distribution has location mu = 1. Lomax can also be considered as a simplified version of the Generalized Pareto distribution (available in SciPy), with the scale set to one and the location set to zero. The Pareto distribution must be greater than zero, and is unbounded above. It is also known as the “80-20 rule”. In this distribution, 80 percent of the weights are in the lowest 20 percent of the range, while the other 20 percent fill the remaining 80 percent of the range. Parameters afloat or array_like of floats Shape of the distribution. Must be positive. 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 is a scalar. Otherwise, np.array(a).size samples are drawn. Returns outndarray or scalar Drawn samples from the parameterized Pareto distribution. See also scipy.stats.lomax probability density function, distribution or cumulative density function, etc. scipy.stats.genpareto probability density function, distribution or cumulative density function, etc. Notes The probability density for the Pareto distribution is \[p(x) = \frac{am^a}{x^{a+1}}\] where \(a\) is the shape and \(m\) the scale. The Pareto distribution, named after the Italian economist Vilfredo Pareto, is a power law probability distribution useful in many real world problems. Outside the field of economics it is generally referred to as the Bradford distribution. Pareto developed the distribution to describe the distribution of wealth in an economy. It has also found use in insurance, web page access statistics, oil field sizes, and many other problems, including the download frequency for projects in Sourceforge [1]. It is one of the so-called “fat-tailed” distributions. References 1 Francis Hunt and Paul Johnson, On the Pareto Distribution of Sourceforge projects. 2 Pareto, V. (1896). Course of Political Economy. Lausanne. 3 Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme Values, Birkhauser Verlag, Basel, pp 23-30. 4 Wikipedia, “Pareto distribution”, https://en.wikipedia.org/wiki/Pareto_distribution Examples Draw samples from the distribution: >>> a, m = 3., 2. # shape and mode >>> s = (np.random.default_rng().pareto(a, 1000) + 1) * m Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, _ = plt.hist(s, 100, density=True) >>> fit = a*m**a / bins**(a+1) >>> plt.plot(bins, max(count)*fit/max(fit), linewidth=2, color='r') >>> plt.show()
numpy.reference.random.generated.numpy.random.generator.pareto
numpy.random.Generator.permutation method random.Generator.permutation(x, axis=0) Randomly permute a sequence, or return a permuted range. Parameters xint or array_like If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle the elements randomly. axisint, optional The axis which x is shuffled along. Default is 0. Returns outndarray Permuted sequence or array range. Examples >>> rng = np.random.default_rng() >>> rng.permutation(10) array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6]) # random >>> rng.permutation([1, 4, 9, 12, 15]) array([15, 1, 9, 4, 12]) # random >>> arr = np.arange(9).reshape((3, 3)) >>> rng.permutation(arr) array([[6, 7, 8], # random [0, 1, 2], [3, 4, 5]]) >>> rng.permutation("abc") Traceback (most recent call last): ... numpy.AxisError: axis 0 is out of bounds for array of dimension 0 >>> arr = np.arange(9).reshape((3, 3)) >>> rng.permutation(arr, axis=1) array([[0, 2, 1], # random [3, 5, 4], [6, 8, 7]])
numpy.reference.random.generated.numpy.random.generator.permutation
numpy.random.Generator.permuted method random.Generator.permuted(x, axis=None, out=None) Randomly permute x along axis axis. Unlike shuffle, each slice along the given axis is shuffled independently of the others. Parameters xarray_like, at least one-dimensional Array to be shuffled. axisint, optional Slices of x in this axis are shuffled. Each slice is shuffled independently of the others. If axis is None, the flattened array is shuffled. outndarray, optional If given, this is the destinaton of the shuffled array. If out is None, a shuffled copy of the array is returned. Returns ndarray If out is None, a shuffled copy of x is returned. Otherwise, the shuffled array is stored in out, and out is returned See also shuffle permutation Examples Create a numpy.random.Generator instance: >>> rng = np.random.default_rng() Create a test array: >>> x = np.arange(24).reshape(3, 8) >>> x array([[ 0, 1, 2, 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23]]) Shuffle the rows of x: >>> y = rng.permuted(x, axis=1) >>> y array([[ 4, 3, 6, 7, 1, 2, 5, 0], # random [15, 10, 14, 9, 12, 11, 8, 13], [17, 16, 20, 21, 18, 22, 23, 19]]) x has not been modified: >>> x array([[ 0, 1, 2, 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23]]) To shuffle the rows of x in-place, pass x as the out parameter: >>> y = rng.permuted(x, axis=1, out=x) >>> x array([[ 3, 0, 4, 7, 1, 6, 2, 5], # random [ 8, 14, 13, 9, 12, 11, 15, 10], [17, 18, 16, 22, 19, 23, 20, 21]]) Note that when the out parameter is given, the return value is out: >>> y is x True
numpy.reference.random.generated.numpy.random.generator.permuted