Generate a Legendre series with given roots.
The function returns the coefficients of the polynomial
in Legendre form, 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
The coefficient of the last term is not generally 1 for monic polynomials in Legendre form.
Sequence containing the roots.
1-D array of coefficients. If all roots are real then out is a real array, if some of the roots are complex, then out is complex even if all the coefficients in the result are real (see Examples below).
See also


Gauss-Legendre quadrature.
Computes the sample points and weights for Gauss-Legendre quadrature. These sample points and weights will correctly integrate polynomials of degree \(2*deg - 1\) or less over the interval \([-1, 1]\) with the weight function \(f(x) = 1\).
Number of sample points and weights. It must be >= 1.
1-D ndarray containing the sample points.
1-D ndarray containing the weights.
New in version 1.7.0.
The results have only been tested up to degree 100, higher degrees may be problematic. The weights are determined by using the fact that
where \(c\) is a constant independent of \(k\) and \(x_k\) is the k’th root of \(L_n\), and then scaling the results to get the right value when integrating 1.


Evaluate a 2-D Legendre series on the Cartesian product of x and y.
This function returns the values:
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.
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.
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.
The values of the two dimensional Chebyshev series at points in the Cartesian product of x and y.
See also
New in version 1.7.0.


Evaluate a 3-D Legendre series on the Cartesian product of x, y, and z.
This function returns the values:
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.
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.
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.
The values of the two dimensional polynomial at points in the Cartesian product of x and y.
See also
New in version 1.7.0.


Integrate a Legendre series.
Returns the Legendre series 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 series L_0 + 2*L_1 + 3*L_2 while [[1,2],[1,2]] represents 1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) +
2*L_1(x)*L_1(y) if axis=0 is x and axis=1 is y.
Array of Legendre series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index.
Order of integration, must be positive. (Default: 1)
Integration constant(s). The value of the first integral at lbnd is the first value in the list, the value of the second integral at lbnd 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.
The lower bound of the integral. (Default: 0)
Following each integration the result is multiplied by scl before the integration constant is added. (Default: 1)
Axis over which the integral is taken. (Default: 0).
New in version 1.7.0.
Legendre series coefficient array of the integral.
If m < 0, len(k) > m, np.ndim(lbnd) != 0, or np.ndim(scl) != 0.
See also
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.
Also note that, in general, the result of integrating a C-series needs to be “reprojected” onto the C-series basis set. Thus, typically, the result of this function is “unintuitive,” albeit correct; see Examples section below.


Legendre series whose graph is a straight line.
The specified line is given by off + scl*x.
This module’s representation of the Legendre series for off + scl*x.
See also


Multiply one Legendre series by another.
Returns the product of two Legendre series c1 * c2. The arguments are sequences of coefficients, from lowest order “term” to highest, e.g., [1,2,3] represents the series P_0 + 2*P_1 + 3*P_2.
1-D arrays of Legendre series coefficients ordered from low to high.
Of Legendre series coefficients representing their product.
See also
In general, the (polynomial) product of two C-series results in terms that are not in the Legendre polynomial basis set. Thus, to express the product as a Legendre series, it is necessary to “reproject” the product onto said basis set, which may produce “unintuitive” (but correct) results; see Examples section below.


Multiply a Legendre series by x.
Multiply the Legendre series c by x, where x is the independent variable.
1-D array of Legendre series coefficients ordered from low to high.
Array representing the result of the multiplication.
See also
The multiplication uses the recursion relationship for Legendre polynomials in the form


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.
Shape of created array.
Any object that can be interpreted as a numpy data type.
Used to fill the array with data.
Offset of array data in buffer.
Strides of data in memory.
Row-major (C-style) or column-major (Fortran-style) order.
See also
Construct an array.
Create an array, each element of which is zero.
Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”).
Create a data-type.
An ndarray alias generic w.r.t. its dtype.type.
There are two modes of creating an array using __new__:
No __init__ method is needed because the array is fully initialized after the __new__ method.
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:
Second mode:
Transpose of the array.
The array’s elements, in memory.
Describes the format of the elements in the array.
Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO).
Imaginary part of the array.
Real part of the array.
Number of elements in the array.
The memory use of each array element in bytes.
The total number of bytes required to store the array data, i.e., itemsize * size.
The array’s number of dimensions.
Shape of the array.
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).
Class containing properties of the array needed for interaction with ctypes.
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.


