doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.typename numpy.typename(char)[source] Return a description for the given data type code. Parameters charstr Data type code. Returns outstr Description of the input data type code. See also dtype, typecodes Examples >>> typechars = ['S1', '?', 'B', 'D', 'G', 'F', 'I', 'H', 'L', 'O', 'Q', ... 'S', 'U', 'V', 'b', 'd', 'g', 'f', 'i', 'h', 'l', 'q'] >>> for typechar in typechars: ... print(typechar, ' : ', np.typename(typechar)) ... S1 : character ? : bool B : unsigned char D : complex double precision G : complex long double precision F : complex single precision I : unsigned integer H : unsigned short L : unsigned long integer O : object Q : unsigned long long integer S : string U : unicode V : void b : signed char d : double precision g : long precision f : single precision i : integer h : short l : long integer q : long long integer
numpy.reference.generated.numpy.typename
Typing (numpy.typing) New in version 1.20. Large parts of the NumPy API have PEP-484-style type annotations. In addition a number of type aliases are available to users, most prominently the two below: ArrayLike: objects that can be converted to arrays DTypeLike: objects that can be converted to dtypes Mypy plugin New in version 1.21. A mypy plugin for managing a number of platform-specific annotations. Its functionality can be split into three distinct parts: Assigning the (platform-dependent) precisions of certain number subclasses, including the likes of int_, intp and longlong. See the documentation on scalar types for a comprehensive overview of the affected classes. Without the plugin the precision of all relevant classes will be inferred as Any. Removing all extended-precision number subclasses that are unavailable for the platform in question. Most notably this includes the likes of float128 and complex256. Without the plugin all extended-precision types will, as far as mypy is concerned, be available to all platforms. Assigning the (platform-dependent) precision of c_intp. Without the plugin the type will default to ctypes.c_int64. New in version 1.22. Examples To enable the plugin, one must add it to their mypy configuration file: [mypy] plugins = numpy.typing.mypy_plugin Differences from the runtime NumPy API NumPy is very flexible. Trying to describe the full range of possibilities statically would result in types that are not very helpful. For that reason, the typed NumPy API is often stricter than the runtime NumPy API. This section describes some notable differences. ArrayLike The ArrayLike type tries to avoid creating object arrays. For example, >>> np.array(x**2 for x in range(10)) array(<generator object <genexpr> at ...>, dtype=object) is valid NumPy code which will create a 0-dimensional object array. Type checkers will complain about the above example when using the NumPy types however. If you really intended to do the above, then you can either use a # type: ignore comment: >>> np.array(x**2 for x in range(10)) # type: ignore or explicitly type the array like object as Any: >>> from typing import Any >>> array_like: Any = (x**2 for x in range(10)) >>> np.array(array_like) array(<generator object <genexpr> at ...>, dtype=object) ndarray It’s possible to mutate the dtype of an array at runtime. For example, the following code is valid: >>> x = np.array([1, 2]) >>> x.dtype = np.bool_ This sort of mutation is not allowed by the types. Users who want to write statically typed code should instead use the numpy.ndarray.view method to create a view of the array with a different dtype. DTypeLike The DTypeLike type tries to avoid creation of dtype objects using dictionary of fields like below: >>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)}) Although this is valid NumPy code, the type checker will complain about it, since its usage is discouraged. Please see : Data type objects Number precision The precision of numpy.number subclasses is treated as a covariant generic parameter (see NBitBase), simplifying the annotating of processes involving precision-based casting. >>> from typing import TypeVar >>> import numpy as np >>> import numpy.typing as npt >>> T = TypeVar("T", bound=npt.NBitBase) >>> def func(a: "np.floating[T]", b: "np.floating[T]") -> "np.floating[T]": ... ... Consequently, the likes of float16, float32 and float64 are still sub-types of floating, but, contrary to runtime, they’re not necessarily considered as sub-classes. Timedelta64 The timedelta64 class is not considered a subclass of signedinteger, the former only inheriting from generic while static type checking. 0D arrays During runtime numpy aggressively casts any passed 0D arrays into their corresponding generic instance. Until the introduction of shape typing (see PEP 646) it is unfortunately not possible to make the necessary distinction between 0D and >0D arrays. While thus not strictly correct, all operations are that can potentially perform a 0D-array -> scalar cast are currently annotated as exclusively returning an ndarray. If it is known in advance that an operation _will_ perform a 0D-array -> scalar cast, then one can consider manually remedying the situation with either typing.cast or a # type: ignore comment. Record array dtypes The dtype of numpy.recarray, and the numpy.rec functions in general, can be specified in one of two ways: Directly via the dtype argument. With up to five helper arguments that operate via numpy.format_parser: formats, names, titles, aligned and byteorder. These two approaches are currently typed as being mutually exclusive, i.e. if dtype is specified than one may not specify formats. While this mutual exclusivity is not (strictly) enforced during runtime, combining both dtype specifiers can lead to unexpected or even downright buggy behavior. API numpy.typing.ArrayLike = typing.Union[...] A Union representing objects that can be coerced into an ndarray. Among others this includes the likes of: Scalars. (Nested) sequences. Objects implementing the __array__ protocol. New in version 1.20. See Also array_like: Any scalar or sequence that can be interpreted as an ndarray. Examples >>> import numpy as np >>> import numpy.typing as npt >>> def as_array(a: npt.ArrayLike) -> np.ndarray: ... return np.array(a) numpy.typing.DTypeLike = typing.Union[...] A Union representing objects that can be coerced into a dtype. Among others this includes the likes of: type objects. Character codes or the names of type objects. Objects with the .dtype attribute. New in version 1.20. See Also Specifying and constructing data types A comprehensive overview of all objects that can be coerced into data types. Examples >>> import numpy as np >>> import numpy.typing as npt >>> def as_dtype(d: npt.DTypeLike) -> np.dtype: ... return np.dtype(d) numpy.typing.NDArray = numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]][source] A generic version of np.ndarray[Any, np.dtype[+ScalarType]]. Can be used during runtime for typing arrays with a given dtype and unspecified shape. New in version 1.21. Examples >>> import numpy as np >>> import numpy.typing as npt >>> print(npt.NDArray) numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]] >>> print(npt.NDArray[np.float64]) numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]] >>> NDArrayInt = npt.NDArray[np.int_] >>> a: NDArrayInt = np.arange(10) >>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]: ... return np.array(a) final class numpy.typing.NBitBase[source] A type representing numpy.number precision during static type checking. Used exclusively for the purpose static type checking, NBitBase represents the base of a hierarchical set of subclasses. Each subsequent subclass is herein used for representing a lower level of precision, e.g. 64Bit > 32Bit > 16Bit. New in version 1.20. Examples Below is a typical usage example: NBitBase is herein used for annotating a function that takes a float and integer of arbitrary precision as arguments and returns a new float of whichever precision is largest (e.g. np.float16 + np.int64 -> np.float64). >>> from __future__ import annotations >>> from typing import TypeVar, TYPE_CHECKING >>> import numpy as np >>> import numpy.typing as npt >>> T1 = TypeVar("T1", bound=npt.NBitBase) >>> T2 = TypeVar("T2", bound=npt.NBitBase) >>> def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[T1 | T2]: ... return a + b >>> a = np.float16() >>> b = np.int64() >>> out = add(a, b) >>> if TYPE_CHECKING: ... reveal_locals() ... # note: Revealed local types are: ... # note: a: numpy.floating[numpy.typing._16Bit*] ... # note: b: numpy.signedinteger[numpy.typing._64Bit*] ... # note: out: numpy.floating[numpy.typing._64Bit*]
numpy.reference.typing
numpy.typing.DTypeLike = typing.Union[...] A Union representing objects that can be coerced into a dtype. Among others this includes the likes of: type objects. Character codes or the names of type objects. Objects with the .dtype attribute. New in version 1.20. See Also Specifying and constructing data types A comprehensive overview of all objects that can be coerced into data types. Examples >>> import numpy as np >>> import numpy.typing as npt >>> def as_dtype(d: npt.DTypeLike) -> np.dtype: ... return np.dtype(d)
numpy.reference.typing#numpy.typing.DTypeLike
numpy.typing.NDArray = numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]][source] A generic version of np.ndarray[Any, np.dtype[+ScalarType]]. Can be used during runtime for typing arrays with a given dtype and unspecified shape. New in version 1.21. Examples >>> import numpy as np >>> import numpy.typing as npt >>> print(npt.NDArray) numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]] >>> print(npt.NDArray[np.float64]) numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]] >>> NDArrayInt = npt.NDArray[np.int_] >>> a: NDArrayInt = np.arange(10) >>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]: ... return np.array(a)
numpy.reference.typing#numpy.typing.NDArray
class numpy.ubyte[source] Unsigned integer type, compatible with C unsigned char. Character code 'B' Alias on this platform (Linux x86_64) numpy.uint8: 8-bit unsigned integer (0 to 255).
numpy.reference.arrays.scalars#numpy.ubyte
numpy.ufunc class numpy.ufunc[source] Functions that operate element by element on whole arrays. To see the documentation for a specific ufunc, use info. For example, np.info(np.sin). Because ufuncs are written in C (for speed) and linked into Python with NumPy’s ufunc facility, Python’s help() function finds this page whenever help() is called on a ufunc. A detailed explanation of ufuncs can be found in the docs for Universal functions (ufunc). Calling ufuncs: op(*x[, out], where=True, **kwargs) Apply op to the arguments *x elementwise, broadcasting the arguments. The broadcasting rules are: Dimensions of length 1 may be prepended to either array. Arrays may be repeated along dimensions of length 1. Parameters *xarray_like Input arrays. outndarray, None, or tuple of ndarray and None, optional Alternate array object(s) in which to put the result; if provided, it must have a shape that the inputs broadcast to. A tuple of arrays (possible only as a keyword argument) must have length equal to the number of outputs; use None for uninitialized outputs to be allocated by the ufunc. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns rndarray or tuple of ndarray r will have the shape that the arrays in x broadcast to; if out is provided, it will be returned. If not, r will be allocated and may contain uninitialized values. If the function has more than one output, then the result will be a tuple of arrays. Attributes identity The identity value. nargs The number of arguments. nin The number of inputs. nout The number of outputs. ntypes The number of types. signature Definition of the core elements a generalized ufunc operates on. types Returns a list with types grouped input->output. Methods __call__(*args, **kwargs) Call self as a function. accumulate(array[, axis, dtype, out]) Accumulate the result of applying the operator to all elements. at(a, indices[, b]) Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. outer(A, B, /, **kwargs) Apply the ufunc op to all pairs (a, b) with a in A and b in B. reduce(array[, axis, dtype, out, keepdims, ...]) Reduces array's dimension by one, by applying ufunc along one axis. reduceat(array, indices[, axis, dtype, out]) Performs a (local) reduce with specified slices over a single axis.
numpy.reference.generated.numpy.ufunc
class numpy.uint[source] Unsigned integer type, compatible with C unsigned long. Character code 'L' Alias on this platform (Linux x86_64) numpy.uint64: 64-bit unsigned integer (0 to 18_446_744_073_709_551_615). Alias on this platform (Linux x86_64) numpy.uintp: Unsigned integer large enough to fit pointer, compatible with C uintptr_t.
numpy.reference.arrays.scalars#numpy.uint
numpy.uint8[source] numpy.uint16 numpy.uint32 numpy.uint64 Alias for the unsigned integer types (one of numpy.ubyte, numpy.ushort, numpy.uintc, numpy.uint and numpy.ulonglong) with the specified number of bits. Compatible with the C99 uint8_t, uint16_t, uint32_t, and uint64_t, respectively.
numpy.reference.arrays.scalars#numpy.uint16
numpy.uint8[source] numpy.uint16 numpy.uint32 numpy.uint64 Alias for the unsigned integer types (one of numpy.ubyte, numpy.ushort, numpy.uintc, numpy.uint and numpy.ulonglong) with the specified number of bits. Compatible with the C99 uint8_t, uint16_t, uint32_t, and uint64_t, respectively.
numpy.reference.arrays.scalars#numpy.uint32
numpy.uint8[source] numpy.uint16 numpy.uint32 numpy.uint64 Alias for the unsigned integer types (one of numpy.ubyte, numpy.ushort, numpy.uintc, numpy.uint and numpy.ulonglong) with the specified number of bits. Compatible with the C99 uint8_t, uint16_t, uint32_t, and uint64_t, respectively.
numpy.reference.arrays.scalars#numpy.uint64
numpy.uint8[source] numpy.uint16 numpy.uint32 numpy.uint64 Alias for the unsigned integer types (one of numpy.ubyte, numpy.ushort, numpy.uintc, numpy.uint and numpy.ulonglong) with the specified number of bits. Compatible with the C99 uint8_t, uint16_t, uint32_t, and uint64_t, respectively.
numpy.reference.arrays.scalars#numpy.uint8
class numpy.uintc[source] Unsigned integer type, compatible with C unsigned int. Character code 'I' Alias on this platform (Linux x86_64) numpy.uint32: 32-bit unsigned integer (0 to 4_294_967_295).
numpy.reference.arrays.scalars#numpy.uintc
numpy.uintp[source] Alias for the unsigned integer type (one of numpy.ubyte, numpy.ushort, numpy.uintc, numpy.uint and np.ulonglong) that is the same size as a pointer. Compatible with the C uintptr_t. Character code 'P'
numpy.reference.arrays.scalars#numpy.uintp
class numpy.ulonglong[source] Signed integer type, compatible with C unsigned long long. Character code 'Q'
numpy.reference.arrays.scalars#numpy.ulonglong
numpy.unicode_[source] alias of numpy.str_
numpy.reference.arrays.scalars#numpy.unicode_
numpy.union1d numpy.union1d(ar1, ar2)[source] Find the union of two arrays. Return the unique, sorted array of values that are in either of the two input arrays. Parameters ar1, ar2array_like Input arrays. They are flattened if they are not already 1D. Returns union1dndarray Unique, sorted union of the input arrays. See also numpy.lib.arraysetops Module with a number of other functions for performing set operations on arrays. Examples >>> np.union1d([-1, 0, 1], [-2, 0, 2]) array([-2, -1, 0, 1, 2]) To find the union of more than two arrays, use functools.reduce: >>> from functools import reduce >>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2])) array([1, 2, 3, 4, 6])
numpy.reference.generated.numpy.union1d
numpy.unique numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)[source] Find the unique elements of an array. Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements: the indices of the input array that give the unique values the indices of the unique array that reconstruct the input array the number of times each unique value comes up in the input array Parameters ararray_like Input array. Unless axis is specified, this will be flattened if it is not already 1-D. return_indexbool, optional If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array. return_inversebool, optional If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar. return_countsbool, optional If True, also return the number of times each unique item appears in ar. New in version 1.9.0. axisint or None, optional The axis to operate on. If None, ar will be flattened. If an integer, the subarrays indexed by the given axis will be flattened and treated as the elements of a 1-D array with the dimension of the given axis, see the notes for more details. Object arrays or structured arrays that contain objects are not supported if the axis kwarg is used. The default is None. New in version 1.13.0. Returns uniquendarray The sorted unique values. unique_indicesndarray, optional The indices of the first occurrences of the unique values in the original array. Only provided if return_index is True. unique_inversendarray, optional The indices to reconstruct the original array from the unique array. Only provided if return_inverse is True. unique_countsndarray, optional The number of times each of the unique values comes up in the original array. Only provided if return_counts is True. New in version 1.9.0. See also numpy.lib.arraysetops Module with a number of other functions for performing set operations on arrays. repeat Repeat elements of an array. Notes When an axis is specified the subarrays indexed by the axis are sorted. This is done by making the specified axis the first dimension of the array (move the axis to the first dimension to keep the order of the other axes) and then flattening the subarrays in C order. The flattened subarrays are then viewed as a structured type with each element given a label, with the effect that we end up with a 1-D array of structured types that can be treated in the same way as any other 1-D array. The result is that the flattened subarrays are sorted in lexicographic order starting with the first element. Examples >>> np.unique([1, 1, 2, 2, 3, 3]) array([1, 2, 3]) >>> a = np.array([[1, 1], [2, 3]]) >>> np.unique(a) array([1, 2, 3]) Return the unique rows of a 2D array >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) >>> np.unique(a, axis=0) array([[1, 0, 0], [2, 3, 4]]) Return the indices of the original array that give the unique values: >>> a = np.array(['a', 'b', 'b', 'c', 'a']) >>> u, indices = np.unique(a, return_index=True) >>> u array(['a', 'b', 'c'], dtype='<U1') >>> indices array([0, 1, 3]) >>> a[indices] array(['a', 'b', 'c'], dtype='<U1') Reconstruct the input array from the unique values and inverse: >>> a = np.array([1, 2, 6, 4, 2, 3, 2]) >>> u, indices = np.unique(a, return_inverse=True) >>> u array([1, 2, 3, 4, 6]) >>> indices array([0, 1, 4, 3, 1, 2, 1]) >>> u[indices] array([1, 2, 6, 4, 2, 3, 2]) Reconstruct the input values from the unique values and counts: >>> a = np.array([1, 2, 6, 4, 2, 3, 2]) >>> values, counts = np.unique(a, return_counts=True) >>> values array([1, 2, 3, 4, 6]) >>> counts array([1, 3, 1, 1, 1]) >>> np.repeat(values, counts) array([1, 2, 2, 2, 3, 4, 6]) # original order not preserved
numpy.reference.generated.numpy.unique
numpy.unpackbits numpy.unpackbits(a, /, axis=None, count=None, bitorder='big') Unpacks elements of a uint8 array into a binary-valued output array. Each element of a represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified. Parameters andarray, uint8 type Input array. axisint, optional The dimension over which bit-unpacking is done. None implies unpacking the flattened array. countint or None, optional The number of elements to unpack along axis, provided as a way of undoing the effect of packing a size that is not a multiple of eight. A non-negative number means to only unpack count bits. A negative number means to trim off that many bits from the end. None means to unpack the entire array (the default). Counts larger than the available number of bits will add zero padding to the output. Negative counts must not exceed the available number of bits. New in version 1.17.0. bitorder{‘big’, ‘little’}, optional The order of the returned bits. ‘big’ will mimic bin(val), 3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1], ‘little’ will reverse the order to [1, 1, 0, 0, 0, 0, 0, 0]. Defaults to ‘big’. New in version 1.17.0. Returns unpackedndarray, uint8 type The elements are binary-valued (0 or 1). See also packbits Packs the elements of a binary-valued array into bits in a uint8 array. Examples >>> a = np.array([[2], [7], [23]], dtype=np.uint8) >>> a array([[ 2], [ 7], [23]], dtype=uint8) >>> b = np.unpackbits(a, axis=1) >>> b array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8) >>> c = np.unpackbits(a, axis=1, count=-3) >>> c array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0]], dtype=uint8) >>> p = np.packbits(b, axis=0) >>> np.unpackbits(p, axis=0) array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) >>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0])) True
numpy.reference.generated.numpy.unpackbits
numpy.unravel_index numpy.unravel_index(indices, shape, order='C') Converts a flat index or array of flat indices into a tuple of coordinate arrays. Parameters indicesarray_like An integer array whose elements are indices into the flattened version of an array of dimensions shape. Before version 1.6.0, this function accepted just one index value. shapetuple of ints The shape of the array to use for unraveling indices. Changed in version 1.16.0: Renamed from dims to shape. order{‘C’, ‘F’}, optional Determines whether the indices should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order. New in version 1.6.0. Returns unraveled_coordstuple of ndarray Each array in the tuple has the same shape as the indices array. See also ravel_multi_index Examples >>> np.unravel_index([22, 41, 37], (7,6)) (array([3, 6, 6]), array([4, 5, 1])) >>> np.unravel_index([31, 41, 13], (7,6), order='F') (array([3, 6, 6]), array([4, 5, 1])) >>> np.unravel_index(1621, (6,7,8,9)) (3, 1, 4, 1)
numpy.reference.generated.numpy.unravel_index
numpy.unwrap numpy.unwrap(p, discont=None, axis=- 1, *, period=6.283185307179586)[source] Unwrap by taking the complement of large deltas with respect to the period. This unwraps a signal p by changing elements which have an absolute difference from their predecessor of more than max(discont, period/2) to their period-complementary values. For the default case where period is \(2\pi\) and discont is \(\pi\), this unwraps a radian phase p such that adjacent differences are never greater than \(\pi\) by adding \(2k\pi\) for some integer \(k\). Parameters parray_like Input array. discontfloat, optional Maximum discontinuity between values, default is period/2. Values below period/2 are treated as if they were period/2. To have an effect different from the default, discont should be larger than period/2. axisint, optional Axis along which unwrap will operate, default is the last axis. period: float, optional Size of the range over which the input wraps. By default, it is 2 pi. New in version 1.21.0. Returns outndarray Output array. See also rad2deg, deg2rad Notes If the discontinuity in p is smaller than period/2, but larger than discont, no unwrapping is done because taking the complement would only make the discontinuity larger. Examples >>> phase = np.linspace(0, np.pi, num=5) >>> phase[3:] += np.pi >>> phase array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531]) # may vary >>> np.unwrap(phase) array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ]) # may vary >>> np.unwrap([0, 1, 2, -1, 0], period=4) array([0, 1, 2, 3, 4]) >>> np.unwrap([ 1, 2, 3, 4, 5, 6, 1, 2, 3], period=6) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.unwrap([2, 3, 4, 5, 2, 3, 4, 5], period=4) array([2, 3, 4, 5, 6, 7, 8, 9]) >>> phase_deg = np.mod(np.linspace(0 ,720, 19), 360) - 180 >>> np.unwrap(phase_deg, period=360) array([-180., -140., -100., -60., -20., 20., 60., 100., 140., 180., 220., 260., 300., 340., 380., 420., 460., 500., 540.])
numpy.reference.generated.numpy.unwrap
class numpy.ushort[source] Unsigned integer type, compatible with C unsigned short. Character code 'H' Alias on this platform (Linux x86_64) numpy.uint16: 16-bit unsigned integer (0 to 65_535).
numpy.reference.arrays.scalars#numpy.ushort
numpy.vander numpy.vander(x, N=None, increasing=False)[source] Generate a Vandermonde matrix. The columns of the output matrix are powers of the input vector. The order of the powers is determined by the increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression in each row is named for Alexandre- Theophile Vandermonde. Parameters xarray_like 1-D input array. Nint, optional Number of columns in the output. If N is not specified, a square array is returned (N = len(x)). increasingbool, optional Order of the powers of the columns. If True, the powers increase from left to right, if False (the default) they are reversed. New in version 1.9.0. Returns outndarray Vandermonde matrix. If increasing is False, the first column is x^(N-1), the second x^(N-2) and so forth. If increasing is True, the columns are x^0, x^1, ..., x^(N-1). See also polynomial.polynomial.polyvander Examples >>> x = np.array([1, 2, 3, 5]) >>> N = 3 >>> np.vander(x, N) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> np.column_stack([x**(N-1-i) for i in range(N)]) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> x = np.array([1, 2, 3, 5]) >>> np.vander(x) array([[ 1, 1, 1, 1], [ 8, 4, 2, 1], [ 27, 9, 3, 1], [125, 25, 5, 1]]) >>> np.vander(x, increasing=True) array([[ 1, 1, 1, 1], [ 1, 2, 4, 8], [ 1, 3, 9, 27], [ 1, 5, 25, 125]]) The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector: >>> np.linalg.det(np.vander(x)) 48.000000000000043 # may vary >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) 48
numpy.reference.generated.numpy.vander
numpy.var numpy.var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)[source] Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. Parameters aarray_like Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. axisNone or int or tuple of ints, optional Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. New in version 1.7.0. If this is a tuple of ints, a variance is performed over multiple axes, instead of a single axis or all the axes as before. dtypedata-type, optional Type to use in computing the variance. For arrays of integer type the default is float64; for arrays of float types it is the same as the array type. outndarray, optional Alternate output array in which to place the result. It must have the same shape as the expected output, but the type is cast if necessary. ddofint, optional “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of elements. By default ddof is zero. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the var method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. wherearray_like of bool, optional Elements to include in the variance. See reduce for details. New in version 1.20.0. Returns variancendarray, see dtype parameter above If out=None, returns a new array containing the variance; otherwise, a reference to the output array is returned. See also std, mean, nanmean, nanstd, nanvar Output type determination Notes The variance is the average of the squared deviations from the mean, i.e., var = mean(x), where x = abs(a - a.mean())**2. The mean is typically calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of a hypothetical infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative. For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue. Examples >>> a = np.array([[1, 2], [3, 4]]) >>> np.var(a) 1.25 >>> np.var(a, axis=0) array([1., 1.]) >>> np.var(a, axis=1) array([0.25, 0.25]) In single precision, var() can be inaccurate: >>> a = np.zeros((2, 512*512), dtype=np.float32) >>> a[0, :] = 1.0 >>> a[1, :] = 0.1 >>> np.var(a) 0.20250003 Computing the variance in float64 is more accurate: >>> np.var(a, dtype=np.float64) 0.20249999932944759 # may vary >>> ((1-0.55)**2 + (0.1-0.55)**2)/2 0.2025 Specifying a where argument: >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]]) >>> np.var(a) 6.833333333333333 # may vary >>> np.var(a, where=[[True], [True], [False]]) 4.0
numpy.reference.generated.numpy.var
numpy.vdot numpy.vdot(a, b, /) Return the dot product of two vectors. The vdot(a, b) function handles complex numbers differently than dot(a, b). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product. Note that vdot handles multidimensional arrays differently than dot: it does not perform a matrix product, but flattens input arguments to 1-D vectors first. Consequently, it should only be used for vectors. Parameters aarray_like If a is complex the complex conjugate is taken before calculation of the dot product. barray_like Second argument to the dot product. Returns outputndarray Dot product of a and b. Can be an int, float, or complex depending on the types of a and b. See also dot Return the dot product without using the complex conjugate of the first argument. Examples >>> a = np.array([1+2j,3+4j]) >>> b = np.array([5+6j,7+8j]) >>> np.vdot(a, b) (70-8j) >>> np.vdot(b, a) (70+8j) Note that higher-dimensional arrays are flattened! >>> a = np.array([[1, 4], [5, 6]]) >>> b = np.array([[4, 1], [2, 2]]) >>> np.vdot(a, b) 30 >>> np.vdot(b, a) 30 >>> 1*4 + 4*1 + 5*2 + 6*2 30
numpy.reference.generated.numpy.vdot
numpy.vectorize class numpy.vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None)[source] Generalized function class. Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns a single numpy array or a tuple of numpy arrays. The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy. The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided by specifying the otypes argument. Parameters pyfunccallable A python function or method. otypesstr or list of dtypes, optional The output data type. It must be specified as either a string of typecode characters or a list of data type specifiers. There should be one data type specifier for each output. docstr, optional The docstring for the function. If None, the docstring will be the pyfunc.__doc__. excludedset, optional Set of strings or integers representing the positional or keyword arguments for which the function will not be vectorized. These will be passed directly to pyfunc unmodified. New in version 1.7.0. cachebool, optional If True, then cache the first function call that determines the number of outputs if otypes is not provided. New in version 1.7.0. signaturestring, optional Generalized universal function signature, e.g., (m,n),(n)->(m) for vectorized matrix-vector multiplication. If provided, pyfunc will be called with (and expected to return) arrays with shapes given by the size of corresponding core dimensions. By default, pyfunc is assumed to take scalars as input and output. New in version 1.12.0. Returns vectorizedcallable Vectorized function. See also frompyfunc Takes an arbitrary Python function and returns a ufunc Notes The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop. If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive. The new keyword argument interface and excluded argument support further degrades performance. References 1 Generalized Universal Function API Examples >>> def myfunc(a, b): ... "Return a-b if a>b, otherwise return a+b" ... if a > b: ... return a - b ... else: ... return a + b >>> vfunc = np.vectorize(myfunc) >>> vfunc([1, 2, 3, 4], 2) array([3, 4, 1, 2]) The docstring is taken from the input function to vectorize unless it is specified: >>> vfunc.__doc__ 'Return a-b if a>b, otherwise return a+b' >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`') >>> vfunc.__doc__ 'Vectorized `myfunc`' The output type is determined by evaluating the first element of the input, unless it is specified: >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) <class 'numpy.int64'> >>> vfunc = np.vectorize(myfunc, otypes=[float]) >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) <class 'numpy.float64'> The excluded argument can be used to prevent vectorizing over certain arguments. This can be useful for array-like arguments of a fixed length such as the coefficients for a polynomial as in polyval: >>> def mypolyval(p, x): ... _p = list(p) ... res = _p.pop(0) ... while _p: ... res = res*x + _p.pop(0) ... return res >>> vpolyval = np.vectorize(mypolyval, excluded=['p']) >>> vpolyval(p=[1, 2, 3], x=[0, 1]) array([3, 6]) Positional arguments may also be excluded by specifying their position: >>> vpolyval.excluded.add(0) >>> vpolyval([1, 2, 3], x=[0, 1]) array([3, 6]) The signature argument allows for vectorizing functions that act on non-scalar arrays of fixed length. For example, you can use it for a vectorized calculation of Pearson correlation coefficient and its p-value: >>> import scipy.stats >>> pearsonr = np.vectorize(scipy.stats.pearsonr, ... signature='(n),(n)->(),()') >>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]]) (array([ 1., -1.]), array([ 0., 0.])) Or for a vectorized convolution: >>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)') >>> convolve(np.eye(4), [1, 2, 1]) array([[1., 2., 1., 0., 0., 0.], [0., 1., 2., 1., 0., 0.], [0., 0., 1., 2., 1., 0.], [0., 0., 0., 1., 2., 1.]]) Methods __call__(*args, **kwargs) Return arrays with the results of pyfunc broadcast (vectorized) over args and kwargs not in excluded.
numpy.reference.generated.numpy.vectorize
class numpy.void[source] Either an opaque sequence of bytes, or a structure. >>> np.void(b'abcd') void(b'\x61\x62\x63\x64') Structured void scalars can only be constructed via extraction from Structured arrays: >>> arr = np.array((1, 2), dtype=[('x', np.int8), ('y', np.int8)]) >>> arr[()] (1, 2) # looks like a tuple, but is `np.void` Character code 'V'
numpy.reference.arrays.scalars#numpy.void
numpy.vsplit numpy.vsplit(ary, indices_or_sections)[source] Split an array into multiple sub-arrays vertically (row-wise). Please refer to the split documentation. vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension. See also split Split an array into multiple sub-arrays of equal size. Examples >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]) >>> np.vsplit(x, 2) [array([[0., 1., 2., 3.], [4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.], [12., 13., 14., 15.]])] >>> np.vsplit(x, np.array([3, 6])) [array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]]), array([[12., 13., 14., 15.]]), array([], shape=(0, 4), dtype=float64)] With a higher dimensional array the split is still along the first axis. >>> x = np.arange(8.0).reshape(2, 2, 2) >>> x array([[[0., 1.], [2., 3.]], [[4., 5.], [6., 7.]]]) >>> np.vsplit(x, 2) [array([[[0., 1.], [2., 3.]]]), array([[[4., 5.], [6., 7.]]])]
numpy.reference.generated.numpy.vsplit
numpy.vstack numpy.vstack(tup)[source] Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. Parameters tupsequence of ndarrays The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Returns stackedndarray The array formed by stacking the given arrays, will be at least 2-D. See also concatenate Join a sequence of arrays along an existing axis. stack Join a sequence of arrays along a new axis. block Assemble an nd-array from nested lists of blocks. hstack Stack arrays in sequence horizontally (column wise). dstack Stack arrays in sequence depth wise (along third axis). column_stack Stack 1-D arrays as columns into a 2-D array. vsplit Split an array into multiple sub-arrays vertically (row-wise). Examples >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.vstack((a,b)) array([[1, 2, 3], [4, 5, 6]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[4], [5], [6]]) >>> np.vstack((a,b)) array([[1], [2], [3], [4], [5], [6]])
numpy.reference.generated.numpy.vstack
numpy.where numpy.where(condition, [x, y, ]/) Return elements chosen from x or y depending on condition. Note When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided. Parameters conditionarray_like, bool Where True, yield x, otherwise yield y. x, yarray_like Values from which to choose. x, y and condition need to be broadcastable to some shape. Returns outndarray An array with elements from x where condition is True, and elements from y elsewhere. See also choose nonzero The function that is called when x and y are omitted Notes If all the arrays are 1-D, where is equivalent to: [xv if c else yv for c, xv, yv in zip(condition, x, y)] Examples >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.where(a < 5, a, 10*a) array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90]) This can be used on multidimensional arrays too: >>> np.where([[True, False], [True, True]], ... [[1, 2], [3, 4]], ... [[9, 8], [7, 6]]) array([[1, 8], [3, 4]]) The shapes of x, y, and the condition are broadcast together: >>> x, y = np.ogrid[:3, :4] >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast array([[10, 0, 0, 0], [10, 11, 1, 1], [10, 11, 12, 2]]) >>> a = np.array([[0, 1, 2], ... [0, 2, 4], ... [0, 3, 6]]) >>> np.where(a < 4, a, -1) # -1 is broadcast array([[ 0, 1, 2], [ 0, 2, -1], [ 0, 3, -1]])
numpy.reference.generated.numpy.where
numpy.who numpy.who(vardict=None)[source] Print the NumPy arrays in the given dictionary. If there is no dictionary passed in or vardict is None then returns NumPy arrays in the globals() dictionary (all NumPy arrays in the namespace). Parameters vardictdict, optional A dictionary possibly containing ndarrays. Default is globals(). Returns outNone Returns ‘None’. Notes Prints out the name, shape, bytes and type of all of the ndarrays present in vardict. Examples >>> a = np.arange(10) >>> b = np.ones(20) >>> np.who() Name Shape Bytes Type =========================================================== a 10 80 int64 b 20 160 float64 Upper bound on total bytes = 240 >>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str', ... 'idx':5} >>> np.who(d) Name Shape Bytes Type =========================================================== x 2 16 float64 y 3 24 float64 Upper bound on total bytes = 40
numpy.reference.generated.numpy.who
numpy.zeros numpy.zeros(shape, dtype=float, order='C', *, like=None) Return a new array of given shape and type, filled with zeros. Parameters shapeint or tuple of ints Shape of the new array, e.g., (2, 3) or 2. dtypedata-type, optional The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64. order{‘C’, ‘F’}, optional, default: ‘C’ Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory. likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns outndarray Array of zeros with the given shape, dtype, and order. See also zeros_like Return an array of zeros with shape and type of input. empty Return a new uninitialized array. ones Return a new array setting values to one. full Return a new array of given shape filled with value. Examples >>> np.zeros(5) array([ 0., 0., 0., 0., 0.]) >>> np.zeros((5,), dtype=int) array([0, 0, 0, 0, 0]) >>> np.zeros((2, 1)) array([[ 0.], [ 0.]]) >>> s = (2,2) >>> np.zeros(s) array([[ 0., 0.], [ 0., 0.]]) >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype array([(0, 0), (0, 0)], dtype=[('x', '<i4'), ('y', '<i4')])
numpy.reference.generated.numpy.zeros
numpy.zeros_like numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None)[source] Return an array of zeros with the same shape and type as a given array. Parameters aarray_like The shape and data-type of a define these same attributes of the returned array. dtypedata-type, optional Overrides the data type of the result. New in version 1.6.0. order{‘C’, ‘F’, ‘A’, or ‘K’}, optional Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. New in version 1.6.0. subokbool, optional. If True, then the newly created array will use the sub-class type of a, otherwise it will be a base-class array. Defaults to True. shapeint or sequence of ints, optional. Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied. New in version 1.17.0. Returns outndarray Array of zeros with the same shape and type as a. See also empty_like Return an empty array with shape and type of input. ones_like Return an array of ones with shape and type of input. full_like Return a new array with shape of input filled with value. zeros Return a new array setting values to zero. Examples >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]]) >>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.zeros_like(y) array([0., 0., 0.])
numpy.reference.generated.numpy.zeros_like
Packaging (numpy.distutils) NumPy provides enhanced distutils functionality to make it easier to build and install sub-packages, auto-generate code, and extension modules that use Fortran-compiled libraries. To use features of NumPy distutils, use the setup command from numpy.distutils.core. A useful Configuration class is also provided in numpy.distutils.misc_util that can make it easier to construct keyword arguments to pass to the setup function (by passing the dictionary obtained from the todict() method of the class). More information is available in the NumPy Distutils - Users Guide. The choice and location of linked libraries such as BLAS and LAPACK as well as include paths and other such build options can be specified in a site.cfg file located in the NumPy root repository or a .numpy-site.cfg file in your home directory. See the site.cfg.example example file included in the NumPy repository or sdist for documentation. Modules in numpy.distutils distutils.misc_util ccompiler ccompiler_opt Provides the CCompilerOpt class, used for handling the CPU/hardware optimization, starting from parsing the command arguments, to managing the relation between the CPU baseline and dispatch-able features, also generating the required C headers and ending with compiling the sources with proper compiler's flags. cpuinfo.cpu core.Extension(name, sources[, ...]) Parameters exec_command exec_command log.set_verbosity(v[, force]) system_info.get_info(name[, notfound_action]) notfound_action: system_info.get_standard_file(fname) Returns a list of files named 'fname' from 1) System-wide directory (directory-location of this module) 2) Users HOME directory (os.environ['HOME']) 3) Local directory Configuration class class numpy.distutils.misc_util.Configuration(package_name=None, parent_name=None, top_path=None, package_path=None, **attrs)[source] Construct a configuration instance for the given package name. If parent_name is not None, then construct the package as a sub-package of the parent_name package. If top_path and package_path are None then they are assumed equal to the path of the file this instance was created in. The setup.py files in the numpy distribution are good examples of how to use the Configuration instance. todict()[source] Return a dictionary compatible with the keyword arguments of distutils setup function. Examples >>> setup(**config.todict()) get_distribution()[source] Return the distutils distribution object for self. get_subpackage(subpackage_name, subpackage_path=None, parent_name=None, caller_level=1)[source] Return list of subpackage configurations. Parameters subpackage_namestr or None Name of the subpackage to get the configuration. ‘*’ in subpackage_name is handled as a wildcard. subpackage_pathstr If None, then the path is assumed to be the local path plus the subpackage_name. If a setup.py file is not found in the subpackage_path, then a default configuration is used. parent_namestr Parent name. add_subpackage(subpackage_name, subpackage_path=None, standalone=False)[source] Add a sub-package to the current Configuration instance. This is useful in a setup.py script for adding sub-packages to a package. Parameters subpackage_namestr name of the subpackage subpackage_pathstr if given, the subpackage path such as the subpackage is in subpackage_path / subpackage_name. If None,the subpackage is assumed to be located in the local path / subpackage_name. standalonebool add_data_files(*files)[source] Add data files to configuration data_files. Parameters filessequence Argument(s) can be either 2-sequence (<datadir prefix>,<path to data file(s)>) paths to data files where python datadir prefix defaults to package dir. Notes The form of each element of the files sequence is very flexible allowing many combinations of where to get the files from the package and where they should ultimately be installed on the system. The most basic usage is for an element of the files argument sequence to be a simple filename. This will cause that file from the local path to be installed to the installation path of the self.name package (package path). The file argument can also be a relative path in which case the entire relative path will be installed into the package directory. Finally, the file can be an absolute path name in which case the file will be found at the absolute path name but installed to the package path. This basic behavior can be augmented by passing a 2-tuple in as the file argument. The first element of the tuple should specify the relative path (under the package install directory) where the remaining sequence of files should be installed to (it has nothing to do with the file-names in the source distribution). The second element of the tuple is the sequence of files that should be installed. The files in this sequence can be filenames, relative paths, or absolute paths. For absolute paths the file will be installed in the top-level package installation directory (regardless of the first argument). Filenames and relative path names will be installed in the package install directory under the path name given as the first element of the tuple. Rules for installation paths: file.txt -> (., file.txt)-> parent/file.txt foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt *.txt -> parent/a.txt, parent/b.txt foo/*.txt`` -> parent/foo/a.txt, parent/foo/b.txt */*.txt -> (*, */*.txt) -> parent/c/a.txt, parent/d/b.txt (sun, file.txt) -> parent/sun/file.txt (sun, bar/file.txt) -> parent/sun/file.txt (sun, /foo/bar/file.txt) -> parent/sun/file.txt (sun, *.txt) -> parent/sun/a.txt, parent/sun/b.txt (sun, bar/*.txt) -> parent/sun/a.txt, parent/sun/b.txt (sun/*, */*.txt) -> parent/sun/c/a.txt, parent/d/b.txt An additional feature is that the path to a data-file can actually be a function that takes no arguments and returns the actual path(s) to the data-files. This is useful when the data files are generated while building the package. Examples Add files to the list of data_files to be included with the package. >>> self.add_data_files('foo.dat', ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']), ... 'bar/cat.dat', ... '/full/path/to/can.dat') will install these data files to: <package install directory>/ foo.dat fun/ gun.dat nun/ pun.dat sun.dat bar/ car.dat can.dat where <package install directory> is the package (or sub-package) directory such as ‘/usr/lib/python2.4/site-packages/mypackage’ (‘C: Python2.4 Lib site-packages mypackage’) or ‘/usr/lib/python2.4/site- packages/mypackage/mysubpackage’ (‘C: Python2.4 Lib site-packages mypackage mysubpackage’). add_data_dir(data_path)[source] Recursively add files under data_path to data_files list. Recursively add files under data_path to the list of data_files to be installed (and distributed). The data_path can be either a relative path-name, or an absolute path-name, or a 2-tuple where the first argument shows where in the install directory the data directory should be installed to. Parameters data_pathseq or str Argument can be either 2-sequence (<datadir suffix>, <path to data directory>) path to data directory where python datadir suffix defaults to package dir. Notes Rules for installation paths: foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar (gun, foo/bar) -> parent/gun foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun (gun/*, foo/*) -> parent/gun/a, parent/gun/b /foo/bar -> (bar, /foo/bar) -> parent/bar (gun, /foo/bar) -> parent/gun (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar Examples For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat: >>> self.add_data_dir('fun') >>> self.add_data_dir(('sun', 'fun')) >>> self.add_data_dir(('gun', '/full/path/to/fun')) Will install data-files to the locations: <package install directory>/ fun/ foo.dat bar/ car.dat sun/ foo.dat bar/ car.dat gun/ foo.dat car.dat add_include_dirs(*paths)[source] Add paths to configuration include directories. Add the given sequence of paths to the beginning of the include_dirs list. This list will be visible to all extension modules of the current package. add_headers(*files)[source] Add installable headers to configuration. Add the given sequence of files to the beginning of the headers list. By default, headers will be installed under <python- include>/<self.name.replace(‘.’,’/’)>/ directory. If an item of files is a tuple, then its first argument specifies the actual installation location relative to the <python-include> path. Parameters filesstr or seq Argument(s) can be either: 2-sequence (<includedir suffix>,<path to header file(s)>) path(s) to header file(s) where python includedir suffix will default to package name. add_extension(name, sources, **kw)[source] Add extension to configuration. Create and add an Extension instance to the ext_modules list. This method also takes the following optional keyword arguments that are passed on to the Extension constructor. Parameters namestr name of the extension sourcesseq list of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. include_dirs : define_macros : undef_macros : library_dirs : libraries : runtime_library_dirs : extra_objects : extra_compile_args : extra_link_args : extra_f77_compile_args : extra_f90_compile_args : export_symbols : swig_opts : depends : The depends list contains paths to files or directories that the sources of the extension module depend on. If any path in the depends list is newer than the extension module, then the module will be rebuilt. language : f2py_options : module_dirs : extra_infodict or list dict or list of dict of keywords to be appended to keywords. Notes The self.paths(…) method is applied to all lists that may contain paths. add_library(name, sources, **build_info)[source] Add library to configuration. Parameters namestr Name of the extension. sourcessequence List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. build_infodict, optional The following keys are allowed: depends macros include_dirs extra_compiler_args extra_f77_compile_args extra_f90_compile_args f2py_options language add_scripts(*files)[source] Add scripts to configuration. Add the sequence of files to the beginning of the scripts list. Scripts will be installed under the <prefix>/bin/ directory. add_installed_library(name, sources, install_dir, build_info=None)[source] Similar to add_library, but the specified library is installed. Most C libraries used with distutils are only used to build python extensions, but libraries built through this method will be installed so that they can be reused by third-party packages. Parameters namestr Name of the installed library. sourcessequence List of the library’s source files. See add_library for details. install_dirstr Path to install the library, relative to the current sub-package. build_infodict, optional The following keys are allowed: depends macros include_dirs extra_compiler_args extra_f77_compile_args extra_f90_compile_args f2py_options language Returns None See also add_library, add_npy_pkg_config, get_info Notes The best way to encode the options required to link against the specified C libraries is to use a “libname.ini” file, and use get_info to retrieve the required options (see add_npy_pkg_config for more information). add_npy_pkg_config(template, install_dir, subst_dict=None)[source] Generate and install a npy-pkg config file from a template. The config file generated from template is installed in the given install directory, using subst_dict for variable substitution. Parameters templatestr The path of the template, relatively to the current package path. install_dirstr Where to install the npy-pkg config file, relatively to the current package path. subst_dictdict, optional If given, any string of the form @key@ will be replaced by subst_dict[key] in the template file when installed. The install prefix is always available through the variable @prefix@, since the install prefix is not easy to get reliably from setup.py. See also add_installed_library, get_info Notes This works for both standard installs and in-place builds, i.e. the @prefix@ refer to the source directory for in-place builds. Examples config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar}) Assuming the foo.ini.in file has the following content: [meta] Name=@foo@ Version=1.0 Description=dummy description [default] Cflags=-I@prefix@/include Libs= The generated file will have the following content: [meta] Name=bar Version=1.0 Description=dummy description [default] Cflags=-Iprefix_dir/include Libs= and will be installed as foo.ini in the ‘lib’ subpath. When cross-compiling with numpy distutils, it might be necessary to use modified npy-pkg-config files. Using the default/generated files will link with the host libraries (i.e. libnpymath.a). For cross-compilation you of-course need to link with target libraries, while using the host Python installation. You can copy out the numpy/core/lib/npy-pkg-config directory, add a pkgdir value to the .ini files and set NPY_PKG_CONFIG_PATH environment variable to point to the directory with the modified npy-pkg-config files. Example npymath.ini modified for cross-compilation: [meta] Name=npymath Description=Portable, core math library implementing C99 standard Version=0.1 [variables] pkgname=numpy.core pkgdir=/build/arm-linux-gnueabi/sysroot/usr/lib/python3.7/site-packages/numpy/core prefix=${pkgdir} libdir=${prefix}/lib includedir=${prefix}/include [default] Libs=-L${libdir} -lnpymath Cflags=-I${includedir} Requires=mlib [msvc] Libs=/LIBPATH:${libdir} npymath.lib Cflags=/INCLUDE:${includedir} Requires=mlib paths(*paths, **kws)[source] Apply glob to paths and prepend local_path if needed. Applies glob.glob(…) to each path in the sequence (if needed) and pre-pends the local_path if needed. Because this is called on all source lists, this allows wildcard characters to be specified in lists of sources for extension modules and libraries and scripts and allows path-names be relative to the source directory. get_config_cmd()[source] Returns the numpy.distutils config command instance. get_build_temp_dir()[source] Return a path to a temporary directory where temporary files should be placed. have_f77c()[source] Check for availability of Fortran 77 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled successfully). have_f90c()[source] Check for availability of Fortran 90 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes True if a Fortran 90 compiler is available (because a simple Fortran 90 code was able to be compiled successfully) get_version(version_file=None, version_variable=None)[source] Try to get version string of a package. Return a version string of the current package or None if the version information could not be detected. Notes This method scans files named __version__.py, <packagename>_version.py, version.py, and __svn_version__.py for string variables version, __version__, and <packagename>_version, until a version number is found. make_svn_version_py(delete=True)[source] Appends a data function to the data_files list that will generate __svn_version__.py file to the current package directory. Generate package __svn_version__.py file from SVN revision number, it will be removed after python exits but will be available when sdist, etc commands are executed. Notes If __svn_version__.py existed before, nothing is done. This is intended for working with source directories that are in an SVN repository. make_config_py(name='__config__')[source] Generate package __config__.py file containing system_info information used during building the package. This file is installed to the package installation directory. get_info(*names)[source] Get resources information. Return information (from system_info.get_info) for all of the names in the argument list in a single dictionary. Building Installable C libraries Conventional C libraries (installed through add_library) are not installed, and are just used during the build (they are statically linked). An installable C library is a pure C library, which does not depend on the python C runtime, and is installed such that it may be used by third-party packages. To build and install the C library, you just use the method add_installed_library instead of add_library, which takes the same arguments except for an additional install_dir argument: .. hidden in a comment so as to be included in refguide but not rendered documentation >>> import numpy.distutils.misc_util >>> config = np.distutils.misc_util.Configuration(None, '', '.') >>> with open('foo.c', 'w') as f: pass >>> config.add_installed_library('foo', sources=['foo.c'], install_dir='lib') npy-pkg-config files To make the necessary build options available to third parties, you could use the npy-pkg-config mechanism implemented in numpy.distutils. This mechanism is based on a .ini file which contains all the options. A .ini file is very similar to .pc files as used by the pkg-config unix utility: [meta] Name: foo Version: 1.0 Description: foo library [variables] prefix = /home/user/local libdir = ${prefix}/lib includedir = ${prefix}/include [default] cflags = -I${includedir} libs = -L${libdir} -lfoo Generally, the file needs to be generated during the build, since it needs some information known at build time only (e.g. prefix). This is mostly automatic if one uses the Configuration method add_npy_pkg_config. Assuming we have a template file foo.ini.in as follows: [meta] Name: foo Version: @version@ Description: foo library [variables] prefix = @prefix@ libdir = ${prefix}/lib includedir = ${prefix}/include [default] cflags = -I${includedir} libs = -L${libdir} -lfoo and the following code in setup.py: >>> config.add_installed_library('foo', sources=['foo.c'], install_dir='lib') >>> subst = {'version': '1.0'} >>> config.add_npy_pkg_config('foo.ini.in', 'lib', subst_dict=subst) This will install the file foo.ini into the directory package_dir/lib, and the foo.ini file will be generated from foo.ini.in, where each @version@ will be replaced by subst_dict['version']. The dictionary has an additional prefix substitution rule automatically added, which contains the install prefix (since this is not easy to get from setup.py). npy-pkg-config files can also be installed at the same location as used for numpy, using the path returned from get_npy_pkg_dir function. Reusing a C library from another package Info are easily retrieved from the get_info function in numpy.distutils.misc_util: >>> info = np.distutils.misc_util.get_info('npymath') >>> config.add_extension('foo', sources=['foo.c'], extra_info=info) An additional list of paths to look for .ini files can be given to get_info. Conversion of .src files NumPy distutils supports automatic conversion of source files named <somefile>.src. This facility can be used to maintain very similar code blocks requiring only simple changes between blocks. During the build phase of setup, if a template file named <somefile>.src is encountered, a new file named <somefile> is constructed from the template and placed in the build directory to be used instead. Two forms of template conversion are supported. The first form occurs for files named <file>.ext.src where ext is a recognized Fortran extension (f, f90, f95, f77, for, ftn, pyf). The second form is used for all other cases. See Conversion of .src files using Templates.
numpy.reference.distutils
paths(*paths, **kws)[source] Apply glob to paths and prepend local_path if needed. Applies glob.glob(…) to each path in the sequence (if needed) and pre-pends the local_path if needed. Because this is called on all source lists, this allows wildcard characters to be specified in lists of sources for extension modules and libraries and scripts and allows path-names be relative to the source directory.
numpy.reference.distutils#numpy.distutils.misc_util.Configuration.paths
Performance Recommendation The recommended generator for general use is PCG64 or its upgraded variant PCG64DXSM for heavily-parallel use cases. They are statistically high quality, full-featured, and fast on most platforms, but somewhat slow when compiled for 32-bit processes. See Upgrading PCG64 with PCG64DXSM for details on when heavy parallelism would indicate using PCG64DXSM. Philox is fairly slow, but its statistical properties have very high quality, and it is easy to get an assuredly-independent stream by using unique keys. If that is the style you wish to use for parallel streams, or you are porting from another system that uses that style, then Philox is your choice. SFC64 is statistically high quality and very fast. However, it lacks jumpability. If you are not using that capability and want lots of speed, even on 32-bit processes, this is your choice. MT19937 fails some statistical tests and is not especially fast compared to modern PRNGs. For these reasons, we mostly do not recommend using it on its own, only through the legacy RandomState for reproducing old results. That said, it has a very long history as a default in many systems. Timings The timings below are the time in ns to produce 1 random value from a specific distribution. The original MT19937 generator is much slower since it requires 2 32-bit values to equal the output of the faster generators. Integer performance has a similar ordering. The pattern is similar for other, more complex generators. The normal performance of the legacy RandomState generator is much lower than the other since it uses the Box-Muller transform rather than the Ziggurat method. The performance gap for Exponentials is also large due to the cost of computing the log function to invert the CDF. The column labeled MT19973 uses the same 32-bit generator as RandomState but produces random variates using Generator. MT19937 PCG64 PCG64DXSM Philox SFC64 RandomState 32-bit Unsigned Ints 3.3 1.9 2.0 3.3 1.8 3.1 64-bit Unsigned Ints 5.6 3.2 2.9 4.9 2.5 5.5 Uniforms 5.9 3.1 2.9 5.0 2.6 6.0 Normals 13.9 10.8 10.5 12.0 8.3 56.8 Exponentials 9.1 6.0 5.8 8.1 5.4 63.9 Gammas 37.2 30.8 28.9 34.0 27.5 77.0 Binomials 21.3 17.4 17.6 19.3 15.6 21.4 Laplaces 73.2 72.3 76.1 73.0 72.3 82.5 Poissons 111.7 103.4 100.5 109.4 90.7 115.2 The next table presents the performance in percentage relative to values generated by the legacy generator, RandomState(MT19937()). The overall performance was computed using a geometric mean. MT19937 PCG64 PCG64DXSM Philox SFC64 32-bit Unsigned Ints 96 162 160 96 175 64-bit Unsigned Ints 97 171 188 113 218 Uniforms 102 192 206 121 233 Normals 409 526 541 471 684 Exponentials 701 1071 1101 784 1179 Gammas 207 250 266 227 281 Binomials 100 123 122 111 138 Laplaces 113 114 108 113 114 Poissons 103 111 115 105 127 Overall 159 219 225 174 251 Note All timings were taken using Linux on an AMD Ryzen 9 3900X processor. Performance on different Operating Systems Performance differs across platforms due to compiler and hardware availability (e.g., register width) differences. The default bit generator has been chosen to perform well on 64-bit platforms. Performance on 32-bit operating systems is very different. The values reported are normalized relative to the speed of MT19937 in each table. A value of 100 indicates that the performance matches the MT19937. Higher values indicate improved performance. These values cannot be compared across tables. 64-bit Linux Distribution MT19937 PCG64 PCG64DXSM Philox SFC64 32-bit Unsigned Ints 100 168 166 100 182 64-bit Unsigned Ints 100 176 193 116 224 Uniforms 100 188 202 118 228 Normals 100 128 132 115 167 Exponentials 100 152 157 111 168 Overall 100 161 168 112 192 64-bit Windows The relative performance on 64-bit Linux and 64-bit Windows is broadly similar with the notable exception of the Philox generator. Distribution MT19937 PCG64 PCG64DXSM Philox SFC64 32-bit Unsigned Ints 100 155 131 29 150 64-bit Unsigned Ints 100 157 143 25 154 Uniforms 100 151 144 24 155 Normals 100 129 128 37 150 Exponentials 100 150 145 28 159 Overall 100 148 138 28 154 32-bit Windows The performance of 64-bit generators on 32-bit Windows is much lower than on 64-bit operating systems due to register width. MT19937, the generator that has been in NumPy since 2005, operates on 32-bit integers. Distribution MT19937 PCG64 PCG64DXSM Philox SFC64 32-bit Unsigned Ints 100 24 34 14 57 64-bit Unsigned Ints 100 21 32 14 74 Uniforms 100 21 34 16 73 Normals 100 36 57 28 101 Exponentials 100 28 44 20 88 Overall 100 25 39 18 77 Note Linux timings used Ubuntu 20.04 and GCC 9.3.0. Windows timings were made on Windows 10 using Microsoft C/C++ Optimizing Compiler Version 19 (Visual Studio 2019). All timings were produced on an AMD Ryzen 9 3900X processor.
numpy.reference.random.performance
Poly1d Basics poly1d(c_or_r[, r, variable]) A one-dimensional polynomial class. polyval(p, x) Evaluate a polynomial at specific values. poly(seq_of_zeros) Find the coefficients of a polynomial with the given sequence of roots. roots(p) Return the roots of a polynomial with coefficients given in p. Fitting polyfit(x, y, deg[, rcond, full, w, cov]) Least squares polynomial fit. Calculus polyder(p[, m]) Return the derivative of the specified order of a polynomial. polyint(p[, m, k]) Return an antiderivative (indefinite integral) of a polynomial. Arithmetic polyadd(a1, a2) Find the sum of two polynomials. polydiv(u, v) Returns the quotient and remainder of polynomial division. polymul(a1, a2) Find the product of two polynomials. polysub(a1, a2) Difference (subtraction) of two polynomials. Warnings RankWarning Issued by polyfit when the Vandermonde matrix is rank deficient.
numpy.reference.routines.polynomials.poly1d
numpy.poly1d.__call__ method poly1d.__call__(val)[source] Call self as a function.
numpy.reference.generated.numpy.poly1d.__call__
numpy.poly1d.deriv method poly1d.deriv(m=1)[source] Return a derivative of this polynomial. Refer to polyder for full documentation. See also polyder equivalent function
numpy.reference.generated.numpy.poly1d.deriv
numpy.poly1d.integ method poly1d.integ(m=1, k=0)[source] Return an antiderivative (indefinite integral) of this polynomial. Refer to polyint for full documentation. See also polyint equivalent function
numpy.reference.generated.numpy.poly1d.integ
numpy.polynomial.chebyshev.cheb2poly polynomial.chebyshev.cheb2poly(c)[source] Convert a Chebyshev series to a polynomial. Convert an array representing the coefficients of a Chebyshev series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the “standard” basis) ordered from lowest to highest degree. Parameters carray_like 1-D array containing the Chebyshev series coefficients, ordered from lowest order term to highest. Returns polndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the “standard” basis) ordered from lowest order term to highest. See also poly2cheb Notes The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples >>> from numpy import polynomial as P >>> c = P.Chebyshev(range(4)) >>> c Chebyshev([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1]) >>> p = c.convert(kind=P.Polynomial) >>> p Polynomial([-2., -8., 4., 12.], domain=[-1., 1.], window=[-1., 1.]) >>> P.chebyshev.cheb2poly(range(4)) array([-2., -8., 4., 12.])
numpy.reference.generated.numpy.polynomial.chebyshev.cheb2poly
numpy.polynomial.chebyshev.chebadd polynomial.chebyshev.chebadd(c1, c2)[source] Add one Chebyshev series to another. Returns the sum of two Chebyshev series c1 + c2. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series T_0 + 2*T_1 + 3*T_2. Parameters c1, c2array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns outndarray Array representing the Chebyshev series of their sum. See also chebsub, chebmulx, chebmul, chebdiv, chebpow Notes Unlike multiplication, division, etc., the sum of two Chebyshev series is a Chebyshev series (without having to “reproject” the result onto the basis set) so addition, just like that of “standard” polynomials, is simply “component-wise.” Examples >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebadd(c1,c2) array([4., 4., 4.])
numpy.reference.generated.numpy.polynomial.chebyshev.chebadd
numpy.polynomial.chebyshev.chebcompanion polynomial.chebyshev.chebcompanion(c)[source] Return the scaled companion matrix of c. The basis polynomials are scaled so that the companion matrix is symmetric when c is a Chebyshev basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if numpy.linalg.eigvalsh is used to obtain them. Parameters carray_like 1-D array of Chebyshev series coefficients ordered from low to high degree. Returns matndarray Scaled companion matrix of dimensions (deg, deg). Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebcompanion
numpy.polynomial.chebyshev.chebder polynomial.chebyshev.chebder(c, m=1, scl=1, axis=0)[source] Differentiate a Chebyshev series. Returns the Chebyshev series 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 series 1*T_0 + 2*T_1 + 3*T_2 while [[1,2],[1,2]] represents 1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y) if axis=0 is x and axis=1 is y. Parameters carray_like Array of Chebyshev series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. mint, optional Number of derivatives taken, must be non-negative. (Default: 1) sclscalar, optional Each differentiation is multiplied by scl. The end result is multiplication by scl**m. This is for use in a linear change of variable. (Default: 1) axisint, optional Axis over which the derivative is taken. (Default: 0). New in version 1.7.0. Returns derndarray Chebyshev series of the derivative. See also chebint Notes In general, the result of differentiating 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. Examples >>> from numpy.polynomial import chebyshev as C >>> c = (1,2,3,4) >>> C.chebder(c) array([14., 12., 24.]) >>> C.chebder(c,3) array([96.]) >>> C.chebder(c,scl=-1) array([-14., -12., -24.]) >>> C.chebder(c,2,-1) array([12., 96.])
numpy.reference.generated.numpy.polynomial.chebyshev.chebder
numpy.polynomial.chebyshev.chebdiv polynomial.chebyshev.chebdiv(c1, c2)[source] Divide one Chebyshev series by another. Returns the quotient-with-remainder of two Chebyshev series c1 / c2. The arguments are sequences of coefficients from lowest order “term” to highest, e.g., [1,2,3] represents the series T_0 + 2*T_1 + 3*T_2. Parameters c1, c2array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns [quo, rem]ndarrays Of Chebyshev series coefficients representing the quotient and remainder. See also chebadd, chebsub, chebmulx, chebmul, chebpow Notes In general, the (polynomial) division of one C-series by another results in quotient and remainder terms that are not in the Chebyshev polynomial basis set. Thus, to express these results as C-series, it is typically necessary to “reproject” the results onto said basis set, which typically produces “unintuitive” (but correct) results; see Examples section below. Examples >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not (array([3.]), array([-8., -4.])) >>> c2 = (0,1,2,3) >>> C.chebdiv(c2,c1) # neither "intuitive" (array([0., 2.]), array([-2., -4.]))
numpy.reference.generated.numpy.polynomial.chebyshev.chebdiv
numpy.polynomial.chebyshev.chebdomain polynomial.chebyshev.chebdomain = array([-1, 1]) An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array. Parameters (for the __new__ method; see Notes below) shapetuple of ints Shape of created array. dtypedata-type, optional Any object that can be interpreted as a numpy data type. bufferobject exposing buffer interface, optional Used to fill the array with data. offsetint, optional Offset of array data in buffer. stridestuple of ints, optional Strides of data in memory. order{‘C’, ‘F’}, optional Row-major (C-style) or column-major (Fortran-style) order. See also array Construct an array. zeros Create an array, each element of which is zero. empty Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”). dtype Create a data-type. numpy.typing.NDArray An ndarray alias generic w.r.t. its dtype.type. Notes There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted. No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F') array([[0.0e+000, 0.0e+000], # random [ nan, 2.5e-323]]) Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3]) Attributes Tndarray Transpose of the array. databuffer The array’s elements, in memory. dtypedtype object Describes the format of the elements in the array. flagsdict Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc. flatnumpy.flatiter object Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO). imagndarray Imaginary part of the array. realndarray Real part of the array. sizeint Number of elements in the array. itemsizeint The memory use of each array element in bytes. nbytesint The total number of bytes required to store the array data, i.e., itemsize * size. ndimint The array’s number of dimensions. shapetuple of ints Shape of the array. stridestuple of ints The step-size required to move from one element to the next in memory. For example, a contiguous (3, 4) array of type int16 in C-order has strides (8, 2). This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (2 * 4). ctypesctypes object Class containing properties of the array needed for interaction with ctypes. basendarray If the array is a view into another array, that array is its base (unless that array is also a view). The base array is where the array data is actually stored.
numpy.reference.generated.numpy.polynomial.chebyshev.chebdomain
numpy.polynomial.chebyshev.chebfit polynomial.chebyshev.chebfit(x, y, deg, rcond=None, full=False, w=None)[source] Least squares fit of Chebyshev series to data. Return the coefficients of a Chebyshev series of degree deg that is the least squares fit to the data values y given at points x. If y is 1-D the returned coefficients will also be 1-D. If y is 2-D multiple fits are done, one for each column of y, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form \[p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x),\] where n is deg. Parameters xarray_like, shape (M,) x-coordinates of the M sample points (x[i], y[i]). yarray_like, shape (M,) or (M, K) y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column. degint or 1-D array_like Degree(s) of the fitting polynomials. If deg is a single integer, all terms up to and including the deg’th term are included in the fit. For NumPy versions >= 1.11.0 a list of integers specifying the degrees of the terms to include may be used instead. rcondfloat, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases. fullbool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. warray_like, shape (M,), optional Weights. If not None, the weight w[i] applies to the unsquared residual y[i] - y_hat[i] at x[i]. Ideally the weights are chosen so that the errors of the products w[i]*y[i] all have the same variance. When using inverse-variance weighting, use w[i] = 1/sigma(y[i]). The default value is None. New in version 1.5.0. Returns coefndarray, shape (M,) or (M, K) Chebyshev coefficients ordered from low to high. If y was 2-D, the coefficients for the data in column k of y are in column k. [residuals, rank, singular_values, rcond]list These values are only returned if full == True residuals – sum of squared residuals of the least squares fit rank – the numerical rank of the scaled Vandermonde matrix singular_values – singular values of the scaled Vandermonde matrix rcond – value of rcond. For more details, see numpy.linalg.lstsq. Warns RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if full == False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', np.RankWarning) See also numpy.polynomial.polynomial.polyfit numpy.polynomial.legendre.legfit numpy.polynomial.laguerre.lagfit numpy.polynomial.hermite.hermfit numpy.polynomial.hermite_e.hermefit chebval Evaluates a Chebyshev series. chebvander Vandermonde matrix of Chebyshev series. chebweight Chebyshev weight function. numpy.linalg.lstsq Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline Computes spline fits. Notes The solution is the coefficients of the Chebyshev series p that minimizes the sum of the weighted squared errors \[E = \sum_j w_j^2 * |y_j - p(x_j)|^2,\] where \(w_j\) are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation \[V(x) * c = w * y,\] where V is the weighted pseudo Vandermonde matrix of x, c are the coefficients to be solved for, w are the weights, and y are the observed values. This equation is then solved using the singular value decomposition of V. If some of the singular values of V are so small that they are neglected, then a RankWarning will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. 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. Fits using Chebyshev series are usually better conditioned than fits using power series, but much can 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. References 1 Wikipedia, “Curve fitting”, https://en.wikipedia.org/wiki/Curve_fitting
numpy.reference.generated.numpy.polynomial.chebyshev.chebfit
numpy.polynomial.chebyshev.chebfromroots polynomial.chebyshev.chebfromroots(roots)[source] Generate a Chebyshev series with given roots. The function returns the coefficients of the polynomial \[p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\] in Chebyshev 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 \[p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x)\] The coefficient of the last term is not generally 1 for monic polynomials in Chebyshev form. Parameters rootsarray_like Sequence containing the roots. Returns outndarray 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 numpy.polynomial.polynomial.polyfromroots numpy.polynomial.legendre.legfromroots numpy.polynomial.laguerre.lagfromroots numpy.polynomial.hermite.hermfromroots numpy.polynomial.hermite_e.hermefromroots Examples >>> import numpy.polynomial.chebyshev as C >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis array([ 0. , -0.25, 0. , 0.25]) >>> j = complex(0,1) >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis array([1.5+0.j, 0. +0.j, 0.5+0.j])
numpy.reference.generated.numpy.polynomial.chebyshev.chebfromroots
numpy.polynomial.chebyshev.chebgauss polynomial.chebyshev.chebgauss(deg)[source] Gauss-Chebyshev quadrature. Computes the sample points and weights for Gauss-Chebyshev 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/\sqrt{1 - x^2}\). Parameters degint Number of sample points and weights. It must be >= 1. Returns xndarray 1-D ndarray containing the sample points. yndarray 1-D ndarray containing the weights. Notes New in version 1.7.0. The results have only been tested up to degree 100, higher degrees may be problematic. For Gauss-Chebyshev there are closed form solutions for the sample points and weights. If n = deg, then \[x_i = \cos(\pi (2 i - 1) / (2 n))\] \[w_i = \pi / n\]
numpy.reference.generated.numpy.polynomial.chebyshev.chebgauss
numpy.polynomial.chebyshev.chebgrid2d polynomial.chebyshev.chebgrid2d(x, y, c)[source] Evaluate a 2-D Chebyshev series on the Cartesian product of x and y. This function returns the values: \[p(a,b) = \sum_{i,j} c_{i,j} * T_i(a) * T_j(b),\] where the points (a, b) consist of all pairs formed by taking a from x and b from y. The resulting points form a grid with x in the first dimension and y in the second. The parameters x and y are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either x and y or their elements must support multiplication and addition both with themselves and with the elements of c. If c has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape + y.shape. Parameters x, yarray_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of x and y. If x or y is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn’t an ndarray, it is treated as a scalar. carray_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in c[i,j]. If c has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns valuesndarray, compatible object The values of the two dimensional Chebyshev series at points in the Cartesian product of x and y. See also chebval, chebval2d, chebval3d, chebgrid3d Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebgrid2d
numpy.polynomial.chebyshev.chebgrid3d polynomial.chebyshev.chebgrid3d(x, y, z, c)[source] Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z. This function returns the values: \[p(a,b,c) = \sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)\] where the points (a, b, c) consist of all triples formed by taking a from x, b from y, and c from z. The resulting points form a grid with x in the first dimension, y in the second, and z in the third. The parameters x, y, and z are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either x, y, and z or their elements must support multiplication and addition both with themselves and with the elements of c. If c has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters x, y, zarray_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of x, y, and z. If x,`y`, or z is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn’t an ndarray, it is treated as a scalar. carray_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in c[i,j]. If c has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns valuesndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of x and y. See also chebval, chebval2d, chebgrid2d, chebval3d Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebgrid3d
numpy.polynomial.chebyshev.chebint polynomial.chebyshev.chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0)[source] Integrate a Chebyshev series. Returns the Chebyshev 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 T_0 + 2*T_1 + 3*T_2 while [[1,2],[1,2]] represents 1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y) if axis=0 is x and axis=1 is y. Parameters carray_like Array of Chebyshev series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. mint, optional Order of integration, must be positive. (Default: 1) k{[], list, scalar}, optional Integration constant(s). The value of the first integral at zero is the first value in the list, the value of the second integral at zero is the second value, etc. If k == [] (the default), all constants are set to zero. If m == 1, a single scalar can be given instead of a list. lbndscalar, optional The lower bound of the integral. (Default: 0) sclscalar, optional Following each integration the result is multiplied by scl before the integration constant is added. (Default: 1) axisint, optional Axis over which the integral is taken. (Default: 0). New in version 1.7.0. Returns Sndarray C-series coefficients of the integral. Raises ValueError If m < 1, len(k) > m, np.ndim(lbnd) != 0, or np.ndim(scl) != 0. See also chebder Notes Note that the result of each integration is multiplied by scl. Why is this important to note? Say one is making a linear change of variable \(u = ax + b\) in an integral relative to x. Then \(dx = du/a\), so one will need to set scl equal to \(1/a\)- perhaps not what one would have first thought. 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. Examples >>> from numpy.polynomial import chebyshev as C >>> c = (1,2,3) >>> C.chebint(c) array([ 0.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,3) array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, # may vary 0.00625 ]) >>> C.chebint(c, k=3) array([ 3.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,lbnd=-2) array([ 8.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,scl=-2) array([-1., 1., -1., -1.])
numpy.reference.generated.numpy.polynomial.chebyshev.chebint
numpy.polynomial.chebyshev.chebinterpolate polynomial.chebyshev.chebinterpolate(func, deg, args=())[source] Interpolate a function at the Chebyshev points of the first kind. Returns the Chebyshev series that interpolates func at the Chebyshev points of the first kind in the interval [-1, 1]. The interpolating series tends to a minmax approximation to func with increasing deg if the function is continuous in the interval. New in version 1.14.0. Parameters funcfunction The function to be approximated. It must be a function of a single variable of the form f(x, a, b, c...), where a, b, c... are extra arguments passed in the args parameter. degint Degree of the interpolating polynomial argstuple, optional Extra arguments to be used in the function call. Default is no extra arguments. Returns coefndarray, shape (deg + 1,) Chebyshev coefficients of the interpolating series ordered from low to high. Notes The Chebyshev polynomials used in the interpolation are orthogonal when sampled at the Chebyshev points of the first kind. If it is desired to constrain some of the coefficients they can simply be set to the desired value after the interpolation, no new interpolation or fit is needed. This is especially useful if it is known apriori that some of coefficients are zero. For instance, if the function is even then the coefficients of the terms of odd degree in the result can be set to zero. Examples >>> import numpy.polynomial.chebyshev as C >>> C.chebfromfunction(lambda x: np.tanh(x) + 0.5, 8) array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17, -5.42457905e-02, -2.71387850e-16, 4.51658839e-03, 2.46716228e-17, -3.79694221e-04, -3.26899002e-16])
numpy.reference.generated.numpy.polynomial.chebyshev.chebinterpolate
numpy.polynomial.chebyshev.chebline polynomial.chebyshev.chebline(off, scl)[source] Chebyshev series whose graph is a straight line. Parameters off, sclscalars The specified line is given by off + scl*x. Returns yndarray This module’s representation of the Chebyshev series for off + scl*x. See also numpy.polynomial.polynomial.polyline numpy.polynomial.legendre.legline numpy.polynomial.laguerre.lagline numpy.polynomial.hermite.hermline numpy.polynomial.hermite_e.hermeline Examples >>> import numpy.polynomial.chebyshev as C >>> C.chebline(3,2) array([3, 2]) >>> C.chebval(-3, C.chebline(3,2)) # should be -3 -3.0
numpy.reference.generated.numpy.polynomial.chebyshev.chebline
numpy.polynomial.chebyshev.chebmul polynomial.chebyshev.chebmul(c1, c2)[source] Multiply one Chebyshev series by another. Returns the product of two Chebyshev series c1 * c2. The arguments are sequences of coefficients, from lowest order “term” to highest, e.g., [1,2,3] represents the series T_0 + 2*T_1 + 3*T_2. Parameters c1, c2array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns outndarray Of Chebyshev series coefficients representing their product. See also chebadd, chebsub, chebmulx, chebdiv, chebpow Notes In general, the (polynomial) product of two C-series results in terms that are not in the Chebyshev polynomial basis set. Thus, to express the product as a C-series, it is typically necessary to “reproject” the product onto said basis set, which typically produces “unintuitive live” (but correct) results; see Examples section below. Examples >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebmul(c1,c2) # multiplication requires "reprojection" array([ 6.5, 12. , 12. , 4. , 1.5])
numpy.reference.generated.numpy.polynomial.chebyshev.chebmul
numpy.polynomial.chebyshev.chebmulx polynomial.chebyshev.chebmulx(c)[source] Multiply a Chebyshev series by x. Multiply the polynomial c by x, where x is the independent variable. Parameters carray_like 1-D array of Chebyshev series coefficients ordered from low to high. Returns outndarray Array representing the result of the multiplication. Notes New in version 1.5.0. Examples >>> from numpy.polynomial import chebyshev as C >>> C.chebmulx([1,2,3]) array([1. , 2.5, 1. , 1.5])
numpy.reference.generated.numpy.polynomial.chebyshev.chebmulx
numpy.polynomial.chebyshev.chebone polynomial.chebyshev.chebone = array([1]) An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array. Parameters (for the __new__ method; see Notes below) shapetuple of ints Shape of created array. dtypedata-type, optional Any object that can be interpreted as a numpy data type. bufferobject exposing buffer interface, optional Used to fill the array with data. offsetint, optional Offset of array data in buffer. stridestuple of ints, optional Strides of data in memory. order{‘C’, ‘F’}, optional Row-major (C-style) or column-major (Fortran-style) order. See also array Construct an array. zeros Create an array, each element of which is zero. empty Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”). dtype Create a data-type. numpy.typing.NDArray An ndarray alias generic w.r.t. its dtype.type. Notes There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted. No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F') array([[0.0e+000, 0.0e+000], # random [ nan, 2.5e-323]]) Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3]) Attributes Tndarray Transpose of the array. databuffer The array’s elements, in memory. dtypedtype object Describes the format of the elements in the array. flagsdict Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc. flatnumpy.flatiter object Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO). imagndarray Imaginary part of the array. realndarray Real part of the array. sizeint Number of elements in the array. itemsizeint The memory use of each array element in bytes. nbytesint The total number of bytes required to store the array data, i.e., itemsize * size. ndimint The array’s number of dimensions. shapetuple of ints Shape of the array. stridestuple of ints The step-size required to move from one element to the next in memory. For example, a contiguous (3, 4) array of type int16 in C-order has strides (8, 2). This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (2 * 4). ctypesctypes object Class containing properties of the array needed for interaction with ctypes. basendarray If the array is a view into another array, that array is its base (unless that array is also a view). The base array is where the array data is actually stored.
numpy.reference.generated.numpy.polynomial.chebyshev.chebone
numpy.polynomial.chebyshev.chebpow polynomial.chebyshev.chebpow(c, pow, maxpower=16)[source] Raise a Chebyshev series to a power. Returns the Chebyshev 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 T_0 + 2*T_1 + 3*T_2. Parameters carray_like 1-D array of Chebyshev series coefficients ordered from low to high. powinteger Power to which the series will be raised maxpowerinteger, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns coefndarray Chebyshev series of power. See also chebadd, chebsub, chebmulx, chebmul, chebdiv Examples >>> from numpy.polynomial import chebyshev as C >>> C.chebpow([1, 2, 3, 4], 2) array([15.5, 22. , 16. , ..., 12.5, 12. , 8. ])
numpy.reference.generated.numpy.polynomial.chebyshev.chebpow
numpy.polynomial.chebyshev.chebpts1 polynomial.chebyshev.chebpts1(npts)[source] Chebyshev points of the first kind. The Chebyshev points of the first kind are the points cos(x), where x = [pi*(k + .5)/npts for k in range(npts)]. Parameters nptsint Number of sample points desired. Returns ptsndarray The Chebyshev points of the first kind. See also chebpts2 Notes New in version 1.5.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebpts1
numpy.polynomial.chebyshev.chebpts2 polynomial.chebyshev.chebpts2(npts)[source] Chebyshev points of the second kind. The Chebyshev points of the second kind are the points cos(x), where x = [pi*k/(npts - 1) for k in range(npts)]. Parameters nptsint Number of sample points desired. Returns ptsndarray The Chebyshev points of the second kind. Notes New in version 1.5.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebpts2
numpy.polynomial.chebyshev.chebroots polynomial.chebyshev.chebroots(c)[source] Compute the roots of a Chebyshev series. Return the roots (a.k.a. “zeros”) of the polynomial \[p(x) = \sum_i c[i] * T_i(x).\] Parameters c1-D array_like 1-D array of coefficients. Returns outndarray Array of the roots of the series. If all the roots are real, then out is also real, otherwise it is complex. See also numpy.polynomial.polynomial.polyroots numpy.polynomial.legendre.legroots numpy.polynomial.laguerre.lagroots numpy.polynomial.hermite.hermroots numpy.polynomial.hermite_e.hermeroots Notes The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the 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 Chebyshev series basis polynomials aren’t powers of x so the results of this function may seem unintuitive. Examples >>> import numpy.polynomial.chebyshev as cheb >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) # may vary
numpy.reference.generated.numpy.polynomial.chebyshev.chebroots
numpy.polynomial.chebyshev.chebsub polynomial.chebyshev.chebsub(c1, c2)[source] Subtract one Chebyshev series from another. Returns the difference of two Chebyshev series c1 - c2. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series T_0 + 2*T_1 + 3*T_2. Parameters c1, c2array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns outndarray Of Chebyshev series coefficients representing their difference. See also chebadd, chebmulx, chebmul, chebdiv, chebpow Notes Unlike multiplication, division, etc., the difference of two Chebyshev series is a Chebyshev series (without having to “reproject” the result onto the basis set) so subtraction, just like that of “standard” polynomials, is simply “component-wise.” Examples >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebsub(c1,c2) array([-2., 0., 2.]) >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2) array([ 2., 0., -2.])
numpy.reference.generated.numpy.polynomial.chebyshev.chebsub
numpy.polynomial.chebyshev.chebtrim polynomial.chebyshev.chebtrim(c, tol=0)[source] Remove “small” “trailing” coefficients from a polynomial. “Small” means “small in absolute value” and is controlled by the parameter tol; “trailing” means highest order coefficient(s), e.g., in [0, 1, 1, 0, 0] (which represents 0 + x + x**2 + 0*x**3 + 0*x**4) both the 3-rd and 4-th order coefficients would be “trimmed.” Parameters carray_like 1-d array of coefficients, ordered from lowest order to highest. tolnumber, optional Trailing (i.e., highest order) elements with absolute value less than or equal to tol (default value is zero) are removed. Returns trimmedndarray 1-d array with trailing zeros removed. If the resulting series would be empty, a series containing a single zero is returned. Raises ValueError If tol < 0 See also trimseq Examples >>> from numpy.polynomial import polyutils as pu >>> pu.trimcoef((0,0,3,0,5,0,0)) array([0., 0., 3., 0., 5.]) >>> pu.trimcoef((0,0,1e-3,0,1e-5,0,0),1e-3) # item == tol is trimmed array([0.]) >>> i = complex(0,1) # works for complex >>> pu.trimcoef((3e-4,1e-3*(1-i),5e-4,2e-5*(1+i)), 1e-3) array([0.0003+0.j , 0.001 -0.001j])
numpy.reference.generated.numpy.polynomial.chebyshev.chebtrim
numpy.polynomial.chebyshev.chebval polynomial.chebyshev.chebval(x, c, tensor=True)[source] Evaluate a Chebyshev series at points x. If c is of length n + 1, this function returns the value: \[p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)\] The parameter x is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either x or its elements must support multiplication and addition both with themselves and with the elements of c. If c is a 1-D array, then p(x) will have the same shape as x. If c is multidimensional, then the shape of the result depends on the value of tensor. If tensor is true the shape will be c.shape[1:] + x.shape. If tensor is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters xarray_like, compatible object If x is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, x or its elements must support addition and multiplication with with themselves and with the elements of c. carray_like Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If c is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of c. tensorboolean, optional If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of x. Scalars have dimension 0 for this action. The result is that every column of coefficients in c is evaluated for every element of x. If False, x is broadcast over the columns of c for the evaluation. This keyword is useful when c is multidimensional. The default value is True. New in version 1.7.0. Returns valuesndarray, algebra_like The shape of the return value is described above. See also chebval2d, chebgrid2d, chebval3d, chebgrid3d Notes The evaluation uses Clenshaw recursion, aka synthetic division.
numpy.reference.generated.numpy.polynomial.chebyshev.chebval
numpy.polynomial.chebyshev.chebval2d polynomial.chebyshev.chebval2d(x, y, c)[source] Evaluate a 2-D Chebyshev series at points (x, y). This function returns the values: \[p(x,y) = \sum_{i,j} c_{i,j} * T_i(x) * T_j(y)\] 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. Parameters x, yarray_like, compatible objects The two dimensional series is evaluated at the points (x, y), where x and y must have the same shape. If x or y is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn’t an ndarray it is treated as a scalar. carray_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in c[i,j]. If c has dimension greater than 2 the remaining indices enumerate multiple sets of coefficients. Returns valuesndarray, compatible object The values of the two dimensional Chebyshev series at points formed from pairs of corresponding values from x and y. See also chebval, chebgrid2d, chebval3d, chebgrid3d Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebval2d
numpy.polynomial.chebyshev.chebval3d polynomial.chebyshev.chebval3d(x, y, z, c)[source] Evaluate a 3-D Chebyshev series at points (x, y, z). This function returns the values: \[p(x,y,z) = \sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z)\] The parameters x, y, and z are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either x, y, and z or their elements must support multiplication and addition both with themselves and with the elements of c. If c has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape. Parameters x, y, zarray_like, compatible object The three dimensional series is evaluated at the points (x, y, z), where x, y, and z must have the same shape. If any of x, y, or z is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn’t an ndarray it is treated as a scalar. carray_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in c[i,j,k]. If c has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients. Returns valuesndarray, compatible object The values of the multidimensional polynomial on points formed with triples of corresponding values from x, y, and z. See also chebval, chebval2d, chebgrid2d, chebgrid3d Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebval3d
numpy.polynomial.chebyshev.chebvander polynomial.chebyshev.chebvander(x, deg)[source] 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 \[V[..., i] = T_i(x),\] where 0 <= i <= deg. The leading indices of V index the elements of x and the last index is the degree of the Chebyshev polynomial. If c is a 1-D array of coefficients of length n + 1 and V is the matrix V = chebvander(x, n), then np.dot(V, c) and chebval(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 Chebyshev series of the same degree and sample points. Parameters xarray_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If x is scalar it is converted to a 1-D array. degint Degree of the resulting matrix. Returns vanderndarray The pseudo Vandermonde matrix. The shape of the returned matrix is x.shape + (deg + 1,), where The last index is the degree of the corresponding Chebyshev polynomial. The dtype will be the same as the converted x.
numpy.reference.generated.numpy.polynomial.chebyshev.chebvander
numpy.polynomial.chebyshev.chebvander2d polynomial.chebyshev.chebvander2d(x, y, deg)[source] Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees deg and sample points (x, y). The pseudo-Vandermonde matrix is defined by \[V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y),\] 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 Chebyshev polynomials. If V = chebvander2d(x, y, [xdeg, ydeg]), then the columns of V correspond to the elements of a 2-D coefficient array c of shape (xdeg + 1, ydeg + 1) in the order \[c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\] and np.dot(V, c.flat) and chebval2d(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 Chebyshev series of the same degrees and sample points. Parameters x, yarray_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deglist of ints List of maximum degrees of the form [x_deg, y_deg]. Returns vander2dndarray The shape of the returned matrix is x.shape + (order,), where \(order = (deg[0]+1)*(deg[1]+1)\). The dtype will be the same as the converted x and y. See also chebvander, chebvander3d, chebval2d, chebval3d Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebvander2d
numpy.polynomial.chebyshev.chebvander3d polynomial.chebyshev.chebvander3d(x, y, z, deg)[source] Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees deg and sample points (x, y, z). If l, m, n are the given degrees in x, y, z, then The pseudo-Vandermonde matrix is defined by \[V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z),\] 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 Chebyshev polynomials. If V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg]), then the columns of V correspond to the elements of a 3-D coefficient array c of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order \[c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\] and np.dot(V, c.flat) and chebval3d(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 Chebyshev series of the same degrees and sample points. Parameters x, y, zarray_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deglist of ints List of maximum degrees of the form [x_deg, y_deg, z_deg]. Returns vander3dndarray The shape of the returned matrix is x.shape + (order,), where \(order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)\). The dtype will be the same as the converted x, y, and z. See also chebvander, chebvander3d, chebval2d, chebval3d Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebvander3d
numpy.polynomial.chebyshev.chebweight polynomial.chebyshev.chebweight(x)[source] The weight function of the Chebyshev polynomials. The weight function is \(1/\sqrt{1 - x^2}\) and the interval of integration is \([-1, 1]\). The Chebyshev polynomials are orthogonal, but not normalized, with respect to this weight function. Parameters xarray_like Values at which the weight function will be computed. Returns wndarray The weight function at x. Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.chebyshev.chebweight
numpy.polynomial.chebyshev.chebx polynomial.chebyshev.chebx = array([0, 1]) An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array. Parameters (for the __new__ method; see Notes below) shapetuple of ints Shape of created array. dtypedata-type, optional Any object that can be interpreted as a numpy data type. bufferobject exposing buffer interface, optional Used to fill the array with data. offsetint, optional Offset of array data in buffer. stridestuple of ints, optional Strides of data in memory. order{‘C’, ‘F’}, optional Row-major (C-style) or column-major (Fortran-style) order. See also array Construct an array. zeros Create an array, each element of which is zero. empty Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”). dtype Create a data-type. numpy.typing.NDArray An ndarray alias generic w.r.t. its dtype.type. Notes There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted. No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F') array([[0.0e+000, 0.0e+000], # random [ nan, 2.5e-323]]) Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3]) Attributes Tndarray Transpose of the array. databuffer The array’s elements, in memory. dtypedtype object Describes the format of the elements in the array. flagsdict Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc. flatnumpy.flatiter object Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO). imagndarray Imaginary part of the array. realndarray Real part of the array. sizeint Number of elements in the array. itemsizeint The memory use of each array element in bytes. nbytesint The total number of bytes required to store the array data, i.e., itemsize * size. ndimint The array’s number of dimensions. shapetuple of ints Shape of the array. stridestuple of ints The step-size required to move from one element to the next in memory. For example, a contiguous (3, 4) array of type int16 in C-order has strides (8, 2). This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (2 * 4). ctypesctypes object Class containing properties of the array needed for interaction with ctypes. basendarray If the array is a view into another array, that array is its base (unless that array is also a view). The base array is where the array data is actually stored.
numpy.reference.generated.numpy.polynomial.chebyshev.chebx
numpy.polynomial.chebyshev.Chebyshev.__call__ method polynomial.chebyshev.Chebyshev.__call__(arg)[source] Call self as a function.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.__call__
numpy.polynomial.chebyshev.Chebyshev.basis method classmethod polynomial.chebyshev.Chebyshev.basis(deg, domain=None, window=None)[source] Series basis polynomial of degree deg. Returns the series representing the basis polynomial of degree deg. New in version 1.7.0. Parameters degint Degree of the basis polynomial for the series. Must be >= 0. domain{None, array_like}, optional If given, the array must be of the form [beg, end], where beg and end are the endpoints of the domain. If None is given then the class domain is used. The default is None. window{None, array_like}, optional If given, the resulting array must be if the form [beg, end], where beg and end are the endpoints of the window. If None is given then the class window is used. The default is None. Returns new_seriesseries A series with the coefficient of the deg term set to one and all others zero.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.basis
numpy.polynomial.chebyshev.Chebyshev.cast method classmethod polynomial.chebyshev.Chebyshev.cast(series, domain=None, window=None)[source] Convert series to series of this class. The series is expected to be an instance of some polynomial series of one of the types supported by by the numpy.polynomial module, but could be some other class that supports the convert method. New in version 1.7.0. Parameters seriesseries The series instance to be converted. domain{None, array_like}, optional If given, the array must be of the form [beg, end], where beg and end are the endpoints of the domain. If None is given then the class domain is used. The default is None. window{None, array_like}, optional If given, the resulting array must be if the form [beg, end], where beg and end are the endpoints of the window. If None is given then the class window is used. The default is None. Returns new_seriesseries A series of the same kind as the calling class and equal to series when evaluated. See also convert similar instance method
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.cast
numpy.polynomial.chebyshev.Chebyshev.convert method polynomial.chebyshev.Chebyshev.convert(domain=None, kind=None, window=None)[source] Convert series to a different kind and/or domain and/or window. Parameters domainarray_like, optional The domain of the converted series. If the value is None, the default domain of kind is used. kindclass, optional The polynomial series type class to which the current instance should be converted. If kind is None, then the class of the current instance is used. windowarray_like, optional The window of the converted series. If the value is None, the default window of kind is used. Returns new_seriesseries The returned class can be of different type than the current instance and/or have a different domain and/or different window. Notes Conversion between domains and class types can result in numerically ill defined series.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.convert
numpy.polynomial.chebyshev.Chebyshev.copy method polynomial.chebyshev.Chebyshev.copy()[source] Return a copy. Returns new_seriesseries Copy of self.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.copy
numpy.polynomial.chebyshev.Chebyshev.cutdeg method polynomial.chebyshev.Chebyshev.cutdeg(deg)[source] Truncate series to the given degree. Reduce the degree of the series to deg by discarding the high order terms. If deg is greater than the current degree a copy of the current series is returned. This can be useful in least squares where the coefficients of the high degree terms may be very small. New in version 1.5.0. Parameters degnon-negative int The series is reduced to degree deg by discarding the high order terms. The value of deg must be a non-negative integer. Returns new_seriesseries New instance of series with reduced degree.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.cutdeg
numpy.polynomial.chebyshev.Chebyshev.degree method polynomial.chebyshev.Chebyshev.degree()[source] The degree of the series. New in version 1.5.0. Returns degreeint Degree of the series, one less than the number of coefficients.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.degree
numpy.polynomial.chebyshev.Chebyshev.deriv method polynomial.chebyshev.Chebyshev.deriv(m=1)[source] Differentiate. Return a series instance of that is the derivative of the current series. Parameters mnon-negative int Find the derivative of order m. Returns new_seriesseries A new series representing the derivative. The domain is the same as the domain of the differentiated series.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.deriv
numpy.polynomial.chebyshev.Chebyshev.domain attribute polynomial.chebyshev.Chebyshev.domain = array([-1, 1])
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.domain
numpy.polynomial.chebyshev.Chebyshev.fit method classmethod polynomial.chebyshev.Chebyshev.fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=None)[source] Least squares fit to data. Return a series instance that is the least squares fit to the data y sampled at x. The domain of the returned instance can be specified and this will often result in a superior fit with less chance of ill conditioning. Parameters xarray_like, shape (M,) x-coordinates of the M sample points (x[i], y[i]). yarray_like, shape (M,) y-coordinates of the M sample points (x[i], y[i]). degint or 1-D array_like Degree(s) of the fitting polynomials. If deg is a single integer all terms up to and including the deg’th term are included in the fit. For NumPy versions >= 1.11.0 a list of integers specifying the degrees of the terms to include may be used instead. domain{None, [beg, end], []}, optional Domain to use for the returned series. If None, then a minimal domain that covers the points x is chosen. If [] the class domain is used. The default value was the class domain in NumPy 1.4 and None in later versions. The [] option was added in numpy 1.5.0. rcondfloat, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases. fullbool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. warray_like, shape (M,), optional Weights. If not None, the weight w[i] applies to the unsquared residual y[i] - y_hat[i] at x[i]. Ideally the weights are chosen so that the errors of the products w[i]*y[i] all have the same variance. When using inverse-variance weighting, use w[i] = 1/sigma(y[i]). The default value is None. New in version 1.5.0. window{[beg, end]}, optional Window to use for the returned series. The default value is the default class domain New in version 1.6.0. Returns new_seriesseries A series that represents the least squares fit to the data and has the domain and window specified in the call. If the coefficients for the unscaled and unshifted basis polynomials are of interest, do new_series.convert().coef. [resid, rank, sv, rcond]list These values are only returned if full == True resid – sum of squared residuals of the least squares fit rank – the numerical rank of the scaled Vandermonde matrix sv – singular values of the scaled Vandermonde matrix rcond – value of rcond. For more details, see linalg.lstsq.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.fit
numpy.polynomial.chebyshev.Chebyshev.fromroots method classmethod polynomial.chebyshev.Chebyshev.fromroots(roots, domain=[], window=None)[source] Return series instance that has the specified roots. Returns a series representing the product (x - r[0])*(x - r[1])*...*(x - r[n-1]), where r is a list of roots. Parameters rootsarray_like List of roots. domain{[], None, array_like}, optional Domain for the resulting series. If None the domain is the interval from the smallest root to the largest. If [] the domain is the class domain. The default is []. window{None, array_like}, optional Window for the returned series. If None the class window is used. The default is None. Returns new_seriesseries Series with the specified roots.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.fromroots
numpy.polynomial.chebyshev.Chebyshev.has_samecoef method polynomial.chebyshev.Chebyshev.has_samecoef(other)[source] Check if coefficients match. New in version 1.6.0. Parameters otherclass instance The other class must have the coef attribute. Returns boolboolean True if the coefficients are the same, False otherwise.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.has_samecoef
numpy.polynomial.chebyshev.Chebyshev.has_samedomain method polynomial.chebyshev.Chebyshev.has_samedomain(other)[source] Check if domains match. New in version 1.6.0. Parameters otherclass instance The other class must have the domain attribute. Returns boolboolean True if the domains are the same, False otherwise.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.has_samedomain
numpy.polynomial.chebyshev.Chebyshev.has_sametype method polynomial.chebyshev.Chebyshev.has_sametype(other)[source] Check if types match. New in version 1.7.0. Parameters otherobject Class instance. Returns boolboolean True if other is same class as self
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.has_sametype
numpy.polynomial.chebyshev.Chebyshev.has_samewindow method polynomial.chebyshev.Chebyshev.has_samewindow(other)[source] Check if windows match. New in version 1.6.0. Parameters otherclass instance The other class must have the window attribute. Returns boolboolean True if the windows are the same, False otherwise.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.has_samewindow
numpy.polynomial.chebyshev.Chebyshev.identity method classmethod polynomial.chebyshev.Chebyshev.identity(domain=None, window=None)[source] Identity function. If p is the returned series, then p(x) == x for all values of x. Parameters domain{None, array_like}, optional If given, the array must be of the form [beg, end], where beg and end are the endpoints of the domain. If None is given then the class domain is used. The default is None. window{None, array_like}, optional If given, the resulting array must be if the form [beg, end], where beg and end are the endpoints of the window. If None is given then the class window is used. The default is None. Returns new_seriesseries Series of representing the identity.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.identity
numpy.polynomial.chebyshev.Chebyshev.integ method polynomial.chebyshev.Chebyshev.integ(m=1, k=[], lbnd=None)[source] Integrate. Return a series instance that is the definite integral of the current series. Parameters mnon-negative int The number of integrations to perform. karray_like Integration constants. The first constant is applied to the first integration, the second to the second, and so on. The list of values must less than or equal to m in length and any missing values are set to zero. lbndScalar The lower bound of the definite integral. Returns new_seriesseries A new series representing the integral. The domain is the same as the domain of the integrated series.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.integ
numpy.polynomial.chebyshev.Chebyshev.interpolate method classmethod polynomial.chebyshev.Chebyshev.interpolate(func, deg, domain=None, args=())[source] Interpolate a function at the Chebyshev points of the first kind. Returns the series that interpolates func at the Chebyshev points of the first kind scaled and shifted to the domain. The resulting series tends to a minmax approximation of func when the function is continuous in the domain. New in version 1.14.0. Parameters funcfunction The function to be interpolated. It must be a function of a single variable of the form f(x, a, b, c...), where a, b, c... are extra arguments passed in the args parameter. degint Degree of the interpolating polynomial. domain{None, [beg, end]}, optional Domain over which func is interpolated. The default is None, in which case the domain is [-1, 1]. argstuple, optional Extra arguments to be used in the function call. Default is no extra arguments. Returns polynomialChebyshev instance Interpolating Chebyshev instance. Notes See numpy.polynomial.chebfromfunction for more details.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.interpolate
numpy.polynomial.chebyshev.Chebyshev.linspace method polynomial.chebyshev.Chebyshev.linspace(n=100, domain=None)[source] Return x, y values at equally spaced points in domain. Returns the x, y values at n linearly spaced points across the domain. Here y is the value of the polynomial at the points x. By default the domain is the same as that of the series instance. This method is intended mostly as a plotting aid. New in version 1.5.0. Parameters nint, optional Number of point pairs to return. The default value is 100. domain{None, array_like}, optional If not None, the specified domain is used instead of that of the calling instance. It should be of the form [beg,end]. The default is None which case the class domain is used. Returns x, yndarray x is equal to linspace(self.domain[0], self.domain[1], n) and y is the series evaluated at element of x.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.linspace
numpy.polynomial.chebyshev.Chebyshev.mapparms method polynomial.chebyshev.Chebyshev.mapparms()[source] Return the mapping parameters. The returned values define a linear map off + scl*x that is applied to the input arguments before the series is evaluated. The map depends on the domain and window; if the current domain is equal to the window the resulting map is the identity. If the coefficients of the series instance are to be used by themselves outside this class, then the linear function must be substituted for the x in the standard representation of the base polynomials. Returns off, sclfloat or complex The mapping function is defined by off + scl*x. Notes If the current domain is the interval [l1, r1] and the window is [l2, r2], then the linear mapping function L is defined by the equations: L(l1) = l2 L(r1) = r2
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.mapparms
numpy.polynomial.chebyshev.Chebyshev.roots method polynomial.chebyshev.Chebyshev.roots()[source] Return the roots of the series polynomial. Compute the roots for the series. Note that the accuracy of the roots decrease the further outside the domain they lie. Returns rootsndarray Array containing the roots of the series.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.roots
numpy.polynomial.chebyshev.Chebyshev.trim method polynomial.chebyshev.Chebyshev.trim(tol=0)[source] Remove trailing coefficients Remove trailing coefficients until a coefficient is reached whose absolute value greater than tol or the beginning of the series is reached. If all the coefficients would be removed the series is set to [0]. A new series instance is returned with the new coefficients. The current instance remains unchanged. Parameters tolnon-negative number. All trailing coefficients less than tol will be removed. Returns new_seriesseries New instance of series with trimmed coefficients.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.trim
numpy.polynomial.chebyshev.Chebyshev.truncate method polynomial.chebyshev.Chebyshev.truncate(size)[source] Truncate series to length size. Reduce the series to length size by discarding the high degree terms. The value of size must be a positive integer. This can be useful in least squares where the coefficients of the high degree terms may be very small. Parameters sizepositive int The series is reduced to length size by discarding the high degree terms. The value of size must be a positive integer. Returns new_seriesseries New instance of series with truncated coefficients.
numpy.reference.generated.numpy.polynomial.chebyshev.chebyshev.truncate
numpy.polynomial.chebyshev.chebzero polynomial.chebyshev.chebzero = array([0]) An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array. Parameters (for the __new__ method; see Notes below) shapetuple of ints Shape of created array. dtypedata-type, optional Any object that can be interpreted as a numpy data type. bufferobject exposing buffer interface, optional Used to fill the array with data. offsetint, optional Offset of array data in buffer. stridestuple of ints, optional Strides of data in memory. order{‘C’, ‘F’}, optional Row-major (C-style) or column-major (Fortran-style) order. See also array Construct an array. zeros Create an array, each element of which is zero. empty Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”). dtype Create a data-type. numpy.typing.NDArray An ndarray alias generic w.r.t. its dtype.type. Notes There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted. No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F') array([[0.0e+000, 0.0e+000], # random [ nan, 2.5e-323]]) Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3]) Attributes Tndarray Transpose of the array. databuffer The array’s elements, in memory. dtypedtype object Describes the format of the elements in the array. flagsdict Dictionary containing information related to memory use, e.g., ‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc. flatnumpy.flatiter object Flattened version of the array as an iterator. The iterator allows assignments, e.g., x.flat = 3 (See ndarray.flat for assignment examples; TODO). imagndarray Imaginary part of the array. realndarray Real part of the array. sizeint Number of elements in the array. itemsizeint The memory use of each array element in bytes. nbytesint The total number of bytes required to store the array data, i.e., itemsize * size. ndimint The array’s number of dimensions. shapetuple of ints Shape of the array. stridestuple of ints The step-size required to move from one element to the next in memory. For example, a contiguous (3, 4) array of type int16 in C-order has strides (8, 2). This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (2 * 4). ctypesctypes object Class containing properties of the array needed for interaction with ctypes. basendarray If the array is a view into another array, that array is its base (unless that array is also a view). The base array is where the array data is actually stored.
numpy.reference.generated.numpy.polynomial.chebyshev.chebzero
numpy.polynomial.chebyshev.poly2cheb polynomial.chebyshev.poly2cheb(pol)[source] Convert a polynomial to a Chebyshev 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 Chebyshev series, ordered from lowest to highest degree. Parameters polarray_like 1-D array containing the polynomial coefficients Returns cndarray 1-D array containing the coefficients of the equivalent Chebyshev series. See also cheb2poly Notes The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples >>> from numpy import polynomial as P >>> p = P.Polynomial(range(4)) >>> p Polynomial([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1]) >>> c = p.convert(kind=P.Chebyshev) >>> c Chebyshev([1. , 3.25, 1. , 0.75], domain=[-1., 1.], window=[-1., 1.]) >>> P.chebyshev.poly2cheb(range(4)) array([1. , 3.25, 1. , 0.75])
numpy.reference.generated.numpy.polynomial.chebyshev.poly2cheb
numpy.polynomial.hermite.herm2poly polynomial.hermite.herm2poly(c)[source] Convert a Hermite series to a polynomial. Convert an array representing the coefficients of a Hermite series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the “standard” basis) ordered from lowest to highest degree. Parameters carray_like 1-D array containing the Hermite series coefficients, ordered from lowest order term to highest. Returns polndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the “standard” basis) ordered from lowest order term to highest. See also poly2herm Notes The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples >>> from numpy.polynomial.hermite import herm2poly >>> herm2poly([ 1. , 2.75 , 0.5 , 0.375]) array([0., 1., 2., 3.])
numpy.reference.generated.numpy.polynomial.hermite.herm2poly
numpy.polynomial.hermite.hermadd polynomial.hermite.hermadd(c1, c2)[source] Add one Hermite series to another. Returns the sum of two Hermite series c1 + c2. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series P_0 + 2*P_1 + 3*P_2. Parameters c1, c2array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns outndarray Array representing the Hermite series of their sum. See also hermsub, hermmulx, hermmul, hermdiv, hermpow Notes Unlike multiplication, division, etc., the sum of two Hermite series is a Hermite series (without having to “reproject” the result onto the basis set) so addition, just like that of “standard” polynomials, is simply “component-wise.” Examples >>> from numpy.polynomial.hermite import hermadd >>> hermadd([1, 2, 3], [1, 2, 3, 4]) array([2., 4., 6., 4.])
numpy.reference.generated.numpy.polynomial.hermite.hermadd
numpy.polynomial.hermite.hermcompanion polynomial.hermite.hermcompanion(c)[source] Return the scaled companion matrix of c. The basis polynomials are scaled so that the companion matrix is symmetric when c is an Hermite basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if numpy.linalg.eigvalsh is used to obtain them. Parameters carray_like 1-D array of Hermite series coefficients ordered from low to high degree. Returns matndarray Scaled companion matrix of dimensions (deg, deg). Notes New in version 1.7.0.
numpy.reference.generated.numpy.polynomial.hermite.hermcompanion
numpy.polynomial.hermite.hermder polynomial.hermite.hermder(c, m=1, scl=1, axis=0)[source] Differentiate a Hermite series. Returns the Hermite series 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 series 1*H_0 + 2*H_1 + 3*H_2 while [[1,2],[1,2]] represents 1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y) if axis=0 is x and axis=1 is y. Parameters carray_like Array of Hermite series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. mint, optional Number of derivatives taken, must be non-negative. (Default: 1) sclscalar, optional Each differentiation is multiplied by scl. The end result is multiplication by scl**m. This is for use in a linear change of variable. (Default: 1) axisint, optional Axis over which the derivative is taken. (Default: 0). New in version 1.7.0. Returns derndarray Hermite series of the derivative. See also hermint Notes In general, the result of differentiating a Hermite series does not resemble the same operation on a power series. Thus the result of this function may be “unintuitive,” albeit correct; see Examples section below. Examples >>> from numpy.polynomial.hermite import hermder >>> hermder([ 1. , 0.5, 0.5, 0.5]) array([1., 2., 3.]) >>> hermder([-0.5, 1./2., 1./8., 1./12., 1./16.], m=2) array([1., 2., 3.])
numpy.reference.generated.numpy.polynomial.hermite.hermder
numpy.polynomial.hermite.hermdiv polynomial.hermite.hermdiv(c1, c2)[source] Divide one Hermite series by another. Returns the quotient-with-remainder of two Hermite 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. Parameters c1, c2array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns [quo, rem]ndarrays Of Hermite series coefficients representing the quotient and remainder. See also hermadd, hermsub, hermmulx, hermmul, hermpow Notes In general, the (polynomial) division of one Hermite series by another results in quotient and remainder terms that are not in the Hermite polynomial basis set. Thus, to express these results as a Hermite series, it is necessary to “reproject” the results onto the Hermite basis set, which may produce “unintuitive” (but correct) results; see Examples section below. Examples >>> from numpy.polynomial.hermite import hermdiv >>> hermdiv([ 52., 29., 52., 7., 6.], [0, 1, 2]) (array([1., 2., 3.]), array([0.])) >>> hermdiv([ 54., 31., 52., 7., 6.], [0, 1, 2]) (array([1., 2., 3.]), array([2., 2.])) >>> hermdiv([ 53., 30., 52., 7., 6.], [0, 1, 2]) (array([1., 2., 3.]), array([1., 1.]))
numpy.reference.generated.numpy.polynomial.hermite.hermdiv