Raise a Legendre series to a power.
Returns the Legendre series 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 P_0 + 2*P_1 + 3*P_2.
1-D array of Legendre series coefficients ordered from low to high.
Power to which the series will be raised
Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16
Legendre series of power.
See also


Compute the roots of a Legendre series.
Return the roots (a.k.a. “zeros”) of the polynomial
1-D array of coefficients.
Array of the roots of the series. If all the roots are real, then out is also real, otherwise it is complex.
See also
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 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.
The Legendre series basis polynomials aren’t powers of x so the results of this function may seem unintuitive.


Subtract one Legendre series from another.
Returns the difference of two Legendre series c1 - c2. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series P_0 + 2*P_1 + 3*P_2.
1-D arrays of Legendre series coefficients ordered from low to high.
Of Legendre series coefficients representing their difference.
See also
Unlike multiplication, division, etc., the difference of two Legendre series is a Legendre series (without having to “reproject” the result onto the basis set) so subtraction, just like that of “standard” polynomials, is simply “component-wise.”


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.”
1-d array of coefficients, ordered from lowest order to highest.
Trailing (i.e., highest order) elements with absolute value less than or equal to tol (default value is zero) are removed.
1-d array with trailing zeros removed. If the resulting series would be empty, a series containing a single zero is returned.
If tol < 0
See also


Evaluate a Legendre series at points x.
If c is of length n + 1, this function returns the value:
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.
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.
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.
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.
The shape of the return value is described above.
See also
The evaluation uses Clenshaw recursion, aka synthetic division.


Evaluate a 2-D Legendre series at points (x, y).
This function returns the values:
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 is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape.
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.
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.
The values of the two dimensional Legendre series at points formed from pairs of corresponding values from x and y.
See also
New in version 1.7.0.


Evaluate a 3-D Legendre series at points (x, y, z).
This function returns the values:
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.
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.
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.
The values of the multidimensional polynomial on points formed with triples of corresponding values from x, y, and z.
See also
New in version 1.7.0.


Pseudo-Vandermonde matrix of given degree.
Returns the pseudo-Vandermonde matrix of degree deg and sample points x. The pseudo-Vandermonde matrix is defined by
where 0 <= i <= deg. The leading indices of V index the elements of x and the last index is the degree of the Legendre polynomial.
If c is a 1-D array of coefficients of length n + 1 and V is the array V = legvander(x, n), then np.dot(V, c) and legval(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 Legendre series of the same degree and sample points.
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.
Degree of the resulting matrix.
The pseudo-Vandermonde matrix. The shape of the returned matrix is x.shape + (deg + 1,), where The last index is the degree of the corresponding Legendre polynomial. The dtype will be the same as the converted x.


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
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 degrees of the Legendre polynomials.
If V = legvander2d(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
and np.dot(V, c.flat) and legval2d(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 Legendre series of the same degrees and sample points.
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.
List of maximum degrees of the form [x_deg, y_deg].
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
New in version 1.7.0.


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
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 degrees of the Legendre polynomials.
If V = legvander3d(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
and np.dot(V, c.flat) and legval3d(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 Legendre series of the same degrees and sample points.
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.
List of maximum degrees of the form [x_deg, y_deg, z_deg].
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
New in version 1.7.0.


Weight function of the Legendre polynomials.
The weight function is \(1\) and the interval of integration is \([-1, 1]\). The Legendre polynomials are orthogonal, but not normalized, with respect to this weight function.
Values at which the weight function will be computed.
The weight function at x.
New in version 1.7.0.


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.
1-D array containing the polynomial coefficients
1-D array containing the coefficients of the equivalent Legendre series.
See also
The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance.


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.
1-D arrays of polynomial coefficients ordered from low to high.
The coefficient array representing their sum.
See also


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.
1-D array of polynomial coefficients ordered from low to high degree.
Companion matrix of dimensions (deg, deg).
New in version 1.7.0.


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.
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.
Number of derivatives taken, must be non-negative. (Default: 1)
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)
Axis over which the derivative is taken. (Default: 0).
New in version 1.7.0.
Polynomial coefficients of the derivative.
See also


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.
1-D arrays of polynomial coefficients ordered from low to high.
Of coefficient series representing the quotient and remainder.
See also


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.
Shape of created array.
Any object that can be interpreted as a numpy data type.
Used to fill the array with data.
Offset of array data in buffer.
Strides of data in memory.
Row-major (C-style) or column-major (Fortran-style) order.
See also
Construct an array.
Create an array, each element of which is zero.
Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”).
Create a data-type.
An ndarray alias generic w.r.t. its dtype.type.
There are two modes of creating an array using __new__:
No __init__ method is needed because the array is fully initialized after the __new__ method.
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:
Second mode:
Transpose of the array.
The array’s elements, in memory.
Describes the format of the elements in the array.
Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO).
Imaginary part of the array.
Real part of the array.
Number of elements in the array.
The memory use of each array element in bytes.
The total number of bytes required to store the array data, i.e., itemsize * size.
The array’s number of dimensions.
Shape of the array.
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).
Class containing properties of the array needed for interaction with ctypes.
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.


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
where n is deg.
x-coordinates of the M sample (data) points (x[i], y[i]).
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.
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.
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.
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.
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.
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.
These values are only returned if full == True
For more details, see numpy.linalg.lstsq.
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:
See also
Evaluates a polynomial.
Vandermonde matrix for powers.
Computes a least-squares fit from the matrix.
Computes spline fits.
The solution is the coefficients of the polynomial p that minimizes the sum of the weighted squared errors
where the \(w_j\) are the weights. This problem is solved by setting up the (typically) over-determined matrix equation:
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.
Same thing without the added noise


Generate a monic polynomial with given roots.
Return the coefficients of the polynomial
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
The coefficient of the last term is 1 for monic polynomials in this form.
Sequence containing the roots.
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
The coefficients are determined by multiplying together linear factors of the form (x - r_i), i.e.
where n == len(roots) - 1; note that this implies that 1 is always returned for \(a_n\).


Evaluate a 2-D polynomial on the Cartesian product of x and y.
This function returns the values:
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.
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.
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.
The values of the two dimensional polynomial at points in the Cartesian product of x and y.
See also
New in version 1.7.0.


Evaluate a 3-D polynomial on the Cartesian product of x, y and z.
This function returns the values:
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.
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.
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.
The values of the two dimensional polynomial at points in the Cartesian product of x and y.
See also
New in version 1.7.0.


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.
1-D array of polynomial coefficients, ordered from low to high.
Order of integration, must be positive. (Default: 1)
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.
The lower bound of the integral. (Default: 0)
Following each integration the result is multiplied by scl before the integration constant is added. (Default: 1)
Axis over which the integral is taken. (Default: 0).
New in version 1.7.0.
Coefficient array of the integral.
If m < 1, len(k) > m, np.ndim(lbnd) != 0, or np.ndim(scl) != 0.
See also
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.


Returns an array representing a linear polynomial.
The “y-intercept” and “slope” of the line, respectively.
This module’s representation of the linear polynomial off +
scl*x.
See also


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.
1-D arrays of coefficients representing a polynomial, relative to the “standard” basis, and ordered from lowest order term to highest.
Of the coefficients of their product.
See also


Multiply a polynomial by x.
Multiply the polynomial c by x, where x is the independent variable.
1-D array of polynomial coefficients ordered from low to high.
Array representing the result of the multiplication.
See also
New in version 1.5.0.


method
Series basis polynomial of degree deg.
Returns the series representing the basis polynomial of degree deg.
New in version 1.7.0.
Degree of the basis polynomial for the series. Must be >= 0.
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.
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.
A series with the coefficient of the deg term set to one and all others zero.


method
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.
The series instance to be converted.
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.
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.
A series of the same kind as the calling class and equal to series when evaluated.
See also
similar instance method


method
Convert series to a different kind and/or domain and/or window.
The domain of the converted series. If the value is None, the default domain of kind is used.
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.
The window of the converted series. If the value is None, the default window of kind is used.
The returned class can be of different type than the current instance and/or have a different domain and/or different window.
Conversion between domains and class types can result in numerically ill defined series.


method
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.
The series is reduced to degree deg by discarding the high order terms. The value of deg must be a non-negative integer.
New instance of series with reduced degree.


method
The degree of the series.
New in version 1.5.0.
Degree of the series, one less than the number of coefficients.


method
Differentiate.
Return a series instance of that is the derivative of the current series.
Find the derivative of order m.
A new series representing the derivative. The domain is the same as the domain of the differentiated series.


method
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.
x-coordinates of the M sample points (x[i], y[i]).
y-coordinates of the M sample points (x[i], y[i]).
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 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.
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.
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.
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 to use for the returned series. The default value is the default class domain
New in version 1.6.0.
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.
These values are only returned if full == True
For more details, see linalg.lstsq.


method
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.
List of roots.
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 for the returned series. If None the class window is used. The default is None.
Series with the specified roots.


method
Check if coefficients match.
New in version 1.6.0.
The other class must have the coef attribute.
True if the coefficients are the same, False otherwise.


method
Check if domains match.
New in version 1.6.0.
The other class must have the domain attribute.
True if the domains are the same, False otherwise.


method
Check if types match.
New in version 1.7.0.
Class instance.
True if other is same class as self


method
Check if windows match.
New in version 1.6.0.
The other class must have the window attribute.
True if the windows are the same, False otherwise.


method
Identity function.
If p is the returned series, then p(x) == x for all values of x.
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.
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.
Series of representing the identity.


method
Integrate.
Return a series instance that is the definite integral of the current series.
The number of integrations to perform.
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.
The lower bound of the definite integral.
A new series representing the integral. The domain is the same as the domain of the integrated series.


method
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.
Number of point pairs to return. The default value is 100.
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.
x is equal to linspace(self.domain[0], self.domain[1], n) and y is the series evaluated at element of x.


method
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.
The mapping function is defined by off + scl*x.
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:


method
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.
Array containing the roots of the series.


method
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.
All trailing coefficients less than tol will be removed.
New instance of series with trimmed coefficients.


method
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.
The series is reduced to length size by discarding the high degree terms. The value of size must be a positive integer.
New instance of series with truncated coefficients.


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.
Shape of created array.
Any object that can be interpreted as a numpy data type.
Used to fill the array with data.
Offset of array data in buffer.
Strides of data in memory.
Row-major (C-style) or column-major (Fortran-style) order.
See also
Construct an array.
Create an array, each element of which is zero.
Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”).
Create a data-type.
An ndarray alias generic w.r.t. its dtype.type.
There are two modes of creating an array using __new__:
No __init__ method is needed because the array is fully initialized after the __new__ method.
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:
Second mode:
Transpose of the array.
The array’s elements, in memory.
Describes the format of the elements in the array.
Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO).
Imaginary part of the array.
Real part of the array.
Number of elements in the array.
The memory use of each array element in bytes.
The total number of bytes required to store the array data, i.e., itemsize * size.
The array’s number of dimensions.
Shape of the array.
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).
Class containing properties of the array needed for interaction with ctypes.
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.


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.
1-D array of array of series coefficients ordered from low to high degree.
Power to which the series will be raised
Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16
Power series of power.
See also


Compute the roots of a polynomial.
Return the roots (a.k.a. “zeros”) of the polynomial
1-D array of polynomial coefficients.
Array of the roots of the polynomial. If all the roots are real, then out is also real, otherwise it is complex.
See also
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.


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.
1-D arrays of polynomial coefficients ordered from low to high.
Of coefficients representing their difference.
See also


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.”
1-d array of coefficients, ordered from lowest order to highest.
Trailing (i.e., highest order) elements with absolute value less than or equal to tol (default value is zero) are removed.
1-d array with trailing zeros removed. If the resulting series would be empty, a series containing a single zero is returned.
If tol < 0
See also


Evaluate a polynomial at points x.
If c is of length n + 1, this function returns the value
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.
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.
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.
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.
The shape of the returned array is described above.
See also
The evaluation uses Horner’s method.


Evaluate a 2-D polynomial at points (x, y).
This function returns the value
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.
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.
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.
The values of the two dimensional polynomial at points formed with pairs of corresponding values from x and y.
See also
New in version 1.7.0.


Evaluate a 3-D polynomial at points (x, y, z).
This function returns the values:
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.
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.
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.
The values of the multidimensional polynomial on points formed with triples of corresponding values from x, y, and z.
See also
New in version 1.7.0.


Evaluate a polynomial specified by its roots at points x.
If r is of length N, this function returns the value
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.
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.
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.
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.
The shape of the returned array is described above.
See also


Vandermonde matrix of given degree.
Returns the Vandermonde matrix of degree deg and sample points x. The Vandermonde matrix is defined by
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.
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.
Degree of the resulting matrix.
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


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
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
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.
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.
List of maximum degrees of the form [x_deg, y_deg].
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


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
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
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.
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.
List of maximum degrees of the form [x_deg, y_deg, z_deg].
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
New in version 1.7.0.


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.
A 1- or 2-d array_like
When True, trailing zeros are removed from the inputs. When False, the inputs are passed through intact.
A copy of the input data as a list of 1-d arrays.
Raised when as_series cannot convert its input to 1-d arrays, or at least one of the resulting arrays is empty.


Return a domain suitable for given abscissae.
Find a domain suitable for a polynomial or Chebyshev series defined at the values supplied.
1-d array of abscissae whose domain will be determined.
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


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.
Points to be mapped. If x is a subtype of ndarray the subtype will be preserved.
The two domains that determine the map. Each must (successfully) convert to 1-d arrays containing precisely two values.
Array of points of the same shape as x, after application of the linear map between the two domains.
See also
Effectively, this implements:
where
Also works for complex numbers (and thus can be used to map any line in the complex plane to any other line therein).


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.
Domains. Each domain must (successfully) convert to a 1-d array containing precisely two values.
The map L(x) = offset + scale*x maps the first domain to the second.
See also
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.


Issued by chebfit when the design matrix is rank deficient.


Remove small Poly series coefficients.
Sequence of Poly series coefficients. This routine fails for empty sequences.
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.
Do not lose the type info if the sequence contains unknown objects.


Set the default format for the string representation of polynomials.
Values for style must be valid inputs to __format__, i.e. ‘ascii’ or ‘unicode’.
Format string for default printing style. Must be either ‘ascii’ or ‘unicode’.
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.


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.
RankWarning
Issued by chebfit when the design matrix is rank deficient.
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.


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
where the normalization, B, is the beta function,
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.
Alpha, positive (>0).
Beta, positive (>0).
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.
Drawn samples from the parameterized beta distribution.
See also
which should be used for new code.


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.
Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.
Parameter of the distribution, >= 0 and <=1.
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.
Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.
See also
probability density function, distribution or cumulative density function, etc.
which should be used for new code.
The probability density for the binomial distribution is
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.
Dalgaard, Peter, “Introductory Statistics with R”, Springer-Verlag, 2002.
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.
Weisstein, Eric W. “Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html
Wikipedia, “Binomial distribution”, https://en.wikipedia.org/wiki/Binomial_distribution
Draw samples from the distribution:
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.


attribute
CFFI interface
Named tuple containing CFFI wrapper


method
Return randoms as generated by the underlying BitGenerator
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.
Output values. Used for performance testing since the generated values are not returned.
Drawn samples.
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.


Return random bytes.
Note
New code should use the bytes method of a default_rng() instance instead; please see the Quick Start.
Number of random bytes.
String of length length.
See also
which should be used for new code.


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.
Number of degrees of freedom, must be > 0.
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.
Drawn samples from the parameterized chi-square distribution.
When df <= 0 or when an inappropriate size (e.g. size=-1) is given.
See also
which should be used for new code.
The variable obtained by summing the squares of df independent, standard normally distributed random variables:
is chi-square distributed, denoted
The probability density function of the chi-squared distribution is
where \(\Gamma\) is the gamma function,
NIST “Engineering Statistics Handbook” https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm


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.
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)
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.
Whether the sample is with or without replacement. Default is True, meaning that a value of a can be selected multiple times.
The probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in a.
The generated random samples
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
which should be used in new code
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.
Generate a uniform random sample from np.arange(5) of size 3:
Generate a non-uniform random sample from np.arange(5) of size 3:
Generate a uniform random sample from np.arange(5) of size 3 without replacement:
Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:
Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance:


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.
Parameter of the distribution (length k for sample of length k).
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.
The drawn samples, of shape (size, k).
If any value in alpha is less than or equal to zero
See also
which should be used for new code.
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
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
David McKay, “Information Theory, Inference and Learning Algorithms,” chapter 23, http://www.inference.org.uk/mackay/itila/
Wikipedia, “Dirichlet distribution”, https://en.wikipedia.org/wiki/Dirichlet_distribution
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.


Draw samples from an exponential distribution.
Its probability density function is
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.
The scale parameter, \(\beta = 1/\lambda\). Must be non-negative.
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.
Drawn samples from the parameterized exponential distribution.
See also
which should be used for new code.
Peyton Z. Peebles Jr., “Probability, Random Variables and Random Signal Principles”, 4th ed, 2001, p. 57.
Wikipedia, “Poisson process”, https://en.wikipedia.org/wiki/Poisson_process
Wikipedia, “Exponential distribution”, https://en.wikipedia.org/wiki/Exponential_distribution


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.
Degrees of freedom in numerator, must be > 0.
Degrees of freedom in denominator, must be > 0.
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.
Drawn samples from the parameterized Fisher distribution.
See also
probability density function, distribution or cumulative density function, etc.
which should be used for new code.
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.
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.
Wikipedia, “F-distribution”, https://en.wikipedia.org/wiki/F-distribution
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:
The lower bound for the top 1% of the samples is :
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.


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.
The shape of the gamma distribution. Must be non-negative.
The scale of the gamma distribution. Must be non-negative. Default is equal to 1.
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.
Drawn samples from the parameterized gamma distribution.
See also
probability density function, distribution or cumulative density function, etc.
which should be used for new code.
The probability density for the Gamma distribution is
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.
Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html
Wikipedia, “Gamma distribution”, https://en.wikipedia.org/wiki/Gamma_distribution
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:


method
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
where the normalization, B, is the beta function,
It is often seen in Bayesian inference and order statistics.
Alpha, positive (>0).
Beta, positive (>0).
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.
Drawn samples from the parameterized beta distribution.


method
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)
Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.
Parameter of the distribution, >= 0 and <=1.
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.
Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.
See also
probability density function, distribution or cumulative density function, etc.
The probability density for the binomial distribution is
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.
Dalgaard, Peter, “Introductory Statistics with R”, Springer-Verlag, 2002.
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.
Weisstein, Eric W. “Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html
Wikipedia, “Binomial distribution”, https://en.wikipedia.org/wiki/Binomial_distribution
Draw samples from the distribution:
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.


attribute
Gets the bit generator instance used by the generator
The bit generator instance used by the generator


method
Return random bytes.
Number of random bytes.
String of length length.


method
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.
Number of degrees of freedom, must be > 0.
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.
Drawn samples from the parameterized chi-square distribution.
When df <= 0 or when an inappropriate size (e.g. size=-1) is given.
The variable obtained by summing the squares of df independent, standard normally distributed random variables:
is chi-square distributed, denoted
The probability density function of the chi-squared distribution is
where \(\Gamma\) is the gamma function,
NIST “Engineering Statistics Handbook” https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm


method
Generates a random sample from a given array
If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated from np.arange(a).
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.
Whether the sample is with or without replacement. Default is True, meaning that a value of a can be selected multiple times.
The probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in a.
The axis along which the selection is performed. The default, 0, selects by row.
Whether the sample is shuffled when sampling without replacement. Default is True, False provides a speedup.
The generated random samples
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
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).
Generate a uniform random sample from np.arange(5) of size 3:
Generate a non-uniform random sample from np.arange(5) of size 3:
Generate a uniform random sample from np.arange(5) of size 3 without replacement:
Generate a uniform random sample from a 2-D array along the first axis (the default), without replacement:
Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:
Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance:


method
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.
Parameter of the distribution (length k for sample of length k).
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.
The drawn samples, of shape (size, k).
If any value in alpha is less than or equal to zero
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
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
David McKay, “Information Theory, Inference and Learning Algorithms,” chapter 23, http://www.inference.org.uk/mackay/itila/
Wikipedia, “Dirichlet distribution”, https://en.wikipedia.org/wiki/Dirichlet_distribution
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.


method
Draw samples from an exponential distribution.
Its probability density function is
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].
The scale parameter, \(\beta = 1/\lambda\). Must be non-negative.
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.
Drawn samples from the parameterized exponential distribution.
Peyton Z. Peebles Jr., “Probability, Random Variables and Random Signal Principles”, 4th ed, 2001, p. 57.
Wikipedia, “Poisson process”, https://en.wikipedia.org/wiki/Poisson_process
Wikipedia, “Exponential distribution”, https://en.wikipedia.org/wiki/Exponential_distribution


method
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.
Degrees of freedom in numerator, must be > 0.
Degrees of freedom in denominator, must be > 0.
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.
Drawn samples from the parameterized Fisher distribution.
See also
probability density function, distribution or cumulative density function, etc.
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.
Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.
Wikipedia, “F-distribution”, https://en.wikipedia.org/wiki/F-distribution
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:
The lower bound for the top 1% of the samples is :
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.


method
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.
The shape of the gamma distribution. Must be non-negative.
The scale of the gamma distribution. Must be non-negative. Default is equal to 1.
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.
Drawn samples from the parameterized gamma distribution.
See also
probability density function, distribution or cumulative density function, etc.
The probability density for the Gamma distribution is
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.
Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html
Wikipedia, “Gamma distribution”, https://en.wikipedia.org/wiki/Gamma_distribution
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:


method
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
where p is the probability of success of an individual trial.
The probability of success of an individual trial.
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.
Drawn samples from the parameterized geometric distribution.
Draw ten thousand values from the geometric distribution, with the probability of an individual success equal to 0.35:
How many trials succeeded after a single run?


method
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.
The location of the mode of the distribution. Default is 0.
The scale parameter of the distribution. Default is 1. Must be non- negative.
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.
Drawn samples from the parameterized Gumbel distribution.
See also
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
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\).
Gumbel, E. J., “Statistics of Extremes,” New York: Columbia University Press, 1958.
Reiss, R.-D. and Thomas, M., “Statistical Analysis of Extreme Values from Insurance, Finance, Hydrology and Other Fields,” Basel: Birkhauser Verlag, 2001.
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
Show how an extreme value distribution can arise from a Gaussian process and compare to a Gaussian:


method
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).
Number of ways to make a good selection. Must be nonnegative and less than 10**9.
Number of ways to make a bad selection. Must be nonnegative and less than 10**9.
Number of items sampled. Must be nonnegative and less than ngood + nbad.
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.
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
Draw samples from the multivariate hypergeometric distribution.
probability density function, distribution or cumulative density function, etc.
The probability density for the Hypergeometric distribution is
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)).
Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.
Weisstein, Eric W. “Hypergeometric Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/HypergeometricDistribution.html
Wikipedia, “Hypergeometric distribution”, https://en.wikipedia.org/wiki/Hypergeometric_distribution
Stadlober, Ernst, “The ratio of uniforms approach for generating discrete random variates”, Journal of Computational and Applied Mathematics, 31, pp. 181-189 (1990).
Draw samples from the distribution:
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?


method
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.
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).
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
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.
Desired dtype of the result. Byteorder must be native. The default value is np.int64.
If true, sample from the interval [low, high] instead of the default [low, high) Defaults to False
size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.
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]).
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.
Generate a 2 x 4 array of ints between 0 and 4, inclusive:
Generate a 1 x 3 array with 3 different upper bounds
Generate a 1 by 3 array with 3 different lower bounds
Generate a 2 by 4 array using broadcasting with dtype of uint8


method
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.
The position, \(\mu\), of the distribution peak. Default is 0.
\(\lambda\), the exponential decay. Default is 1. Must be non- negative.
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.
Drawn samples from the parameterized Laplace distribution.
It has the probability density function
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.
Abramowitz, M. and Stegun, I. A. (Eds.). “Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables, 9th printing,” New York: Dover, 1972.
Kotz, Samuel, et. al. “The Laplace Distribution and Generalizations, ” Birkhauser, 2001.
Weisstein, Eric W. “Laplace Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LaplaceDistribution.html
Wikipedia, “Laplace distribution”, https://en.wikipedia.org/wiki/Laplace_distribution
Draw samples from the distribution
Display the histogram of the samples, along with the probability density function:
Plot Gaussian for comparison: