Python#
Everything is importable from numerical; the FFT lives in numerical.fft, and numpy.linalg’s names in
numerical.linalg too.
Tensors#
- class numerical.Tensor#
- property T#
a matrix’s transpose, as NumPy’s
.T, a view (its elements copied in their new order only when an operation needs them so).- Type:
The tensor with its axes reversed
- all(axis=None, dtype=None, out=None, keepdims=False)#
Whether every element is true (nonzero), or every one along axis (a bool Tensor without it), as
numpy.all. axis may name several axes (a tuple, () for none), and keepdims keeps each reduced axis with extent 1, as NumPy’s.
- any(axis=None, dtype=None, out=None, keepdims=False)#
Whether any element is true (nonzero), or any along axis (a bool Tensor without it), as
numpy.any. axis may name several axes (a tuple, () for none), and keepdims keeps each reduced axis with extent 1, as NumPy’s.
- astype(dtype, *, copy=True, device=None)#
x in dtype (float64, complex128, float32, complex64 or bool), as
numpy.astype: a bool is 0 or 1, a number is true where it is nonzero (either part of a complex one); a complex x has no real dtype (its imaginary part would be lost). In dtype already: with copy (the default) ascopy()gives it (the Tensor itself where it holds its elements row-major, a view’s elements copied out), without it the Tensor itself. device None or"cpu".
- conj()#
The complex conjugate of every element, as
numpy.conj; a real, int64 or bool tensor’s own elements.
- conjugate()#
The complex conjugate of every element, as
numpy.conj; a real, int64 or bool tensor’s own elements.
- copy()#
A copy, as
ndarray.copy: the tensor itself where it holds its elements row-major (it is never written into), else, for a view, its elements copied out, without the array the view reads.
- diagonal(offset=0, axis1=0, axis2=1)#
The offset diagonal of the matrices the axes axis1 and axis2 hold, as
ndarray.diagonal: along the other axes’ end.
- dot(b)#
ndarray.dot: the matrix product for vectors and matrices, else the sum over the last axis of self and the second to last of b (its only one for a vector).
- dtype#
‘float64’, ‘complex128’, ‘float32’, ‘complex64’ or ‘bool’.
- property imag#
The imaginary part of every element, of the parts’ precision, as
numpy.imag; zeros of a real or bool tensor’s dtype.
- item(*args)#
The one element of a one-element tensor, or the element at a flat index or a multi-index, as a Python number, as
ndarray.item.
- property mT#
A matrix, or every matrix of a stack, transposed (its last two axes swapped), as
numpy.linalg.matrix_transpose.
- max(axis=None, dtype=None, out=None, keepdims=False, initial=<object object>)#
The largest element, or the largest along axis, as
numpy.max.A NaN wins. Real dtypes only (a complex one has no order).
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
- Returns:
A number for every element, else a Tensor of a’s dtype.
- Return type:
float | bool | Tensor
- Raises:
ValueError – for an axis out of range or repeated, or a reduction over no element.
TypeError – for a complex a.
Examples
>>> import numerical >>> numerical.max([[1.0, 2.0], [3.0, 4.0]]) 4.0 >>> numerical.max([[1.0, 2.0], [3.0, 4.0]], axis=0) numerical.Tensor([3.0, 4.0], dtype=float64) >>> numerical.max([1.0, float("nan")]) nan
- mean(axis=None, dtype=None, out=None, keepdims=False)#
The mean of every element, or the means along axis, as
numpy.mean.- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
dtype – The dtype the elements are converted to and averaged in (keyword-only), as NumPy’s and the array API’s.
- Returns:
A number for every element, else a Tensor of a’s dtype (float64 for a bool one).
- Return type:
float | complex | Tensor
- Raises:
ValueError – for an axis out of range or repeated.
Examples
>>> import numerical >>> numerical.mean([[1.0, 2.0], [3.0, 4.0]]) 2.5 >>> numerical.mean([[1.0, 2.0], [3.0, 4.0]], axis=1) numerical.Tensor([1.5, 3.5], dtype=float64)
- min(axis=None, dtype=None, out=None, keepdims=False, initial=<object object>)#
The smallest element, or the smallest along axis, as
numpy.min.A NaN wins. Real dtypes only.
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
- Returns:
A number for every element, else a Tensor of a’s dtype.
- Return type:
float | bool | Tensor
- Raises:
ValueError – for an axis out of range or repeated, or a reduction over no element.
TypeError – for a complex a.
Examples
>>> import numerical >>> numerical.min([[1.0, 2.0], [3.0, 4.0]]) 1.0 >>> numerical.min([[1.0, 2.0], [3.0, 4.0]], axis=1) numerical.Tensor([1.0, 3.0], dtype=float64)
- ndim#
The number of axes.
- prod(axis=None, dtype=None, out=None, keepdims=False, initial=<object object>)#
The product of every element (a number), or the products along axis, as
numpy.prod: in order (NumPy’s multiplications are not paired as its sums are). An empty one’s is 1. dtype the one the elements are multiplied in; initial the first factor of each product, as NumPy’s (None: none).
- property real#
The real part of every element, of the parts’ precision, as
numpy.real; a real or bool tensor itself.
- shape#
The size of each axis, as a tuple.
- size#
The total number of elements.
- squeeze(axis=None)#
a without its axes of extent 1, or without the ones axis names (an integer or a tuple), as
numpy.squeeze.- Raises:
ValueError – if an axis axis names has another extent.
- sum(axis=None, dtype=None, out=None, keepdims=False, initial=<object object>)#
The sum of every element, or the sums along axis, as
numpy.sum.Added by pairwise halving, as NumPy adds.
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
dtype – The dtype the elements are converted to and summed in (keyword-only), as NumPy’s and the array API’s.
initial – The value each sum starts from (keyword-only), in its dtype, as NumPy’s; None for none.
- Returns:
A number for every element, else a Tensor of a’s dtype (float64 for a bool one).
- Return type:
float | complex | Tensor
- Raises:
ValueError – for an axis out of range or repeated.
TypeError – for a complex initial of a real sum.
Examples
>>> import numerical >>> numerical.sum([[1.0, 2.0], [3.0, 4.0]]) 10.0 >>> numerical.sum([[1.0, 2.0], [3.0, 4.0]], axis=0) numerical.Tensor([4.0, 6.0], dtype=float64) >>> numerical.sum([[1.0, 2.0], [3.0, 4.0]], axis=1, keepdims=True) numerical.Tensor([[3.0], [7.0]], dtype=float64)
- swapaxes(axis1, axis2)#
self with its axes axis1 and axis2 exchanged, as
ndarray.swapaxes: a copy.
- take(indices, axis=None, out=None, mode='raise')#
ndarray.take, whose out comes before mode.
- to_device(device, /, *, stream=None)#
The tensor itself on the CPU, the only device a Tensor has (the array API’s
to_device).
- tobytes()#
The elements’ bytes, row-major, in this machine’s byte order, as
ndarray.tobytes.
- tolist() list#
The elements as nested Python lists (a bare scalar when rank-0).
- trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)#
The sum of the offset diagonal of the matrices the axes axis1 and axis2 hold, as
ndarray.trace.
- numerical.asarray(obj, dtype=None, *, device=None, copy=None)#
A
Tensorfrom obj, asnumpy.asarrayand the array API’sasarray.A complex input is never cast to a real dtype (that would discard the imaginary part).
- Parameters:
obj – A Tensor (the same object when dtype matches), an object with an
__array_interface__(NumPy: bool, integer, float32/64 and complex64/128 elements, any strides), a nested list or tuple of numbers, or a number (rank 0).dtype –
"float64","complex128","float32","complex64"or"bool"(true where nonzero), or the NumPy type or dtype of that name, or Python’sfloat,complexorbool; by default an array’s own for float32, complex64, complex128 and bool, else float64 (integers included); complex128 for a complex number or a list with one, bool for a bool or a list of bools alone, as NumPy’s.device –
Noneor"cpu", the one device.copy –
Nonereads obj as it is;Truegives a Tensor holding its own elements (a view’s copied out, ascopy()gives them);Falserefuses any obj but a Tensor of dtype (whose elements a Tensor shares, never writing into them), since the elements are copied into a Tensor.
- Returns:
The elements of obj, a copy unless obj is a Tensor of dtype already.
- Return type:
- Raises:
ValueError – if a nested list is not rectangular.
TypeError – if obj is none of these, or a nested list holds something other than numbers.
TypeError – for a dtype not offered (also a
numerical.errorand aValueError).numerical.error – for a complex input cast to a real dtype.
ValueError – for copy False where the elements must be copied, or a device other than the CPU.
Examples
>>> import numerical >>> numerical.asarray([[1, 2], [3, 4]]) numerical.Tensor([[1.0, 2.0], [3.0, 4.0]], dtype=float64) >>> numerical.asarray([1, 0], dtype="bool") numerical.Tensor([True, False], dtype=bool) >>> numerical.asarray(2.5).shape ()
- numerical.array(object, dtype=None, *, copy=True, ndmin=0)#
A Tensor of object, as
numpy.array:asarray()’s reading, at least ndmin axes (ones added in front); copy False refused where a copy is needed (a Tensor is its own, so it copies nothing else).
- numerical.asanyarray(a, dtype=None)#
asarray(), asnumpy.asanyarray(a Tensor has no subclasses to keep).
- numerical.ascontiguousarray(a, dtype=None)#
a as a Tensor of at least one axis (row-major, as every Tensor), as
numpy.ascontiguousarray.
- numerical.from_dlpack(x, /, *, device=None, copy=None)#
A Tensor of the elements of x, an object of the DLPack protocol (
__dlpack__: a NumPy array, a PyTorch or JAX CPU tensor, any producer of a DLPack capsule), as the array API’sfrom_dlpack: its capsule read (DLPack 1’s versioned one, else the classic one of a producer that takes nomax_version) and its elements copied, of any dtypeasarray()reads, along its strides. A Tensor is itself, or with copy ascopy()gives it; copy False refused, since a Tensor holds its own elements. BufferError for a tensor on another device.
- numerical.fromfunction(function, shape, *, dtype='float64', **kwargs)#
function of the coordinate tensors of shape (
indices(), of dtype), asnumpy.fromfunction.
- numerical.fromiter(iter, dtype, count=-1)#
A vector of the elements of the iterable iter (its first count where not −1), as
numpy.fromiter.
- numerical.zeros(shape, dtype='float64', *, device=None)#
A Tensor of shape full of zeros, as
numpy.zeros.- Parameters:
shape – The extents: an integer (a vector) or a sequence of non-negative integers.
dtype –
"float64"(the default),"complex128","float32","complex64"or"bool"; NumPy’s dtype objects and Python’sfloat,complexandboolname them too.
- Returns:
The zeros.
- Return type:
- Raises:
ValueError – for a negative extent or a dtype not offered.
TypeError – if shape is neither an integer nor a sequence of them.
Examples
>>> import numerical >>> numerical.zeros(3) numerical.Tensor([0.0, 0.0, 0.0], dtype=float64) >>> numerical.zeros((2, 2), "complex128") numerical.Tensor([[0j, 0j], [0j, 0j]], dtype=complex128)
- numerical.empty(shape, dtype='float64', *, device=None)#
A tensor of shape and dtype (float64 for None, as the array API’s default), as
numpy.empty: its elements zeros here (a Tensor is never written into, so none is left unset).
- numerical.ones(shape, dtype='float64', *, device=None)#
A Tensor of shape full of ones, as
numpy.ones.- Parameters:
shape – The extents: an integer (a vector) or a sequence of non-negative integers.
dtype –
"float64"(the default),"complex128","float32","complex64"or"bool"; NumPy’s dtype objects and Python’sfloat,complexandboolname them too.
- Returns:
The ones.
- Return type:
- Raises:
ValueError – for a negative extent or a dtype not offered.
TypeError – if shape is neither an integer nor a sequence of them.
Examples
>>> import numerical >>> numerical.ones((2,), dtype="float32") numerical.Tensor([1.0, 1.0], dtype=float32)
- numerical.full(shape, value, dtype=None, *, device=None)#
A Tensor of shape whose every element is value, as
numpy.full.- Parameters:
shape – The extents: an integer (a vector) or a sequence of non-negative integers.
value – The number every element holds, or an array-like that broadcasts to shape (its rows repeated, as
numpy.full’s), whose dtype the Tensor takes by default.dtype –
"float64","complex128","float32","complex64"or"bool"; by default complex128 for a complex value, bool for a bool one and float64 otherwise.
- Returns:
The filled Tensor.
- Return type:
- Raises:
ValueError – for a negative extent or a dtype not offered.
TypeError – for a complex value with a real dtype, or a value that is not a number.
Examples
>>> import numerical >>> numerical.full((2,), 7) numerical.Tensor([7.0, 7.0], dtype=float64) >>> numerical.full(2, 1j) numerical.Tensor([1j, 1j], dtype=complex128)
- numerical.eye(n, dtype='float64', *, device=None)#
The n × n identity, as
numpy.eye(n).- Parameters:
n – The order, a non-negative integer.
dtype –
"float64"(the default),"complex128","float32","complex64"or"bool"; NumPy’s dtype objects and Python’sfloat,complexandboolname them too.
- Returns:
The identity matrix.
- Return type:
- Raises:
ValueError – for a negative n or a dtype not offered.
TypeError – if n is not an integer.
Examples
>>> import numerical >>> numerical.eye(2) numerical.Tensor([[1.0, 0.0], [0.0, 1.0]], dtype=float64)
- numerical.tri(N, M=None, k=0, dtype=<class 'float'>)#
The
N × Mmatrix (square where M is None) of ones at and below the k-th diagonal, zeros above, asnumpy.tri.
- numerical.diagflat(v, k=0)#
The square matrix with v flattened on its k-th diagonal and zeros elsewhere, as
numpy.diagflat.
- numerical.meshgrid(*xi, copy=True, sparse=False, indexing='xy')#
Coordinate tensors from coordinate vectors, as
numpy.meshgrid: one per vector, each varying along its own axis (the first two swapped forindexing="xy", matrix order for"ij"), broadcast to the grid unless sparse. copy is NumPy’s and changes nothing (a Tensor is never written into).Examples
>>> import numerical >>> x, y = numerical.meshgrid([1.0, 2.0, 3.0], [4.0, 5.0]) >>> x.shape, y.tolist() ((2, 3), [[4.0, 4.0, 4.0], [5.0, 5.0, 5.0]])
- numerical.arange(start, stop=None, step=1.0, *, dtype=None, device=None)#
start, start + step, …short of stop, asnumpy.arange.- Parameters:
start – The first value; with no stop, the stop itself, the values starting at 0 (
arange(stop)).stop – The bound, not included.
step – The spacing, finite and nonzero, negative for a descending range.
dtype – The values’ dtype, float64 by default (where NumPy takes int64 for integer bounds, until 2026.12.0). Another is filled as NumPy fills it: its first two values
startandstart + stepin that dtype, each next onefirst + i (second − first)computed in it.
- Returns:
The values.
- Return type:
- Raises:
ValueError – for a bound or a step that is not finite, or a zero step (also a
ZeroDivisionError, as NumPy’s).
Examples
>>> import numerical >>> numerical.arange(4) numerical.Tensor([0.0, 1.0, 2.0, 3.0], dtype=float64) >>> numerical.arange(1, 2, 0.25) numerical.Tensor([1.0, 1.25, 1.5, 1.75], dtype=float64)
- numerical.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, *, device=None)#
num values evenly spaced from start to stop, as
numpy.linspaceand by its steps:arange(num) · step + start, through/ div · deltawhere a step is 0, the last value stop itself; start and stop tensors for a tensor of ramps along axis; computed in the inexact dtype they promote to (a Python number weak), floored for an integer dtype.- Parameters:
start – The first value: a number or an array-like.
stop – The last value (past the last, without endpoint).
num – How many values, a non-negative integer (50 by default).
endpoint – Whether stop is the last value; else
numsteps of(stop − start) / num.retstep – Whether to return the step too.
dtype – The result’s dtype; by default that of the computation.
axis – Where the values’ axis goes among the axes of start and stop.
device – The array API’s; None or “cpu” alone.
- Returns:
The values (with the step, a number or a tensor, NaN for fewer than two steps, where retstep).
- Return type:
- Raises:
ValueError – for a negative num.
Examples
>>> import numerical >>> numerical.linspace(0, 1, 5) numerical.Tensor([0.0, 0.25, 0.5, 0.75, 1.0], dtype=float64) >>> numerical.linspace([0.0, 1.0], 2.0, 3, axis=1) numerical.Tensor([[0.0, 1.0, 2.0], [1.0, 1.5, 2.0]], dtype=float64)
- numerical.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)#
base ** linspace(start, stop, num, endpoint, axis=axis), asnumpy.logspace: a tensor base broadcast with start and stop, its axis of the values at axis.
- numerical.geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)#
num values evenly spaced on a log scale from start to stop (both nonzero, negative ones of one sign), as
numpy.geomspace, the ends start and stop themselves. Element k isstart^s · stop^tin float64, s and t the exponents(d − k)/dandk/d, times what their roundings left out: within 3 ulps of the exact value where NumPy’s10 ** linspace(log10(start), log10(stop))loses up to some2·(|ln start| + |ln stop|)ulps, 1500 over 10^±300. Real dtypes.
- numerical.identity(n, dtype=None, *, like=None)#
The
n × nidentity, asnumpy.identity:eye(), float64 by default.
- numerical.vander(x, N=None, increasing=False)#
The Vandermonde matrix of the vector x, as
numpy.vander: its columns the powers of x (decreasing by default), each a running product (x · x · …, as NumPy’smultiply.accumulate); integers stay int64.
- numerical.zeros_like(a, dtype=None, shape=None, *, device=None)#
Zeros of a’s shape and dtype (or those given), as
numpy.zeros_like.
- numerical.ones_like(a, dtype=None, shape=None, *, device=None)#
Ones of a’s shape and dtype (or those given), as
numpy.ones_like.
- numerical.empty_like(a, dtype=None, shape=None, *, device=None)#
A tensor of a’s shape and dtype (or those given), as
numpy.empty_like; its elements zeros here, where NumPy’s are whatever the memory held.
- numerical.full_like(a, fill_value, dtype=None, shape=None, *, device=None)#
fill_value in a’s shape and dtype (or those given), as
numpy.full_like.
- numerical.copy(a)#
a as a Tensor, as
numpy.copy: an array-like read into one; a Tensor itself where it holds its elements row-major (never written, it serves as its own copy), else, for a view, its elements copied out, without the array the view reads.
- numerical.astype(x, dtype, /, *, copy=True, device=None)#
x in dtype (float64, complex128, float32, complex64 or bool), as
numpy.astype: a bool is 0 or 1, a number is true where it is nonzero (either part of a complex one); a complex x has no real dtype (its imaginary part would be lost). In dtype already: with copy (the default) ascopy()gives it (the Tensor itself where it holds its elements row-major, a view’s elements copied out), without it the Tensor itself. device None or"cpu".
- numerical.isdtype(dtype, kind)#
Whether dtype is of kind, as the array API’s
isdtype: a dtype (equal to it), a kind’s name (“bool”, “signed integer”, “unsigned integer”, “integral”, “real floating”, “complex floating”, “numeric”) or a tuple of them (any).Examples
>>> import numerical >>> numerical.isdtype("float32", "real floating"), numerical.isdtype("int64", ("bool", "numeric")) (True, True)
- numerical.result_type(*arrays_and_dtypes)#
The dtype NumPy 2 promotes arrays_and_dtypes to, as
numpy.result_type: tensors and array-likes by their dtypes, dtypes as they are, Python numbers weak (they keep the others’ precision).Examples
>>> import numerical >>> numerical.result_type("float32", "int64"), numerical.result_type(numerical.ones(2, "float32"), 2.0) ('float64', 'float32')
- numerical.can_cast(from_, to, casting='safe')#
Whether from_ (a dtype, or a Tensor’s) converts to to under casting, as
numpy.can_cast: “no” and “equiv” the same dtype alone, “safe” every value held exactly, “same_kind” a kind no lower (bool, integer, real, complex), “unsafe” always.Examples
>>> import numerical >>> numerical.can_cast("int64", "float64"), numerical.can_cast("float64", "float32") (True, False)
- numerical.__array_namespace_info__()#
The array API’s inspection namespace:
capabilities(),default_device(),devices(),default_dtypes()anddtypes(kind=…).
- class numerical.finfo(dtype)#
The limits of a floating-point dtype, as
numpy.finfo: of a complex one, its parts’ (float32 for complex64, float64 for complex128).
- class numerical.iinfo(int_type)#
The limits of an integer dtype, as
numpy.iinfo: int64, NumericAL’s one.
- numerical.pi = 3.141592653589793#
Convert a string or number to a floating-point number, if possible.
- numerical.e = 2.718281828459045#
Convert a string or number to a floating-point number, if possible.
- numerical.inf = inf#
Convert a string or number to a floating-point number, if possible.
- numerical.nan = nan#
Convert a string or number to a floating-point number, if possible.
- numerical.newaxis = None#
The type of the None singleton.
Shapes and joins#
- numerical.reshape(a, shape, *, copy=None)#
The elements of a in the same order under shape, as
numpy.reshape: a Tensor’s elements shared, never copied, whatever copy (NumPy 2.1’s and the array API’s): no Tensor is written into, so a shared one serves as a copy.- Parameters:
a – The Tensor or array-like.
shape – The new extents: an integer or a sequence of them, of a’s size; one extent may be -1, the one the others leave.
- Returns:
The reshaped elements, of a’s dtype.
- Return type:
- Raises:
ValueError – if shape holds another number of elements, or more than one -1.
Examples
>>> import numerical >>> numerical.reshape(numerical.arange(6), (2, 3)) numerical.Tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]], dtype=float64) >>> numerical.reshape(numerical.arange(6), (3, -1)).shape (3, 2)
- numerical.ravel(a)#
The elements of a in row-major order as a vector, as
numpy.ravel.
- numerical.transpose(a, axes=None)#
a with its axes permuted, as
numpy.transpose: a view of a Tensor (its elements copied in their new order only when an operation needs them so).- Parameters:
a – The Tensor or array-like (a bool one kept bool).
axes – A permutation of a’s axes, negative ones counted from the end; by default the axes reversed.
- Returns:
The permuted elements, of a’s dtype.
- Return type:
- Raises:
ValueError – if axes is not a permutation of a’s axes.
Examples
>>> import numerical >>> numerical.transpose([[1, 2], [3, 4]]) numerical.Tensor([[1.0, 3.0], [2.0, 4.0]], dtype=float64) >>> numerical.transpose(numerical.zeros((2, 3, 4)), (1, 0, 2)).shape (3, 2, 4)
- numerical.permute_dims(a, axes=None)#
a with its axes in the order axes (reversed where None), as
numpy.permute_dims(transpose()).
- numerical.matrix_transpose(x, /)#
A matrix, or every matrix of a stack, transposed (its last two axes swapped), as
numpy.linalg.matrix_transpose.
- numerical.squeeze(a, axis=None)#
a without its axes of extent 1, or without the ones axis names (an integer or a tuple), as
numpy.squeeze.- Raises:
ValueError – if an axis axis names has another extent.
- numerical.expand_dims(a, axis)#
a with an axis of extent 1 inserted at each of axis (an integer or a tuple, in the result’s numbering), as
numpy.expand_dims.
- numerical.atleast_1d(*arys)#
Each array with at least one axis (a number a vector of one), as
numpy.atleast_1d: one tensor for one argument, else a list.
- numerical.atleast_2d(*arys)#
Each array with at least two axes (a vector a row), as
numpy.atleast_2d.
- numerical.atleast_3d(*arys)#
Each array with at least three axes, as
numpy.atleast_3d: a vector of n(1, n, 1), a matrix(m, n, 1).
- numerical.shape(a)#
a’s shape, as
numpy.shape.
- numerical.ndim(a)#
a’s number of axes, as
numpy.ndim.
- numerical.size(a, axis=None)#
a’s number of elements, or its extent along axis (an integer or a tuple of them), as
numpy.size.
- numerical.flip(m, axis=None)#
m with its elements in reverse order along axis (an integer, a tuple, or None for every axis), as
numpy.flip.
- numerical.flipud(m)#
m upside down (its first axis reversed), as
numpy.flipud.
- numerical.fliplr(m)#
m left to right (its second axis reversed), as
numpy.fliplr.
- numerical.swapaxes(a, axis1, axis2)#
a with the axes axis1 and axis2 exchanged, as
numpy.swapaxes.
- numerical.moveaxis(a, source, destination)#
a with the axes source moved to the places destination (integers or sequences of one length), the others in their order, as
numpy.moveaxis.
- numerical.concatenate(arrays, /, axis=0, out=None, *, dtype=None)#
The arrays one after the other along axis, as
numpy.concatenate; in dtype where it is given.Every other axis is of one extent. The result is in the dtype they all fit, as NumPy promotes them.
- Parameters:
arrays – A sequence of Tensors or array-likes, of one rank.
axis – The axis to join along (negative counted from the end);
Noneflattens each first.
- Returns:
The joined arrays.
- Return type:
- Raises:
ValueError – if there is no array, one is rank 0, the axis is out of their rank, or the other axes differ.
TypeError – if arrays is a Tensor, a string or not a sequence.
Examples
>>> import numerical >>> numerical.concatenate([[1, 2], [3]]) numerical.Tensor([1.0, 2.0, 3.0], dtype=float64) >>> numerical.concatenate([[[1, 2]], [[3, 4]]], axis=1) numerical.Tensor([[1.0, 2.0, 3.0, 4.0]], dtype=float64)
- numerical.concat(arrays, /, axis=0, out=None, *, dtype=None)#
The arrays one after the other along axis, as
numpy.concatenate; in dtype where it is given.Every other axis is of one extent. The result is in the dtype they all fit, as NumPy promotes them.
- Parameters:
arrays – A sequence of Tensors or array-likes, of one rank.
axis – The axis to join along (negative counted from the end);
Noneflattens each first.
- Returns:
The joined arrays.
- Return type:
- Raises:
ValueError – if there is no array, one is rank 0, the axis is out of their rank, or the other axes differ.
TypeError – if arrays is a Tensor, a string or not a sequence.
Examples
>>> import numerical >>> numerical.concatenate([[1, 2], [3]]) numerical.Tensor([1.0, 2.0, 3.0], dtype=float64) >>> numerical.concatenate([[[1, 2]], [[3, 4]]], axis=1) numerical.Tensor([[1.0, 2.0, 3.0, 4.0]], dtype=float64)
- numerical.stack(arrays, /, axis=0, out=None, *, dtype=None)#
The arrays (one shape) along a new axis axis of the result, as
numpy.stack; in dtype where it is given.The result is in the dtype they all fit, as NumPy promotes them.
- Parameters:
arrays – A sequence of Tensors or array-likes, of one shape.
axis – Where the new axis stands in the result (negative counted from the end).
- Returns:
The stacked arrays, of rank one more than theirs.
- Return type:
- Raises:
ValueError – if there is no array, their shapes differ, or the axis is out of the result’s rank.
TypeError – if arrays is a Tensor, a string or not a sequence.
Examples
>>> import numerical >>> numerical.stack([[1, 2], [3, 4]]) numerical.Tensor([[1.0, 2.0], [3.0, 4.0]], dtype=float64) >>> numerical.stack([[1, 2], [3, 4]], axis=1) numerical.Tensor([[1.0, 3.0], [2.0, 4.0]], dtype=float64)
- numerical.vstack(tup)#
The arrays row-wise, as
numpy.vstack: a vector as a row (1 × n), along the first axis.
- numerical.hstack(tup)#
The arrays column-wise, as
numpy.hstack: vectors one after the other, else along the second axis.
- numerical.column_stack(tup)#
Vectors as columns and matrices as they are, side by side, as
numpy.column_stack.
- numerical.dstack(tup)#
The arrays along the third axis, as
numpy.dstack: each first of rank 3 (atleast_3d()).
- numerical.block(arrays)#
One tensor assembled from nested lists of blocks, as
numpy.block: the innermost lists joined along the last axis, the lists of them along the one before, and so on, each block first given leading axes of extent 1 up to the result’s rank (the deeper of the nesting and the blocks’ ranks).Examples
>>> import numerical >>> numerical.block([[numerical.eye(2), numerical.zeros((2, 1))], [numerical.ones((1, 3))]]) numerical.Tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 1.0]], dtype=float64)
- numerical.pad(array, pad_width, mode='constant', **kwargs)#
array padded by pad_width (one count for every side, a
(before, after)pair, one pair per axis, or a dict of them by axis) asnumpy.padand by its steps, axis after axis: “constant” (constant_values), “edge”, “linear_ramp” (to end_values), “maximum”, “minimum”, “mean” and “median” (of stat_length values from each end), “reflect” and “symmetric” (reflect_type “even” or “odd”), “wrap”, and “empty” (zeros here). A function as mode is refused: NumPy’s writes into the vectors it is handed, and a Tensor is never written into.Examples
>>> import numerical >>> numerical.pad([1.0, 2.0, 3.0], (2, 1), mode="reflect") numerical.Tensor([3.0, 2.0, 1.0, 2.0, 3.0, 2.0], dtype=float64) >>> numerical.pad([[1.0]], 1, constant_values=9) numerical.Tensor([[9.0, 9.0, 9.0], [9.0, 1.0, 9.0], [9.0, 9.0, 9.0]], dtype=float64)
- numerical.trim_zeros(filt, trim='fb', axis=None)#
filt without its leading (
"f") and trailing ("b") zeros, along axis (every one where None), asnumpy.trim_zeros: the slice of filt itself (a list stays a list).
- numerical.append(arr, values, axis=None)#
values after arr along axis, as
numpy.append: both flattened where axis is None.
- numerical.insert(arr, obj, values, axis=None)#
arr with values (in arr’s dtype) inserted before the entries at obj along axis (of the flattened arr where None), as
numpy.insert: obj a slice, an index (values’ first axis along axis) or indices (negative from the end, the extent for the end), the values for equal indices in their order.Examples
>>> import numerical >>> numerical.insert([1, 2, 3], [1, 3], [9, 8]) numerical.Tensor([1.0, 9.0, 2.0, 3.0, 8.0], dtype=float64) >>> numerical.insert([[1, 2], [3, 4]], 1, [7, 8], axis=1) numerical.Tensor([[1.0, 7.0, 2.0], [3.0, 8.0, 4.0]], dtype=float64)
- numerical.delete(arr, obj, axis=None)#
arr without the entries at obj along axis (of the flattened arr where None), as
numpy.delete: obj a slice, an index, indices (negative from the end, repeated ones once) or a mask of the axis’s extent.Examples
>>> import numerical >>> numerical.delete([[1, 2, 3], [4, 5, 6]], [0, -1], axis=1) numerical.Tensor([[2.0], [5.0]], dtype=float64)
- numerical.split(ary, indices_or_sections, axis=0)#
ary cut along axis into a list of tensors, as
numpy.split:array_split(), a number of sections dividing the extent.Examples
>>> import numerical >>> numerical.split([1, 2, 3, 4], 2) [numerical.Tensor([1.0, 2.0], dtype=float64), numerical.Tensor([3.0, 4.0], dtype=float64)]
- numerical.array_split(ary, indices_or_sections, axis=0)#
ary cut along axis into a list of tensors, as
numpy.array_split: at the given indices (slices between them, empty where they do not advance), or into that many sections, the firstextent % sectionsone longer.
- numerical.hsplit(ary, indices_or_sections)#
split()along the second axis (the first of a vector), asnumpy.hsplit.
- numerical.vsplit(ary, indices_or_sections)#
split()along the first axis, asnumpy.vsplit(rank 2 or more).
- numerical.dsplit(ary, indices_or_sections)#
split()along the third axis, asnumpy.dsplit(rank 3 or more).
- numerical.unstack(x, /, *, axis=0)#
The slices of x along axis, as
numpy.unstack: a tuple of tensors.
- numerical.tile(A, reps)#
A repeated reps times along each axis, as
numpy.tile: A and reps brought to one rank by leading extents and counts of 1.Examples
>>> import numerical >>> numerical.tile([1, 2], (2, 2)) numerical.Tensor([[1.0, 2.0, 1.0, 2.0], [1.0, 2.0, 1.0, 2.0]], dtype=float64)
- numerical.repeat(a, repeats, axis=None)#
Each element of a repeated, along axis (of the flattened a where None), as
numpy.repeat: repeats one count for all, or one per element along the axis.Examples
>>> import numerical >>> numerical.repeat([1, 2], 2) numerical.Tensor([1.0, 1.0, 2.0, 2.0], dtype=float64) >>> numerical.repeat([[1, 2], [3, 4]], [1, 2], axis=0) numerical.Tensor([[1.0, 2.0], [3.0, 4.0], [3.0, 4.0]], dtype=float64)
- numerical.roll(a, shift, axis=None)#
a with its elements shifted by shift along axis (of the flattened a where None), those past the end back at the start, as
numpy.roll; shift and axis may be sequences of one length (or one of them a single value), a repeated axis shifted by the sum.Examples
>>> import numerical >>> numerical.roll([1, 2, 3, 4], 1) numerical.Tensor([4.0, 1.0, 2.0, 3.0], dtype=float64)
- numerical.rot90(m, k=1, axes=(0, 1))#
m rotated by 90 degrees k times in the plane of axes, from the first axis toward the second, as
numpy.rot90.Examples
>>> import numerical >>> numerical.rot90([[1, 2], [3, 4]]) numerical.Tensor([[2.0, 4.0], [1.0, 3.0]], dtype=float64)
- numerical.take(a, indices, axis=None, mode='raise')#
The elements of a at indices along axis (of the flattened a where None), as
numpy.take: the result’s shape a’s with that axis replaced by the indices’ shape. mode “raise” refuses an index out of the axis, “wrap” takes it modulo the extent, “clip” to the nearest end.
- numerical.take_along_axis(arr, indices, axis=-1)#
The elements of arr at indices along axis, the other axes matched (broadcast), as
numpy.take_along_axis: the companion ofargsort()(take_along_axis(a, argsort(a, axis), axis)sorts); axis None for the flattened arr and indices of rank 1.Examples
>>> import numerical >>> a = numerical.asarray([[3.0, 1.0], [2.0, 5.0]]) >>> numerical.take_along_axis(a, numerical.argsort(a, axis=1), axis=1) numerical.Tensor([[1.0, 3.0], [2.0, 5.0]], dtype=float64)
- numerical.compress(condition, a, axis=None, out=None)#
The slices of a along axis (of a flattened where None) where condition holds, as
numpy.compress: a shorter condition stops early; a true entry past the axis refused.
- numerical.extract(condition, arr)#
The elements of arr flattened where condition (flattened) holds, as
numpy.extract.
- numerical.choose(a, choices, out=None, mode='raise')#
Each element from the choice its index in a names, all broadcast, as
numpy.choose: an index out of range refused (“raise”), wrapped (“wrap”) or clipped (“clip”).
- numerical.rollaxis(a, axis, start=0)#
a with axis moved to stand before start, as
numpy.rollaxis.
- numerical.resize(a, new_shape)#
a’s elements, flattened and repeated as often as needed, in new_shape, as
numpy.resize.
- numerical.apply_along_axis(func1d, axis, arr, *args, **kwargs)#
func1d of each line of arr along axis, as
numpy.apply_along_axis: the results (one shape for all) where the line stood.
- numerical.broadcast_to(array, shape)#
array repeated along the axes of extent 1 (and new leading ones) to shape, as
numpy.broadcast_to: a copy here (a Tensor is never written, so it reads as NumPy’s read-only view would).
- numerical.broadcast_arrays(*args)#
The arrays broadcast to one shape (
broadcast_shapes()), asnumpy.broadcast_arrays: a tuple.
- numerical.broadcast_shapes(*args)#
The shape args (shapes, an integer a rank-1 one) broadcast to, as
numpy.broadcast_shapes.Examples
>>> import numerical >>> numerical.broadcast_shapes((3, 1), (4,), 1) (3, 4)
- numerical.tril(m, k=0)#
The matrices of m (its last two axes) zero above their k diagonal, as
numpy.tril(a vector broadcast to a square first, as NumPy’s).
- numerical.triu(m, k=0)#
The matrices of m (its last two axes) zero below their k diagonal, as
numpy.triu.
- numerical.diag(v, k=0)#
numpy.diag: a matrix with the vector v on its k diagonal (above the main one for k > 0), or a matrix’s k diagonal as a vector (a copy).- Raises:
ValueError – if v is neither a vector nor a matrix.
- numerical.diagonal(x, /, *, offset=0)#
The offset diagonal of a matrix or of every matrix of a stack (its last two axes), as
numpy.linalg.diagonal: above the main diagonal for a positive offset, below for a negative one; read where it lies, in time of its length.
Element-wise arithmetic#
- numerical.abs(a)#
The magnitude of every element, real of the same precision, as
numpy.abs.
- numerical.absolute(a)#
The magnitude of every element, real of the same precision, as
numpy.abs.
- numerical.negative(x, /)#
-xelement-wise, asnumpy.negative(a bool tensor refused, as NumPy’s).
- numerical.positive(x, /)#
x itself, as
numpy.positive(a Tensor is never written, so it needs no copy).
- numerical.square(x, /)#
x * xelement-wise, asnumpy.square.
- numerical.add(x1, x2, /)#
x1 + x2element-wise, asnumpy.add.
- numerical.subtract(x1, x2, /)#
x1 - x2element-wise, asnumpy.subtract.
- numerical.multiply(x1, x2, /)#
x1 * x2element-wise, asnumpy.multiply.
- numerical.reciprocal(x, /)#
1 / xelement-wise, asnumpy.reciprocal: in x’s dtype, a complex one by NumPy’s loop (Smith’s, the larger part divided first, fused as NumPy’s; an infinity and a NaN for a zero); an integer’s truncated (0 past ±1), which raises for a zero as an infinity converted to int64 does.
- numerical.fabs(x, /)#
The magnitude of every real element, as
numpy.fabs: an integer’s in float64; a complex x refused.
- numerical.divide(x1, x2, /)#
x1 / x2element-wise, asnumpy.divide(numpy.true_divide).
- numerical.true_divide(x1, x2, /)#
x1 / x2element-wise, asnumpy.divide(numpy.true_divide).
- numerical.floor_divide(x1, x2, /)#
x1 // x2element-wise, the quotient floored, asnumpy.floor_divide: NumPy’sdivmodfor reals (by zerox1 / x2: ±inf or NaN). Real dtypes, as NumPy’s.Examples
>>> import numerical >>> numerical.floor_divide(numerical.asarray([7.0, -7.0]), 2) numerical.Tensor([3.0, -4.0], dtype=float64)
- numerical.remainder(x1, x2, /)#
x1 % x2element-wise, of x2’s sign as Python’s, asnumpy.remainder(numpy.mod): NumPy’sdivmodfor reals (by zero NaN). Real dtypes, as NumPy’s.Examples
>>> import numerical >>> numerical.remainder(numerical.asarray([7.0, -7.0]), 2) numerical.Tensor([1.0, 1.0], dtype=float64)
- numerical.mod(x1, x2, /)#
x1 % x2element-wise, of x2’s sign as Python’s, asnumpy.remainder(numpy.mod): NumPy’sdivmodfor reals (by zero NaN). Real dtypes, as NumPy’s.Examples
>>> import numerical >>> numerical.remainder(numerical.asarray([7.0, -7.0]), 2) numerical.Tensor([1.0, 1.0], dtype=float64)
- numerical.divmod(x1, x2, /)#
(x1 // x2, x1 % x2)element-wise, asnumpy.divmod.
- numerical.power(a, b)#
a to the power b element by element, broadcast, as
numpy.power.
- numerical.maximum(x1, x2, /)#
The larger of x1 and x2 element-wise, broadcast, as
numpy.maximum: a NaN wins (the first’s where both), and +0 over −0 whatever their order, as IEEE 754-2019’s maximum (NumPy’s on arm64, andmax()’s). Real dtypes.
- numerical.minimum(x1, x2, /)#
The smaller of x1 and x2 element-wise, broadcast, as
numpy.minimum: a NaN wins (the first’s where both), and −0 under +0 whatever their order, as IEEE 754-2019’s minimum. Real dtypes.
- numerical.fmax(x1, x2, /)#
The larger of x1 and x2 element-wise, a NaN losing to a number (NaN only where both are), as
numpy.fmax; +0 over −0 whatever their order (NumPy’s on arm64). Real dtypes; int64 stays.
- numerical.fmin(x1, x2, /)#
The smaller of x1 and x2 element-wise, a NaN losing to a number, as
numpy.fmin; −0 under +0 whatever their order. Real dtypes; int64 stays.
- numerical.fmod(x1, x2, /)#
C’s remainder
x1 − trunc(x1 / x2) · x2element-wise, of x1’s sign (whereremainder()takes x2’s), asnumpy.fmod: by zero NaN, an int64 0. Real dtypes; int64 stays.Examples
>>> import numerical >>> numerical.fmod([7.0, -7.0], 2) numerical.Tensor([1.0, -1.0], dtype=float64)
- numerical.float_power(x1, x2, /)#
x1 ** x2element-wise in float64 (complex128 for a complex operand), asnumpy.float_power: an integer to a negative power a fraction, wherepower()refuses it.
- numerical.copysign(x1, x2, /)#
x1’s magnitude with x2’s sign element-wise (a zero’s and a NaN’s sign too), as
numpy.copysign. Real dtypes; integers in float64.
- numerical.bitwise_and(x1, x2, /)#
Each pair of integers’ bits and-ed, as
numpy.bitwise_and(&): int64 (two bool operands: their logical and).
- numerical.bitwise_or(x1, x2, /)#
Each pair of integers’ bits or-ed, as
numpy.bitwise_or(|): int64 (two bool operands: their logical or).
- numerical.bitwise_xor(x1, x2, /)#
Each pair of integers’ bits xor-ed, as
numpy.bitwise_xor(^): int64 (two bool operands: their logical xor).
- numerical.left_shift(x1, x2, /)#
Each integer’s bits shifted left by the other’s count, as
numpy.left_shift(<<): int64, wrapping; by 64 or more (or a negative count), 0.
- numerical.right_shift(x1, x2, /)#
Each integer’s bits shifted right by the other’s count, its sign kept, as
numpy.right_shift(>>): int64; by 64 or more (or a negative count), 0 or −1.
- numerical.bitwise_left_shift(x1, x2, /)#
Each integer’s bits shifted left by the other’s count, as
numpy.left_shift(<<): int64, wrapping; by 64 or more (or a negative count), 0.
- numerical.bitwise_right_shift(x1, x2, /)#
Each integer’s bits shifted right by the other’s count, its sign kept, as
numpy.right_shift(>>): int64; by 64 or more (or a negative count), 0 or −1.
- numerical.gcd(x1, x2, /)#
The greatest common divisor of each pair of integers, as
numpy.gcd(non-negative;gcd(INT64_MIN, 0)wraps to INT64_MIN, as NumPy’s).
- numerical.lcm(x1, x2, /)#
The least common multiple of each pair of integers, as
numpy.lcm(non-negative, wrapping; 0 where either is).
- numerical.invert(x, /)#
Each integer’s bits flipped (
~x = −x − 1), asnumpy.invert; a bool’s negation.
- numerical.bitwise_not(x, /)#
Each integer’s bits flipped (
~x = −x − 1), asnumpy.invert; a bool’s negation.
- numerical.bitwise_invert(x, /)#
Each integer’s bits flipped (
~x = −x − 1), asnumpy.invert; a bool’s negation.
- numerical.bitwise_count(x, /)#
The number of 1 bits of each integer’s magnitude, as
numpy.bitwise_count: int64, where NumPy’s is uint8.
- numerical.nextafter(x1, x2, /)#
The next representable number after x1 toward x2 element-wise, as
numpy.nextafter. Real dtypes; integers in float64.
- numerical.clip(a, a_min=None, a_max=None, *, min=None, max=None)#
a limited to
[a_min, a_max]element-wise, asnumpy.clip:minimum(maximum(a, a_min), a_max), either bound None for none (a itself for both). A NaN in a stays. min and max, NumPy 2’s and the array API’s names of the bounds, in place of a_min and a_max.
- numerical.real(x, /)#
The real part of every element, of the parts’ precision, as
numpy.real; a real or bool tensor itself.
- numerical.imag(x, /)#
The imaginary part of every element, of the parts’ precision, as
numpy.imag; zeros of a real or bool tensor’s dtype.
- numerical.conj(x)#
The complex conjugate of every element, as
numpy.conj; a real, int64 or bool tensor’s own elements.
- numerical.conjugate(x)#
The complex conjugate of every element, as
numpy.conj; a real, int64 or bool tensor’s own elements.
- numerical.angle(z, deg=False)#
The argument of every element,
arctan2(imag, real)in[−π, π], asnumpy.angle(a real’s 0, or π where it is negative or −0); in degrees for deg.
- numerical.sign(x, /)#
−1, 0 or 1 by every element’s sign (+0 for either zero, a NaN kept), as
numpy.sign; a complex number’sz / |z|, as NumPy 2’s and the array API’s: 0 for 0, NaN for a NaN modulus, and for an infinite modulus ±1 along the infinite part (NaN where both are).
- numerical.round(a, decimals=0)#
Every element rounded to decimals places (tens, hundreds for a negative one), half to even, as
numpy.round:rint(a · 10ᵈ) / 10ᵈ(· 10⁻ᵈfor a negative decimals), NumPy’s own way, with its rounding of the scaled value; a complex number’s parts apart. A value already exact to those places (its ulp coarser than them) is kept, where NumPy’s product can overflow (round(1e307, 2): inf) or move its last bit, and a finite value rounds to 0 where10⁻ᵈoverflows (NumPy’s: NaN).
- numerical.around(a, decimals=0)#
Every element rounded to decimals places (tens, hundreds for a negative one), half to even, as
numpy.round:rint(a · 10ᵈ) / 10ᵈ(· 10⁻ᵈfor a negative decimals), NumPy’s own way, with its rounding of the scaled value; a complex number’s parts apart. A value already exact to those places (its ulp coarser than them) is kept, where NumPy’s product can overflow (round(1e307, 2): inf) or move its last bit, and a finite value rounds to 0 where10⁻ᵈoverflows (NumPy’s: NaN).
- numerical.floor(x, /)#
The largest integer at or below every element, as
numpy.floor. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
- numerical.ceil(x, /)#
The smallest integer at or above every element, as
numpy.ceil. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
- numerical.trunc(x, /)#
Every element rounded toward zero, as
numpy.trunc. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
- numerical.rint(x, /)#
Every element rounded to the nearest integer, half to even, as
numpy.rint. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
Element-wise functions#
- numerical.exp(a)#
e to the power of every element, as
numpy.exp.- Parameters:
a – The Tensor or array-like (a bool array-like read as float64; a bool Tensor refused).
- Returns:
Of a’s shape and dtype (float64 for integers).
- Return type:
- Raises:
TypeError – if a is a bool Tensor or nothing
asarray()reads.
Examples
>>> import numerical >>> numerical.exp([0.0, 0.0]) numerical.Tensor([1.0, 1.0], dtype=float64) >>> numerical.exp([0j]) numerical.Tensor([(1+0j)], dtype=complex128)
- numerical.log(a)#
The natural logarithm of every element, as
numpy.log.NaN below 0 for a real dtype,
-infat 0; a complex element’s principal logarithm.- Parameters:
a – The Tensor or array-like (a bool array-like read as float64; a bool Tensor refused).
- Returns:
Of a’s shape and dtype (float64 for integers).
- Return type:
- Raises:
TypeError – if a is a bool Tensor or nothing
asarray()reads.
Examples
>>> import numerical >>> numerical.log([1.0, 0.0, -1.0]) numerical.Tensor([0.0, -inf, nan], dtype=float64)
- numerical.sqrt(a)#
The square root of every element, as
numpy.sqrt.NaN below 0 for a real dtype; a complex element’s principal root.
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64; a bool Tensor refused).
- Returns:
Of a’s shape and dtype (float64 for integers).
- Return type:
- Raises:
TypeError – if a is a bool Tensor or nothing
asarray()reads.
Examples
>>> import numerical >>> numerical.sqrt([4.0, 9.0, -1.0]) numerical.Tensor([2.0, 3.0, nan], dtype=float64) >>> numerical.sqrt([-1.0 + 0j]) numerical.Tensor([1j], dtype=complex128)
- numerical.sin(a)#
The sine of every element, as
numpy.sin.
- numerical.cos(a)#
The cosine of every element, as
numpy.cos.
- numerical.tan(a)#
The tangent of every element, as
numpy.tan.
- numerical.tanh(a)#
The hyperbolic tangent of every element, as
numpy.tanh.
- numerical.arcsin(x, /)#
The inverse sine of every element, as
numpy.arcsin. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.arccos(x, /)#
The inverse cosine of every element, as
numpy.arccos. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.arctan(x, /)#
The inverse tangent of every element, as
numpy.arctan. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.sinh(x, /)#
The hyperbolic sine of every element, as
numpy.sinh. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.cosh(x, /)#
The hyperbolic cosine of every element, as
numpy.cosh. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.arcsinh(x, /)#
The inverse hyperbolic sine of every element, as
numpy.arcsinh. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.arccosh(x, /)#
The inverse hyperbolic cosine of every element, as
numpy.arccosh. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.arctanh(x, /)#
The inverse hyperbolic tangent of every element, as
numpy.arctanh. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.acos(x, /)#
The inverse cosine of every element, as
numpy.arccos. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.asin(x, /)#
The inverse sine of every element, as
numpy.arcsin. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.atan(x, /)#
The inverse tangent of every element, as
numpy.arctan. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.acosh(x, /)#
The inverse hyperbolic cosine of every element, as
numpy.arccosh. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.asinh(x, /)#
The inverse hyperbolic sine of every element, as
numpy.arcsinh. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.atanh(x, /)#
The inverse hyperbolic tangent of every element, as
numpy.arctanh. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.pow(a, b)#
a to the power b element by element, broadcast, as
numpy.power.
- numerical.log2(x, /)#
The base-2 logarithm of every element, as
numpy.log2. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.log10(x, /)#
The base-10 logarithm of every element, as
numpy.log10. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.log1p(x, /)#
log(1 + x)of every element, accurate near 0, asnumpy.log1p. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.expm1(x, /)#
exp(x) − 1of every element, accurate near 0, asnumpy.expm1. C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.exp2(x, /)#
2ˣof every element, asnumpy.exp2(C’sexp2: exact at integers). C’s function where it has one, within an ulp or two of NumPy’s own; a complex number’s glibc’s (NumPy’s on Linux) or NumPy’s formula.
- numerical.ldexp(x1, x2, /)#
x1 · 2^x2element-wise, rounded once, asnumpy.ldexp(C’s): x2 integers; x1’s float dtype (float64 for integers).
- numerical.frexp(x, /)#
Each element as
m · 2^ewith0.5 ≤ |m| < 1(m = x,e = 0for a zero, an infinity or a NaN), asnumpy.frexp: m of x’s float dtype; e int64, where NumPy’s is int32.
- numerical.modf(x, /)#
The fractional and the integral parts of every element, each of its sign, as
numpy.modf(C’smodf: an infinity’s fraction a zero).
- numerical.spacing(x, /)#
The distance from every element to the next number away from zero, of its sign (a zero’s positive), as
numpy.spacing: NaN for an infinity.
- numerical.sinc(x)#
sin(πx) / (πx)of every element, 1 at 0, asnumpy.sincby its steps (a zero taken as 10⁻²⁰).
- numerical.real_if_close(a, tol=100)#
a’s real parts where every imaginary part is within tol machine epsilons of zero (tol > 1) or tol itself, as
numpy.real_if_close; a as it is otherwise.
- numerical.cbrt(x, /)#
The cube root of every element, as
numpy.cbrt. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
- numerical.deg2rad(x, /)#
Every element in degrees to radians,
x · π/180, asnumpy.deg2rad. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
- numerical.rad2deg(x, /)#
Every element in radians to degrees,
x · 180/π, asnumpy.rad2deg. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
- numerical.radians(x, /)#
Every element in degrees to radians,
x · π/180, asnumpy.deg2rad. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
- numerical.degrees(x, /)#
Every element in radians to degrees,
x · 180/π, asnumpy.rad2deg. Real dtypes; C’s function where it has one, within an ulp or two of NumPy’s own.
- numerical.hypot(x1, x2, /)#
√(x1² + x2²)element-wise without overflow, asnumpy.hypot(C’shypot). Real dtypes; integers in float64.Examples
>>> import numerical >>> numerical.hypot([3.0, 1e300], [4.0, 1e300]) numerical.Tensor([5.0, 1.4142135623730952e+300], dtype=float64)
- numerical.arctan2(x1, x2, /)#
The angle of the point
(x2, x1)element-wise, in[−π, π], asnumpy.arctan2(C’satan2: the zeros’ signs pick the quadrant). Real dtypes; integers in float64.Examples
>>> import numerical >>> numerical.arctan2([1.0, 0.0], [0.0, -1.0]) numerical.Tensor([1.5707963267948966, 3.141592653589793], dtype=float64)
- numerical.atan2(x1, x2, /)#
The angle of the point
(x2, x1)element-wise, in[−π, π], asnumpy.arctan2(C’satan2: the zeros’ signs pick the quadrant). Real dtypes; integers in float64.Examples
>>> import numerical >>> numerical.arctan2([1.0, 0.0], [0.0, -1.0]) numerical.Tensor([1.5707963267948966, 3.141592653589793], dtype=float64)
- numerical.logaddexp(x1, x2, /)#
log(exp(x1) + exp(x2))element-wise without overflow, asnumpy.logaddexpand by its formula. Real dtypes; integers in float64.Examples
>>> import numerical >>> numerical.logaddexp([1000.0], [1000.0]) numerical.Tensor([1000.6931471805599], dtype=float64)
- numerical.logaddexp2(x1, x2, /)#
log2(2**x1 + 2**x2)element-wise without overflow, asnumpy.logaddexp2and by its formula. Real dtypes; integers in float64.
- numerical.heaviside(x1, x2, /)#
The Heaviside step of x1 element-wise, as
numpy.heaviside: 0 below 0, x2 at either zero, 1 above, NaN for a NaN. Real dtypes; integers in float64.Examples
>>> import numerical >>> numerical.heaviside([-1.0, 0.0, 2.0], 0.5) numerical.Tensor([0.0, 0.5, 1.0], dtype=float64)
- numerical.unwrap(p, discont=None, axis=-1, *, period=6.283185307179586)#
p with each jump along axis of more than discont (by default half the period) taken back by a whole number of periods, as
numpy.unwrapand by its formula: each difference brought into[−period/2, period/2)(a difference of exactly half a period kept positive where it was), the corrections summed from the start. Real dtypes; integers in float64.
- numerical.nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None)#
x with each NaN replaced by nan, +inf by posinf and −inf by neginf (by default the dtype’s largest finite number and its negative), a complex element’s parts apart, as
numpy.nan_to_num; integers and bools as they are. copy is NumPy’s and changes nothing here: a Tensor is never written into.Examples
>>> import numerical >>> numerical.nan_to_num([float("nan"), float("inf"), -float("inf"), 1.0]) numerical.Tensor([0.0, 1.7976931348623157e+308, -1.7976931348623157e+308, 1.0], dtype=float64)
Comparisons and logic#
- numerical.equal(x1, x2, /)#
x1 == x2element by element, broadcast, asnumpy.equal: a bool Tensor.
- numerical.not_equal(x1, x2, /)#
x1 != x2element by element, broadcast, asnumpy.not_equal: a bool Tensor.
- numerical.less(x1, x2, /)#
x1 < x2element by element, broadcast, asnumpy.less: a bool Tensor.
- numerical.less_equal(x1, x2, /)#
x1 <= x2element by element, broadcast, asnumpy.less_equal: a bool Tensor.
- numerical.greater(x1, x2, /)#
x1 > x2element by element, broadcast, asnumpy.greater: a bool Tensor.
- numerical.greater_equal(x1, x2, /)#
x1 >= x2element by element, broadcast, asnumpy.greater_equal: a bool Tensor.
- numerical.logical_and(x1, x2, /)#
Whether both elements are true (nonzero), element by element, broadcast, as
numpy.logical_and.
- numerical.logical_or(x1, x2, /)#
Whether either element is true (nonzero), element by element, broadcast, as
numpy.logical_or.
- numerical.logical_xor(x1, x2, /)#
Whether exactly one element is true (nonzero), element by element, broadcast, as
numpy.logical_xor.
- numerical.logical_not(x, /)#
Whether each element is false (zero), as
numpy.logical_not.
- numerical.isnan(x, /)#
Whether each element is a NaN (either part of a complex one), as
numpy.isnan: a bool Tensor.
- numerical.isinf(x, /)#
Whether each element is infinite (either part of a complex one), as
numpy.isinf: a bool Tensor.
- numerical.isfinite(x, /)#
Whether each element is finite (both parts of a complex one), as
numpy.isfinite: a bool Tensor.
- numerical.isposinf(x, out=None)#
Whether each real element is +∞, as
numpy.isposinf.
- numerical.isneginf(x, out=None)#
Whether each real element is −∞, as
numpy.isneginf.
- numerical.signbit(x, /)#
Whether each real element’s sign bit is set (−0 and a negative NaN’s too), as
numpy.signbit.
- numerical.iscomplex(x)#
Whether each element has a nonzero imaginary part, as
numpy.iscomplex: false throughout for a real dtype.
- numerical.isreal(x)#
Whether each element’s imaginary part is zero, as
numpy.isreal: true throughout for a real dtype.
- numerical.iscomplexobj(x)#
Whether x is of a complex dtype (or a complex number), as
numpy.iscomplexobj; its values unread.
- numerical.isrealobj(x)#
Whether x is not of a complex dtype, as
numpy.isrealobj.
- numerical.isscalar(element)#
Whether element is a scalar, as
numpy.isscalar: a number, a string or bytes (NumPy’s scalars too), not a Tensor, even of rank 0.
- numerical.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)#
Where
|a − b| ≤ atol + rtol |b|element-wise, asnumpy.isclose: infinities close only to themselves, NaNs to nothing unless equal_nan.
- numerical.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)#
Whether every pair is close (
isclose()), asnumpy.allclose.
- numerical.array_equal(a, b, equal_nan=False)#
Truewhen a and b (Tensors or array-likes) have the same shape and equal elements, asnumpy.array_equal: a NaN equals nothing, itself included, unless equal_nan (a complex one with a NaN part equal to any other).
- numerical.array_equiv(a1, a2)#
Whether a1 and a2 broadcast to one shape and are equal there, as
numpy.array_equiv.
- numerical.where(condition, x, y, /)#
x’s element where condition holds, else y’s, the three broadcast, as
numpy.where.- Parameters:
condition – A bool Tensor or what
asarray()reads (a number true where nonzero).x – The elements taken where condition holds: a Tensor or an array-like.
y – The elements taken elsewhere: a Tensor or an array-like.
- Returns:
Of the shape the three broadcast to, in the dtype x and y promote to, as arithmetic promotes them.
- Return type:
- Raises:
ValueError – if the shapes do not broadcast.
TypeError – if an operand is nothing
asarray()reads.
Examples
>>> import numerical >>> numerical.where([True, False], [1, 2], [3, 4]) numerical.Tensor([1.0, 4.0], dtype=float64) >>> numerical.where([[True], [False]], [1, 2], 0) numerical.Tensor([[1.0, 2.0], [0.0, 0.0]], dtype=float64)
- numerical.select(condlist, choicelist, default=0)#
Each element from the first choice whose condition holds there, else default, as
numpy.select: the conditions bool, broadcast with the choices, the result in the dtype they promote to (a Python number weak).
- numerical.any(a, axis=None, keepdims=False, *, dtype=None)#
Whether any element is true (nonzero), or any along axis (a bool Tensor without it), as
numpy.any. axis may name several axes (a tuple, () for none), and keepdims keeps each reduced axis with extent 1, as NumPy’s.
- numerical.all(a, axis=None, keepdims=False, *, dtype=None)#
Whether every element is true (nonzero), or every one along axis (a bool Tensor without it), as
numpy.all. axis may name several axes (a tuple, () for none), and keepdims keeps each reduced axis with extent 1, as NumPy’s.
Reductions, scans and sorting#
- numerical.sum(a, axis=None, keepdims=False, *, dtype=None, initial=<object object>)#
The sum of every element, or the sums along axis, as
numpy.sum.Added by pairwise halving, as NumPy adds.
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
dtype – The dtype the elements are converted to and summed in (keyword-only), as NumPy’s and the array API’s.
initial – The value each sum starts from (keyword-only), in its dtype, as NumPy’s; None for none.
- Returns:
A number for every element, else a Tensor of a’s dtype (float64 for a bool one).
- Return type:
float | complex | Tensor
- Raises:
ValueError – for an axis out of range or repeated.
TypeError – for a complex initial of a real sum.
Examples
>>> import numerical >>> numerical.sum([[1.0, 2.0], [3.0, 4.0]]) 10.0 >>> numerical.sum([[1.0, 2.0], [3.0, 4.0]], axis=0) numerical.Tensor([4.0, 6.0], dtype=float64) >>> numerical.sum([[1.0, 2.0], [3.0, 4.0]], axis=1, keepdims=True) numerical.Tensor([[3.0], [7.0]], dtype=float64)
- numerical.mean(a, axis=None, keepdims=False, *, dtype=None)#
The mean of every element, or the means along axis, as
numpy.mean.- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
dtype – The dtype the elements are converted to and averaged in (keyword-only), as NumPy’s and the array API’s.
- Returns:
A number for every element, else a Tensor of a’s dtype (float64 for a bool one).
- Return type:
float | complex | Tensor
- Raises:
ValueError – for an axis out of range or repeated.
Examples
>>> import numerical >>> numerical.mean([[1.0, 2.0], [3.0, 4.0]]) 2.5 >>> numerical.mean([[1.0, 2.0], [3.0, 4.0]], axis=1) numerical.Tensor([1.5, 3.5], dtype=float64)
- numerical.max(a, axis=None, keepdims=False, *, dtype=None, initial=<object object>)#
The largest element, or the largest along axis, as
numpy.max.A NaN wins. Real dtypes only (a complex one has no order).
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
- Returns:
A number for every element, else a Tensor of a’s dtype.
- Return type:
float | bool | Tensor
- Raises:
ValueError – for an axis out of range or repeated, or a reduction over no element.
TypeError – for a complex a.
Examples
>>> import numerical >>> numerical.max([[1.0, 2.0], [3.0, 4.0]]) 4.0 >>> numerical.max([[1.0, 2.0], [3.0, 4.0]], axis=0) numerical.Tensor([3.0, 4.0], dtype=float64) >>> numerical.max([1.0, float("nan")]) nan
- numerical.min(a, axis=None, keepdims=False, *, dtype=None, initial=<object object>)#
The smallest element, or the smallest along axis, as
numpy.min.A NaN wins. Real dtypes only.
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
- Returns:
A number for every element, else a Tensor of a’s dtype.
- Return type:
float | bool | Tensor
- Raises:
ValueError – for an axis out of range or repeated, or a reduction over no element.
TypeError – for a complex a.
Examples
>>> import numerical >>> numerical.min([[1.0, 2.0], [3.0, 4.0]]) 1.0 >>> numerical.min([[1.0, 2.0], [3.0, 4.0]], axis=1) numerical.Tensor([1.0, 3.0], dtype=float64)
- numerical.amax(a, axis=None, keepdims=False, *, dtype=None, initial=<object object>)#
The largest element, or the largest along axis, as
numpy.max.A NaN wins. Real dtypes only (a complex one has no order).
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
- Returns:
A number for every element, else a Tensor of a’s dtype.
- Return type:
float | bool | Tensor
- Raises:
ValueError – for an axis out of range or repeated, or a reduction over no element.
TypeError – for a complex a.
Examples
>>> import numerical >>> numerical.max([[1.0, 2.0], [3.0, 4.0]]) 4.0 >>> numerical.max([[1.0, 2.0], [3.0, 4.0]], axis=0) numerical.Tensor([3.0, 4.0], dtype=float64) >>> numerical.max([1.0, float("nan")]) nan
- numerical.amin(a, axis=None, keepdims=False, *, dtype=None, initial=<object object>)#
The smallest element, or the smallest along axis, as
numpy.min.A NaN wins. Real dtypes only.
- Parameters:
a – The Tensor or array-like (a bool array-like read as float64).
axis –
None(every element), an integer, or a tuple of them (()for none); negative ones count from the end.keepdims – Keep each reduced axis with extent 1, as NumPy’s.
- Returns:
A number for every element, else a Tensor of a’s dtype.
- Return type:
float | bool | Tensor
- Raises:
ValueError – for an axis out of range or repeated, or a reduction over no element.
TypeError – for a complex a.
Examples
>>> import numerical >>> numerical.min([[1.0, 2.0], [3.0, 4.0]]) 1.0 >>> numerical.min([[1.0, 2.0], [3.0, 4.0]], axis=1) numerical.Tensor([1.0, 3.0], dtype=float64)
- numerical.prod(a, axis=None, keepdims=False, *, dtype=None, initial=<object object>)#
The product of every element (a number), or the products along axis, as
numpy.prod: in order (NumPy’s multiplications are not paired as its sums are). An empty one’s is 1. dtype the one the elements are multiplied in; initial the first factor of each product, as NumPy’s (None: none).
- numerical.cumsum(a, axis=None, dtype=None, out=None)#
The running sums along axis (every element flattened where None), in order, as
numpy.cumsum; dtype the one the elements are converted to and summed in.
- numerical.cumprod(a, axis=None, dtype=None, out=None)#
The running products along axis (every element flattened where None), in order, as
numpy.cumprod; dtype the one the elements are converted to and multiplied in.
- numerical.cumulative_sum(x, /, *, axis=None, dtype=None, out=None, include_initial=False)#
The running sums along axis, as
numpy.cumulative_sum(the array API’s):cumsum(), axis required past rank 1, a 0 first where include_initial.
- numerical.cumulative_prod(x, /, *, axis=None, dtype=None, out=None, include_initial=False)#
The running products along axis, as
numpy.cumulative_prod:cumprod(), axis required past rank 1, a 1 first where include_initial.
- numerical.ediff1d(ary, to_end=None, to_begin=None)#
The differences of consecutive elements of ary flattened, as
numpy.ediff1d: to_begin before them and to_end after (flattened, cast to ary’s dtype, which they must reach under NumPy’s “same_kind” rule).
- numerical.ptp(a, axis=None, keepdims=False)#
The range, maximum less minimum, over every element or along axis, as
numpy.ptp.
- numerical.var(a, axis=None, dtype=None, ddof=0, keepdims=False, *, correction=None)#
The variance,
Σ |x − mean|² / (N − ddof)over every element or along axis, asnumpy.var: real, of a’s precision (a complex one’s parts’ squares summed); dtype the one to compute in; correction another name for ddof.
- numerical.std(a, axis=None, dtype=None, ddof=0, keepdims=False, *, correction=None)#
The standard deviation, the square root of
var(), asnumpy.std.
- numerical.nansum(a, axis=None, dtype=None, out=None, keepdims=False)#
sum()with each NaN counted as 0, asnumpy.nansum(an all-NaN slice’s sum 0).
- numerical.nanprod(a, axis=None, dtype=None, out=None, keepdims=False)#
prod()with each NaN counted as 1, asnumpy.nanprod.
- numerical.nancumsum(a, axis=None, dtype=None, out=None)#
cumsum()with each NaN counted as 0, asnumpy.nancumsum.
- numerical.nancumprod(a, axis=None, dtype=None, out=None)#
cumprod()with each NaN counted as 1, asnumpy.nancumprod.
- numerical.nanmax(a, axis=None, out=None, keepdims=False, initial=<object object>)#
max()ignoring NaNs, asnumpy.nanmax: NaN (with aRuntimeWarning) for a slice of NaNs alone, or initial where it is given (NumPy’sfmaxfrom it).
- numerical.nanmin(a, axis=None, out=None, keepdims=False, initial=<object object>)#
min()ignoring NaNs, asnumpy.nanmin: NaN (with aRuntimeWarning) for a slice of NaNs alone, or initial where it is given (NumPy’sfminfrom it).
- numerical.nanargmax(a, axis=None, out=None, *, keepdims=False)#
argmax()ignoring NaNs, asnumpy.nanargmax:ValueErrorfor a slice of NaNs alone.
- numerical.nanargmin(a, axis=None, out=None, *, keepdims=False)#
argmin()ignoring NaNs, asnumpy.nanargmin:ValueErrorfor a slice of NaNs alone.
- numerical.nanmean(a, axis=None, dtype=None, out=None, keepdims=False)#
The mean of the elements that are not NaN, as
numpy.nanmean: NaN (with aRuntimeWarning) for a slice of NaNs alone.
- numerical.nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, correction=None)#
The variance of the elements that are not NaN, as
numpy.nanvarand by its steps: NaN (with aRuntimeWarning) where they are no more than ddof (correction, NumPy 2’s other name for it).
- numerical.nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, correction=None)#
The standard deviation of the elements that are not NaN, the square root of
nanvar(), asnumpy.nanstd.
- numerical.median(a, axis=None, out=None, overwrite_input=False, keepdims=False)#
The median of every element, or the medians along axis (an integer or a tuple), as
numpy.median: the middle element of the sorted ones, or the mean of the two middle ones; NaN where there is a NaN; integers in float64. overwrite_input is NumPy’s and changes nothing here (a Tensor is never written into).Examples
>>> import numerical >>> numerical.median([[1.0, 3.0, 2.0], [4.0, 6.0, 8.0]], axis=1) numerical.Tensor([2.0, 6.0], dtype=float64)
- numerical.nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=False)#
median()of the elements that are not NaN, asnumpy.nanmedian: NaN (with aRuntimeWarning) for a slice of NaNs alone.
- numerical.quantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, weights=None)#
The q-th quantiles (in [0, 1]) of every element or along axis, as
numpy.quantileand by its steps (its 13 methods, its interpolation, NumPy 2.4’s weak Python q: a float32 kept beside it); the quantiles’ axes first. Real dtypes. weights (method “inverted_cdf” alone, as NumPy’s), non-negative, of a’s shape or of the extents of axis in its order: the first sorted value whose share of the weights reaches q.Examples
>>> import numerical >>> numerical.quantile([1.0, 2.0, 3.0, 4.0], [0.25, 0.5]) numerical.Tensor([1.75, 2.5], dtype=float64) >>> numerical.quantile([1.0, 2.0, 3.0], 0.5, method="inverted_cdf", weights=[1.0, 1.0, 3.0]) 3.0
- numerical.percentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, weights=None)#
The q-th percentiles (in [0, 100]) of every element or along axis, as
numpy.percentile:quantile()atq / 100.
- numerical.nanquantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, weights=None)#
quantile()of the elements that are not NaN, asnumpy.nanquantile: NaN (with aRuntimeWarning) for a slice of NaNs alone.
- numerical.nanpercentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, weights=None)#
percentile()of the elements that are not NaN, asnumpy.nanpercentile.
- numerical.average(a, axis=None, weights=None, returned=False, *, keepdims=False)#
The mean of a, or its mean weighted by weights, over every element or along axis (an integer or a tuple), as
numpy.average:Σ a·w / Σ w; with returned, the pair of it and the sum of the weights (the count without them). weights of a’s shape, or of the extents of axis alone.Examples
>>> import numerical >>> numerical.average([1.0, 2.0, 4.0], weights=[3.0, 1.0, 0.0]) 1.25
- numerical.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None)#
The covariance matrix of the variables in the rows of m (its columns without rowvar), the rows of y joined after them, as
numpy.covand by its steps: the deviations from the (weighted) means, their products summed (a matrix product) and scaled by the reciprocal ofN − ddof(of its weighted form for fweights, integer repeat counts, and aweights, relative weights). One variable’s a number.Examples
>>> import numerical >>> numerical.cov([[0.0, 1.0, 2.0], [2.0, 1.0, 0.0]]) numerical.Tensor([[1.0, -1.0], [-1.0, 1.0]], dtype=float64)
- numerical.corrcoef(x, y=None, rowvar=True, *, dtype=None)#
The Pearson correlation coefficients of the variables in the rows of x (its columns without rowvar), the rows of y joined after them, as
numpy.corrcoef:cov()divided by the products of the standard deviations, then clipped to [−1, 1] (each part of a complex coefficient).
- numerical.sort(a, axis=-1, kind=None, stable=None, *, descending=False)#
The elements sorted along axis (every element flattened where None), as
numpy.sort: ascending, NaNs last, a complex number by its real part then its imaginary part, False before True; equal elements keep their order whatever kind (NumPy’s default sort may order them otherwise, which only a zero’s sign or a NaN’s payload shows). descending, the array API’s: the reverse order, NaNs first, equal elements still in theirs.
- numerical.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, *, equal_nan=True, sorted=True)#
The sorted distinct elements of ar flattened (or its distinct slices along axis, ordered as tuples), as
numpy.unique: with the index of each one’s first occurrence, the index of each element’s among them (of ar’s shape), and their counts, where asked (int64); NaNs as one where equal_nan. A zero’s sign is the first one’s met (the order is stable). sorted is NumPy’s: the elements are sorted either way.
- numerical.unique_values(x)#
The distinct elements of x, as
numpy.unique_values(the array API’s): each NaN its own.
- numerical.unique_counts(x)#
The distinct elements of x and their counts, as
numpy.unique_counts: each NaN its own.
- numerical.unique_inverse(x)#
The distinct elements of x and the index of each element’s among them, as
numpy.unique_inverse.
- numerical.unique_all(x)#
The distinct elements of x, their first indices, each element’s index among them and their counts, as
numpy.unique_all.
- numerical.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)#
The sorted elements of both ar1 and ar2, as
numpy.intersect1d: with the indices of their first occurrences in each, where asked.
- numerical.union1d(ar1, ar2)#
The sorted elements of ar1 or ar2, as
numpy.union1d.
- numerical.setdiff1d(ar1, ar2, assume_unique=False)#
The sorted distinct elements of ar1 not in ar2, as
numpy.setdiff1d.
- numerical.setxor1d(ar1, ar2, assume_unique=False)#
The sorted elements of exactly one of ar1 and ar2, as
numpy.setxor1d.
- numerical.isin(element, test_elements, assume_unique=False, invert=False, *, kind=None)#
Whether each element of element is among test_elements (equal to one: never a NaN), as
numpy.isin: of element’s shape; invert for the opposite. kind is NumPy’s choice of method, which changes nothing in the answer.
- numerical.digitize(x, bins, right=False)#
The index of the bin of each element of x among the monotonic bins, as
numpy.digitize: throughsearchsorted()(the side swapped by right), decreasing bins reversed and their indices counted from the end; int64.
- numerical.bincount(x, /, weights=None, minlength=0)#
How often each value 0, 1, … occurs in the non-negative integers x, as
numpy.bincount: at least minlength of them (int64); or with weights (one per element, read as float64), each value’s weights summed in x’s order, as NumPy’s loop adds them. An empty x gives minlength zeros of int64, its weights unread, as NumPy’s.
- numerical.histogram(a, bins=10, range=None, density=None, weights=None)#
The histogram of a flattened, as
numpy.histogramby its steps: bins equal ones (an integer, or one of NumPy’s estimators by name: “auto”, “fd”, “doane”, “rice”, “scott”, “sqrt”, “sturges”, “stone”) over range (the data’s least to greatest by default), or between the edges bins; the counts (int64), or the sums of weights (their dtype), or a density where density; each half-open bin but the last, closed. Returns(hist, bin_edges).Examples
>>> import numerical >>> counts, edges = numerical.histogram([1.0, 2.0, 2.0, 4.0], bins=3) >>> counts.tolist(), edges.tolist() ([1, 2, 1], [1.0, 2.0, 3.0, 4.0])
- numerical.histogram_bin_edges(a, bins=10, range=None, weights=None)#
The edges of
histogram()’s bins, asnumpy.histogram_bin_edges.
- numerical.histogram2d(x, y, bins=10, range=None, density=None, weights=None)#
The two-dimensional histogram of the points (x, y), as
numpy.histogram2d:histogramdd()of the two coordinates; returns(hist, xedges, yedges).
- numerical.histogramdd(sample, bins=10, range=None, density=None, weights=None)#
The multidimensional histogram of sample (N points of D coordinates, or a sequence of D coordinate vectors), as
numpy.histogramddby its steps: per coordinate a count of equal bins over range or given edges; each bin half-open but the last; counts (or weights’ sums) in float64, or a density.
- numerical.diff(a, n=1, axis=-1, prepend=<object object>, append=<object object>)#
The n-th differences along axis,
a[1:] − a[:-1]repeated, asnumpy.diff: prepend and append joined before and after along the axis first (a number as a slice of it).
- numerical.gradient(f, *varargs, axis=None, edge_order=1)#
The gradient of f by second-order central differences inside and first- or second-order (edge_order) one-sided ones at the ends, as
numpy.gradientby its steps: one tensor per axis of axis (every one where None; the tensor alone for one axis), each spacing a number or the sample points along its axis (one for all axes, or one per axis); integers in float64.
- numerical.trapezoid(y, x=None, dx=1.0, axis=-1)#
The integral of y along axis by the trapezoidal rule, as
numpy.trapezoid: over the sample points x (a vector along the axis, or of y’s shape) or at the spacing dx;Σ d · (y₁ + y₀) / 2, by NumPy’s steps.Examples
>>> import numerical >>> numerical.trapezoid([1.0, 2.0, 3.0]) 4.0
- numerical.correlate(a, v, mode='valid')#
The cross-correlation
c[k] = Σₙ a[n + k] · conj(v[n])of two vectors, asnumpy.correlate: the lags where they overlap wholly (“valid”), the length of the longer centred as NumPy’s (“same”), or every lag (“full”). Each lag’s sum in order of v’s terms, on the threads, where NumPy’s goes through its dot product (its BLAS’s order): the last bits may differ.
- numerical.convolve(a, v, mode='full')#
The discrete linear convolution of two vectors, as
numpy.convolve:correlate()of the longer and the reversed shorter, every lag by default.
- numerical.interp(x, xp, fp, left=None, right=None, period=None)#
The piecewise-linear interpolant of the points (xp, fp) (xp increasing) at x, as
numpy.interpby its loop: left below xp[0] and right above xp[-1] (fp’s ends by default), a NaN x NaN; each line through its first point, or its second where that is NaN; with period, x and xp taken modulo it. float64, or complex128 for a complex fp.Examples
>>> import numerical >>> numerical.interp([0.5, 2.5], [0.0, 1.0, 2.0], [0.0, 10.0, 20.0]).tolist() [5.0, 20.0]
- numerical.polyval(p, x)#
The polynomial of coefficients p (highest power first) at x, as
numpy.polyval: Horner’sy · x + pᵢfrom a zero of x’s dtype, eachpᵢthe slice of p along its first axis (a coefficient, or for p of rank 2 and more one per element, broadcast against x).
- numerical.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)#
The least-squares polynomial fit of degree deg to the points (x, y), as
numpy.polyfitby its steps: the Vandermonde matrix’s columns scaled to unit norm,lstsq(), the scales undone; with full, the residues, rank, singular values and rcond too; with cov, the coefficients’ covariance (unscaled, or scaled by the residue per degree of freedom).
- numerical.polyder(p, m=1)#
The m-th derivative of the polynomial p, as
numpy.polyder.
- numerical.polyint(p, m=1, k=None)#
The m-th antiderivative of the polynomial p, its constants k (one for all, or one per order), as
numpy.polyint.
- numerical.polyadd(a1, a2)#
The sum of two polynomials, as
numpy.polyadd.
- numerical.polysub(a1, a2)#
The difference of two polynomials, as
numpy.polysub.
- numerical.polymul(a1, a2)#
The product of two polynomials, as
numpy.polymul: their coefficients’ convolution.
- numerical.polydiv(u, v)#
The quotient and remainder of two polynomials, as
numpy.polydiv: long division in floats, the remainder’s leading zeros (to 1e-14 relative) dropped.
- numerical.roots(p)#
The roots of the polynomial p, as
numpy.roots: the eigenvalues of its companion matrix (its leading and trailing zeros set apart), complex aseigvals()answers unless p is real and so are they all.
- numerical.hamming(M)#
The Hamming window of M points, as
numpy.hamming:0.54 + 0.46 cos(π n / (M − 1)).
- numerical.hanning(M)#
The Hann window of M points, as
numpy.hanning:0.5 + 0.5 cos(π n / (M − 1)).
- numerical.blackman(M)#
The Blackman window of M points, as
numpy.blackman.
- numerical.bartlett(M)#
The Bartlett (triangular) window of M points, as
numpy.bartlett.
- numerical.kaiser(M, beta)#
The Kaiser window of M points and shape beta, as
numpy.kaiser:i0(β √(1 − ((n − α)/α)²)) / i0(β).
- numerical.i0(x)#
The modified Bessel function of the first kind, order 0, of every element, as
numpy.i0by its steps (Cephes’ Chebyshev series, Clenshaw’s, below and above 8). Real dtypes, an integer in float64.
- numerical.argmax(a, axis=None, keepdims=False)#
The index of the largest element, flat (a Python int) or along axis (an int64 Tensor), as
numpy.argmax: the first of equal ones, the first NaN where there is one. Real and int64 dtypes, bool as 0 and 1.- Raises:
ValueError – if a (or the axis) is empty.
Examples
>>> import numerical >>> numerical.argmax(numerical.asarray([[1.0, 5.0], [7.0, 2.0]]), axis=1) numerical.Tensor([1, 0], dtype=int64)
- numerical.argmin(a, axis=None, keepdims=False)#
The index of the smallest element, flat or along axis, as
numpy.argmin: the first of equal ones, the first NaN where there is one.
- numerical.argsort(a, axis=-1, kind=None, stable=None, *, descending=False)#
The indices that sort a along axis (every element flattened where None), as
numpy.argsort: an int64 Tensor, ascending, NaNs last, equal elements by index whatever kind (NumPy’skind="stable"). descending, the array API’s: the reverse order, NaNs first, equal elements still by index.Examples
>>> import numerical >>> numerical.argsort(numerical.asarray([3.0, 1.0, 2.0])) numerical.Tensor([1, 2, 0], dtype=int64)
- numerical.lexsort(keys, axis=-1)#
The indices that sort by the last of keys first, ties by the one before and so on, stably, as
numpy.lexsort: keys a sequence of arrays of one shape, or the rows of an array (numbers of a 1-D one, whose order is then the number 0).
- numerical.partition(a, kth, axis=-1, kind='introselect', order=None)#
a with each line along axis partitioned at the positions kth, as
numpy.partition: the element there the one a sort puts there (NaNs last), none before it larger, none after smaller, the others in no order specified (NumPy’s own arrangement differs). By selection, linear in the extent, as NumPy’s introselect.
- numerical.argpartition(a, kth, axis=-1, kind='introselect', order=None)#
The indices that partition a along axis at kth, as
numpy.argpartition: at each position the index of the element a sort puts there, by selection; equal elements, and the others, in no order specified.
- numerical.sort_complex(a)#
The elements sorted by their real parts, then their imaginary parts, as complex numbers, as
numpy.sort_complex(complex64 for float32, complex128 for the rest).
- numerical.nonzero(a)#
The indices of the nonzero (true) elements, one int64 Tensor per axis, in C order, as
numpy.nonzero: a NaN is nonzero, as is a complex number either part of which is.- Raises:
ValueError – for a rank-0 a, as NumPy 2’s.
- numerical.tril_indices(n, k=0, m=None)#
The row and column indices of the
n × mlower triangle, to and below the k-th diagonal, asnumpy.tril_indices: int64 tensors, in row-major order.
- numerical.triu_indices(n, k=0, m=None)#
The row and column indices of the
n × mupper triangle, to and above the k-th diagonal, asnumpy.triu_indices.
- numerical.tril_indices_from(arr, k=0)#
tril_indices()of a matrix’s shape, asnumpy.tril_indices_from.
- numerical.triu_indices_from(arr, k=0)#
triu_indices()of a matrix’s shape, asnumpy.triu_indices_from.
- numerical.diag_indices(n, ndim=2)#
The indices of the main diagonal of an n-cube of ndim axes, as
numpy.diag_indices:ndimcopies of0 … n−1(int64).
- numerical.diag_indices_from(arr)#
diag_indices()of an array of equal extents, asnumpy.diag_indices_from.
- numerical.indices(dimensions, dtype=<class 'int'>, sparse=False)#
The index grids of an array of shape dimensions, as
numpy.indices: one tensor of shape(N,) + dimensions(int64 by default), or a tuple of N broadcastable ones where sparse.
- numerical.ix_(*args)#
Open meshes from 1-D sequences for cross indexing, as
numpy.ix_: each its own axis, a bool one its true positions; an empty one int64.
- numerical.ravel_multi_index(multi_index, dims, mode='raise', order='C')#
The flat indices of the coordinates multi_index in an array of shape dims, as
numpy.ravel_multi_index: row-major (order “C”) or column-major (“F”); a coordinate out of its extent refused (“raise”), wrapped (“wrap”) or clipped (“clip”), per axis with a tuple of modes. int64.
- numerical.unravel_index(indices, shape, order='C')#
The coordinates of the flat indices in an array of shape, as
numpy.unravel_index: a tuple of int64 tensors (numbers for a number), row-major (order “C”) or column-major (“F”).
- numerical.flatnonzero(a)#
The flat indices of the nonzero elements, an int64 Tensor, as
numpy.flatnonzero.
- numerical.argwhere(a)#
The indices of the nonzero elements, one row each of a’s rank, as
numpy.argwhere: an int64 Tensor of shape(N, a.ndim).
- numerical.count_nonzero(a, axis=None, *, keepdims=False)#
The number of nonzero elements, of every element (a Python int) or along axis (an int64 Tensor; a tuple of axes for several), as
numpy.count_nonzero.
- numerical.searchsorted(a, v, side='left', sorter=None)#
Where each element of v would go in the sorted vector a to keep it sorted, as
numpy.searchsorted: the first such place (side “left”) or the last (“right”), NaNs ordered last; sorter the indices that sort a (argsort()’s). A Python int for a number v, else an int64 Tensor of its shape.Examples
>>> import numerical >>> numerical.searchsorted(numerical.asarray([1.0, 2.0, 2.0, 3.0]), [2.0, 0.5], side="right") numerical.Tensor([3, 0], dtype=int64)
- numerical.trace(x, /, *, offset=0, dtype=None)#
The sum of a diagonal of a matrix or of every matrix of a stack, as
numpy.linalg.trace.The diagonal is taken over the last two axes. A bool tensor’s trace counts its trues, a float64 as
sum()’s (NumPy’s an integer).- Parameters:
x – The matrix, or a stack of them (
(..., m, n)): a Tensor or an array-like.offset – The diagonal: above the main diagonal for a positive offset, below for a negative one.
dtype – The result’s dtype, when given.
- Returns:
The trace, a number for a matrix; for a stack, a Tensor of its leading shape.
- Return type:
float | complex | Tensor
- Raises:
ValueError – if x is of rank below 2.
Examples
>>> import numerical >>> numerical.trace([[1.0, 2.0], [3.0, 4.0]]) 5.0 >>> numerical.trace([[1.0, 2.0], [3.0, 4.0]], offset=1) 2.0 >>> numerical.trace([[[1.0, 0.0], [0.0, 1.0]], [[2.0, 0.0], [0.0, 2.0]]]) numerical.Tensor([2.0, 4.0], dtype=float64)
Products#
- numerical.matmul(x1, x2, /)#
The matrix product of x1 and x2, as
numpy.matmul(andx1 @ x2).Stacks of matrices along leading axes broadcast against each other, a vector a row first and a column second, two vectors their dot product. The dtypes are promoted as NumPy promotes them; a bool operand is read as float64.
- Parameters:
x1 – The left operand, a Tensor or an array-like of rank 1 or more.
x2 – The right operand, a Tensor or an array-like of rank 1 or more.
- Returns:
The product; a number for two vectors.
- Return type:
Tensor | float | complex
- Raises:
LinAlgError – if an operand is of rank 0 or the inner dimensions differ (the message names both shapes).
TypeError – if an operand is nothing
asarray()reads.
Examples
>>> import numerical >>> numerical.matmul([[1, 2], [3, 4]], [[5, 6], [7, 8]]) numerical.Tensor([[19.0, 22.0], [43.0, 50.0]], dtype=float64) >>> numerical.matmul([1, 2], [3, 4]) 11.0 >>> numerical.matmul(numerical.zeros((3, 2, 2)), numerical.eye(2)).shape (3, 2, 2)
- numerical.matvec(x1, x2, /)#
The products of the matrices of x1 (its last two axes) by the vectors of x2 (its last), broadcast, as
numpy.matvec:(x1 @ x2[..., None])[..., 0].
- numerical.vecmat(x1, x2, /)#
The products of the vectors of x1, conjugated, by the matrices of x2, broadcast, as
numpy.vecmat:(conj(x1)[..., None, :] @ x2)[..., 0, :].
- numerical.dot(a, b)#
The dot product, as
numpy.dot.A number times an array; two vectors’ sum of products; a matrix product; for more axes the sum over a’s last axis and b’s second-to-last.
- Parameters:
a – The left operand: a Tensor or an array-like.
b – The right operand: a Tensor or an array-like.
- Returns:
The product; a number for two vectors.
- Return type:
Tensor | float | complex
- Raises:
LinAlgError – if the summed axes differ in extent.
TypeError – if an operand is nothing
asarray()reads.
Examples
>>> import numerical >>> numerical.dot([1, 2], [3, 4]) 11.0 >>> numerical.dot(2, [1, 2]) numerical.Tensor([2.0, 4.0], dtype=float64) >>> numerical.dot([[1, 2], [3, 4]], [1, 1]) numerical.Tensor([3.0, 7.0], dtype=float64)
- numerical.inner(a, b, /)#
The sum of products over the last axes of a and b, as
numpy.inner: a number times an array where one is a number.
- numerical.vdot(a, b, /)#
The sum of
conj(a) · bover both arrays flattened, asnumpy.vdot: of one float or complex dtype, by chunks among the threads (the same answer on any number of them), asdot()of two vectors sums.
- numerical.outer(a, b, out=None)#
The outer product of a and b flattened,
a[i] * b[j], asnumpy.outer.Each element is its own product, as NumPy’s
multiply.outer(a −0 kept).- Parameters:
a – The first operand, flattened: a Tensor or an array-like.
b – The second operand, flattened: a Tensor or an array-like.
out – NumPy’s; None alone (a Tensor is never written into).
- Returns:
The
a.size × b.sizematrix, in the dtype the two promote to.- Return type:
- Raises:
TypeError – if an operand is a bool Tensor or nothing
asarray()reads, or for an out.
Examples
>>> import numerical >>> numerical.outer([1, 2], [3, 4]) numerical.Tensor([[3.0, 4.0], [6.0, 8.0]], dtype=float64)
- numerical.vecdot(x1, x2, /, *, axis=-1)#
Σ conj(x1) · x2along axis, broadcast over the other axes, asnumpy.linalg.vecdot.
- numerical.tensordot(x1, x2, /, *, axes=2)#
The sum of products over axes of x1 and x2, as
numpy.linalg.tensordot: an integer N contracts the last N axes of x1 with the first N of x2, a pair of sequences the axes it names.
- numerical.einsum(subscripts, /, *operands, optimize=False)#
Einstein summation over the operands, as
numpy.einsum:"ij,jk->ik"(a matrix product),"i,i->"(a dot product),"ij->ji"(a transpose),"ii->i"(a diagonal).Without
->the output takes the labels that appear once, in alphabetical order, as NumPy’s;...stands for the axes no label names. The operands are brought to one dtype as NumPy promotes them (complex where one is, single precision only where all are); a bool array-like is read as float64, a bool Tensor refused.- Parameters:
subscripts – The labels of each operand’s axes, comma-separated, then optionally
->and the output’s: at most the 52 ASCII letters.*operands – The Tensors or array-likes (NumPy arrays, nested lists, numbers), one per comma-separated term.
optimize – NumPy’s choice of a contraction order (a bool,
"greedy","optimal"or a path fromnumpy.einsum_path): taken and not followed, as the order here is chosen by the operands’ extents whatever it says.
- Returns:
The summed product, of rank 0 for a full contraction.
- Return type:
- Raises:
LinAlgError – if the subscripts do not parse, their terms are not one per operand, an operand’s rank does not match its subscripts, or a repeated label has two extents.
TypeError – if subscripts is not a string, or an operand is a bool Tensor or nothing
asarray()reads.TypeError – for an optimize that is none of NumPy’s.
Examples
>>> import numerical >>> numerical.einsum("ij,jk->ik", [[1, 0], [0, 2]], [[1, 2], [3, 4]]) numerical.Tensor([[1.0, 2.0], [6.0, 8.0]], dtype=float64) >>> numerical.einsum("i,i->", [1, 2, 3], [1, 2, 3]) numerical.Tensor(14.0, dtype=float64) >>> numerical.einsum("ii->i", [[1, 2], [3, 4]]) numerical.Tensor([1.0, 4.0], dtype=float64)
- numerical.multi_dot(arrays, *, out=None)#
The product of two or more matrices in the cheapest order, as
numpy.linalg.multi_dot: the first may be a vector (a row), the last a vector (a column). out is not taken.
- numerical.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)#
The cross product of the 3-vectors of a along axisa and of b along axisb, broadcast over the other axes, as
numpy.cross(NumPy 2.5’s: 2-vectors refused, as they are since); the products’ vectors along axisc, axis for all three. Each component by NumPy’s operations.Examples
>>> import numerical >>> numerical.cross([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]) numerical.Tensor([0.0, 0.0, 1.0], dtype=float64)
- numerical.kron(a, b)#
The Kronecker product, as
numpy.kron: blocksa[i, j] * b(over every axis, the shorter shape led by ones).
numpy.linalg#
The names and signatures of NumPy 2’s numpy.linalg; those SciPy shares take its arguments too.
- numerical.solve(a, b, /, lower=False, overwrite_a=False, overwrite_b=False, check_finite=True, assume_a=None, transposed=False)#
The solution x of
a @ x = b, asnumpy.linalg.solve, orscipy.linalg.solvewith its arguments.Without assume_a or transposed, NumPy’s
numpy.linalg.solve: a triangular a detected and solved by substitution, else the LU factorisation; a stack of systems broadcast. With them,scipy.linalg.solve’s: assume_a names a’s structure and its solver, and SciPy’s reciprocal condition number1 / (‖a‖₁ ‖a⁻¹‖₁), the inverse’s norm estimated from the factorisation (LAPACK’sgecon,pocon,trcon,gbcon; a diagonal’s exact), under half the machine epsilon warns (LinAlgWarning: the answer may have no correct digit). a and b are never written, and a NaN or an infinity always raises.- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like.b – The right-hand side: a vector or a matrix of right-hand sides (one per column), or a stack of them.
lower – With assume_a
"sym","her"or"pos", read a from its lower triangle rather than its upper one.overwrite_a – Accepted for SciPy’s signature; ignored.
overwrite_b – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
assume_a – a’s structure, as SciPy names it:
"diagonal"(a division),"tridiagonal"and"banded"(the band LU, of the bandwidth a has),"upper triangular"and"lower triangular"(substitution),"sym","her"(the matrix read from one triangle, by default the upper one, lower the lower; a Hermitian one’s diagonal taken real; then the LU, which here outruns the symmetric indefinite factorisation),"pos"(Cholesky’s, from that triangle) or"gen"; SciPy’s long names ("general","symmetric","hermitian","positive definite") too.transposed – Solve
a.T @ x = b.
- Returns:
x, of b’s shape (broadcast over a stack), in the dtype a and b promote to.
- Return type:
- Raises:
LinAlgError – if a is singular, not positive definite for
"pos", not square, holds an infinite or NaN entry, or b does not fit it.ValueError – if assume_a names no structure.
NotImplementedError – for transposed with a complex a, as SciPy’s.
Examples
>>> import numerical >>> numerical.solve([[2.0, 0.0], [0.0, 4.0]], [2.0, 2.0]) numerical.Tensor([1.0, 0.5], dtype=float64) >>> numerical.solve([[4.0, 0.0], [0.0, 2.0]], [[4.0, 8.0], [2.0, 2.0]]) numerical.Tensor([[1.0, 2.0], [1.0, 1.0]], dtype=float64) >>> numerical.solve([[2.0, 0.0], [1.0, 4.0]], [2.0, 9.0], assume_a="lower triangular") numerical.Tensor([1.0, 2.0], dtype=float64)
- numerical.determinant(a, /, *, overwrite_a=False, check_finite=True)#
The determinant of a square matrix or a stack of them, as
numpy.linalg.detandscipy.linalg.det.From the LU factorisation with partial pivoting. A singular matrix’s determinant is 0, not an error.
- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like, real or complex.overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
The determinant, a number (complex for a complex matrix); for a stack, a Tensor of the stack’s leading shape.
- Return type:
float | complex | Tensor
- Raises:
LinAlgError – if a is not a square matrix (or a stack of them) or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.det([[2.0, 0.0], [0.0, 4.0]]) 8.0 >>> numerical.det([[1, 2], [3, 4]]) -2.0 >>> numerical.det([[[2.0, 0.0], [0.0, 4.0]], [[1.0, 0.0], [0.0, 3.0]]]) numerical.Tensor([8.0, 3.0], dtype=float64)
- numerical.det(a, /, *, overwrite_a=False, check_finite=True)#
The determinant of a square matrix or a stack of them, as
numpy.linalg.detandscipy.linalg.det.From the LU factorisation with partial pivoting. A singular matrix’s determinant is 0, not an error.
- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like, real or complex.overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
The determinant, a number (complex for a complex matrix); for a stack, a Tensor of the stack’s leading shape.
- Return type:
float | complex | Tensor
- Raises:
LinAlgError – if a is not a square matrix (or a stack of them) or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.det([[2.0, 0.0], [0.0, 4.0]]) 8.0 >>> numerical.det([[1, 2], [3, 4]]) -2.0 >>> numerical.det([[[2.0, 0.0], [0.0, 4.0]], [[1.0, 0.0], [0.0, 3.0]]]) numerical.Tensor([8.0, 3.0], dtype=float64)
- numerical.slogdet(a, /)#
The sign and the natural logarithm of the absolute value of the determinant, as
numpy.linalg.slogdet.It does not underflow or overflow where
determinant()does: the determinant issign * exp(logabsdet).- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like, real or complex.- Returns:
(sign, logabsdet). For a real matrix sign is 1.0, -1.0 or 0.0 (a singular matrix, whose logabsdet is-inf); for a complex one, a complex number of modulus 1. For a stack, two Tensors of the stack’s leading shape.- Return type:
tuple
- Raises:
LinAlgError – if a is not a square matrix (or a stack of them) or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.slogdet([[-1.0, 0.0], [0.0, 1.0]]) (-1.0, 0.0) >>> numerical.slogdet([[0.0, 0.0], [0.0, 4.0]]) (0.0, -inf)
- numerical.inverse(a, /, *, overwrite_a=False, check_finite=True)#
The inverse of a square matrix, or of each matrix of a stack, as
numpy.linalg.invandscipy.linalg.inv.- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like, real or complex.overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
The inverse, of a’s shape and dtype (float64 for integers or bools).
- Return type:
- Raises:
LinAlgError – if a is singular, not a square matrix (or a stack of them), or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.inv([[2.0, 0.0], [0.0, 4.0]]) numerical.Tensor([[0.5, 0.0], [0.0, 0.25]], dtype=float64) >>> numerical.inv([[1.0, 1.0], [0.0, 1.0]]) numerical.Tensor([[1.0, -1.0], [0.0, 1.0]], dtype=float64)
- numerical.inv(a, /, *, overwrite_a=False, check_finite=True)#
The inverse of a square matrix, or of each matrix of a stack, as
numpy.linalg.invandscipy.linalg.inv.- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like, real or complex.overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
The inverse, of a’s shape and dtype (float64 for integers or bools).
- Return type:
- Raises:
LinAlgError – if a is singular, not a square matrix (or a stack of them), or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.inv([[2.0, 0.0], [0.0, 4.0]]) numerical.Tensor([[0.5, 0.0], [0.0, 0.25]], dtype=float64) >>> numerical.inv([[1.0, 1.0], [0.0, 1.0]]) numerical.Tensor([[1.0, -1.0], [0.0, 1.0]], dtype=float64)
- numerical.lstsq(a, b, rcond=None, *, cond=None, overwrite_a=False, overwrite_b=False, check_finite=True, lapack_driver=None)#
The minimum-norm least-squares solution of
a @ x ≈ b, asnumpy.linalg.lstsq.A singular value at or under rcond times the largest counts as zero. The epsilon is the operands’ precision’s (float32’s for float32 and complex64).
scipy.linalg.lstsq’s arguments are taken; the SVD solves whichever driver is named.- Parameters:
a – The m×n matrix: a Tensor or an array-like.
b – The right-hand side: a vector of m entries, or an m×k matrix of right-hand sides.
rcond – The relative cutoff: by default (
None) machine epsilon times max(m, n), NumPy’s; a negative rcond is machine epsilon, as LAPACK’s.cond –
scipy.linalg.lstsq’s name for rcond (not both).overwrite_a – Accepted for SciPy’s signature; ignored.
overwrite_b – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored.
lapack_driver –
"gelsd","gelsy"or"gelss", as SciPy’s: the SVD here, whichever.
- Returns:
(x, residuals, rank, s): the solution (a Tensor), the residual sums of squares (a Tensor, for a tall a of full column rank, else empty), the rank (an int) and the singular values of a (a Tensor). With cond or lapack_driver (a SciPy-style call) and a vector b, the residual is a number, as SciPy’s.- Return type:
tuple
- Raises:
LinAlgError – if a is not a matrix, b does not fit it, an entry is infinite or NaN, or the tolerance is NaN.
ValueError – if both rcond and cond are given, or for another lapack_driver.
TypeError – if the tolerance is not a real number.
Examples
>>> import numerical >>> x, residuals, rank, s = numerical.lstsq([[1.0, 0.0], [0.0, 2.0], [0.0, 0.0]], [1.0, 2.0, 3.0]) >>> x numerical.Tensor([1.0, 1.0], dtype=float64) >>> residuals, rank, s (numerical.Tensor([9.0], dtype=float64), 2, numerical.Tensor([2.0, 1.0], dtype=float64))
- numerical.pinv(a, rcond=None, hermitian=False, *, rtol=None, atol=None, return_rank=False, check_finite=True)#
The Moore–Penrose pseudo-inverse, as
numpy.linalg.pinv.A singular value at or under the relative tolerance times the largest counts as zero. A negative or NaN tolerance raises, where NumPy’s result is infinite or NaN.
scipy.linalg.pinv’s atol, return_rank and check_finite are taken.- Parameters:
a – The matrix, or a stack of them (
(..., m, n)) without atol or return_rank: a Tensor or an array-like.rcond – The relative tolerance, by default machine epsilon times max(m, n).
hermitian – Take a as real symmetric or complex Hermitian, its lower triangle read: the pseudo-inverse comes from its eigendecomposition, cheaper.
rtol – NumPy 2’s name for rcond (not both).
atol –
scipy.linalg.pinv’s absolute bound: a singular value at or undermax(atol, rtol σ₁)counts as zero, rtol then 0 by default, as SciPy’s.return_rank – Return the pair
(pinv, rank), as SciPy’s.check_finite – Accepted for SciPy’s signature; ignored.
- Returns:
The pseudo-inverse, n×m (of a’s dtype, float64 for integers or bools); with return_rank,
(pinv, rank), rank an int.- Return type:
Tensor | tuple
- Raises:
LinAlgError – for a negative or NaN tolerance, an infinite or NaN entry, a non-square a with hermitian, or a stack with atol or return_rank.
ValueError – if both rcond and rtol are given.
TypeError – if a tolerance is not a real number (a bool included).
Examples
>>> import numerical >>> numerical.pinv([[2.0, 0.0], [0.0, 4.0]]) numerical.Tensor([[0.5, 0.0], [0.0, 0.25]], dtype=float64) >>> numerical.pinv([[2.0, 0.0], [0.0, 0.0]], return_rank=True) (numerical.Tensor([[0.5, 0.0], [0.0, 0.0]], dtype=float64), 1)
- numerical.matrix_rank(A, tol=None, hermitian=False, *, rtol=None)#
The numerical rank, as
numpy.linalg.matrix_rank.The number of singular values above the tolerance. A vector or a number has rank 1 unless all zero. A negative or NaN tolerance raises.
- Parameters:
A – The matrix, or a stack of them (
(..., m, n)), a vector or a number: a Tensor or an array-like.tol – The absolute tolerance; by default machine epsilon times max(m, n) times the largest singular value.
hermitian – Take A as real symmetric or complex Hermitian, its lower triangle read, its singular values the magnitudes of its eigenvalues, cheaper.
rtol – The tolerance relative to the largest singular value (not with tol).
- Returns:
The rank; for a stack, the ranks as integers nested along its leading axes (NumPy’s an integer array).
- Return type:
int | list
- Raises:
LinAlgError – for a negative or NaN tolerance, or an infinite or NaN entry.
ValueError – if both tol and rtol are given.
TypeError – if a tolerance is not a real number (a bool included).
Examples
>>> import numerical >>> numerical.matrix_rank([[1.0, 2.0], [2.0, 4.0]]) 1 >>> numerical.matrix_rank([[[1.0, 0.0], [0.0, 1.0]], [[1.0, 0.0], [0.0, 0.0]]]) [2, 1] >>> numerical.matrix_rank([0.0, 0.0]) 0
- numerical.cholesky(a, /, *, upper=False, lower=None, overwrite_a=False, check_finite=True)#
The Cholesky factor of a Hermitian positive-definite matrix, as
numpy.linalg.cholesky.The lower L with
a = L @ L.conj().T, read from the lower triangle, or the upper U witha = U.conj().T @ U, read from the upper triangle. NumPy’s default stays, the lower factor, wherescipy.linalg.cholesky’s is the upper one.- Parameters:
a – The Hermitian positive-definite matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like.upper – Return the upper factor U.
lower –
scipy.linalg.cholesky’s: the negation of upper, which it overrides.overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
The factor, of a’s shape and dtype (float64 for integers or bools), zeros in its other triangle.
- Return type:
- Raises:
LinAlgError – if a is not positive definite, not square, or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.cholesky([[4.0, 2.0], [2.0, 5.0]]) numerical.Tensor([[2.0, 0.0], [1.0, 2.0]], dtype=float64) >>> numerical.cholesky([[4.0, 2.0], [2.0, 5.0]], upper=True) numerical.Tensor([[2.0, 1.0], [0.0, 2.0]], dtype=float64)
- numerical.qr(a, mode='reduced', *, pivoting=False, overwrite_a=False, lwork=None, check_finite=True)#
The QR factorisation
a = Q @ R, asnumpy.linalg.qr.R’s diagonal is real and non-negative. With
pivoting=True, asscipy.linalg.qr(a, pivoting=True)(LAPACK’sgeqp3):a[:, P] = Q @ Rwith the column of largest remaining norm taken at each step, so that R’s diagonal does not grow down it and reveals the numerical rank; R’s diagonal is real and non-negative there too, where LAPACK’s may be negative.- Parameters:
a – The m×n matrix, or a stack of them (
(..., m, n)): a Tensor or an array-like.mode – For k = min(m, n):
"reduced"(the default) Q m×k with orthonormal columns and R k×n upper trapezoidal;"complete", Q m×m and R m×n;"r", R alone, k×n. SciPy’s names"economic"and"full"are taken as"reduced"and"complete"(NumPy’s default stays, the reduced one).pivoting – Pivot the columns, as SciPy’s.
overwrite_a – Accepted for SciPy’s signature; ignored.
lwork – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
(Q, R), or R alone for"r". With pivoting,(Q, R, P), or(R, P)for"r", P a tuple of the columns’ origins (SciPy’s an integer array).- Return type:
tuple | Tensor
- Raises:
LinAlgError – if a is not a matrix (or a stack of them) or holds an infinite or NaN entry.
ValueError – for a mode not offered (LAPACK’s reflectors,
"raw", are not).
Examples
>>> import numerical >>> q, r = numerical.qr([[1.0, 0.0], [0.0, 2.0]]) >>> q numerical.Tensor([[1.0, 0.0], [0.0, 1.0]], dtype=float64) >>> numerical.qr([[1.0, 0.0], [0.0, -2.0]], mode="r") numerical.Tensor([[1.0, 0.0], [0.0, 2.0]], dtype=float64)
- numerical.eig(a, b=None, left=False, right=True, overwrite_a=False, overwrite_b=False, check_finite=True, homogeneous_eigvals=False)#
The eigenvalues and right eigenvectors of a general square matrix or a stack of them, as
numpy.linalg.eig.a @ v[:, j] == w[j] * v[:, j], each vector of unit norm with its component of largest modulus real. Complex whatever the eigenvalues, as NumPy 2.5’s (complex64 for a single-precision matrix); in the order LAPACK’sdgeevandzgeevgive them (balancing, Hessenberg reduction, shifted QR), a real matrix’s conjugate pairs together, the positive imaginary part first.With
scipy.linalg.eig’s arguments (a matrix, not a stack): left, right, b and homogeneous_eigvals, the answerw,(w, vl),(w, vr)or(w, vl, vr)as SciPy’s. The vectors are complex always, where SciPy’s are real for a real matrix with real eigenvalues.- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)) with NumPy’s arguments alone: a Tensor or an array-like.b – The generalized problem
a @ v = w * b @ v, by the complex QZ:w = alpha / beta, ∞ where only β is 0, NaN where both are; each vector of unit 2-norm, as SciPy normalisesggev’s. A matrix of a’s shape.left – Return the left eigenvectors too (
vl[:, j].conj() @ a == w[j] * vl[:, j].conj(), asgeev’s).right – Return the right eigenvectors (the default); false for none of them.
overwrite_a – Accepted for SciPy’s signature; ignored.
overwrite_b – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
homogeneous_eigvals – Return the eigenvalues as the pairs
(alpha, beta)stacked (a(2, n)Tensor; β 1 without b).
- Returns:
(w, v)by default: w the eigenvalues, v the eigenvectors as columns, both complex. With SciPy’s arguments,w,(w, vl),(w, vr)or(w, vl, vr).- Return type:
tuple | Tensor
- Raises:
LinAlgError – if a is not square (or a stack of square matrices) or holds an infinite or NaN entry.
ValueError – if, with b, a is not a square matrix or b is not of its shape.
Examples
>>> import numerical >>> w, v = numerical.eig([[2.0, 0.0], [0.0, 1.0]]) >>> w numerical.Tensor([(2+0j), (1+0j)], dtype=complex128) >>> numerical.eig([[0.0, -1.0], [1.0, 0.0]], right=False) numerical.Tensor([1j, -1j], dtype=complex128)
- numerical.eigvals(a, b=None, overwrite_a=False, check_finite=True, homogeneous_eigvals=False)#
The eigenvalues alone of a general square matrix, or of each of a stack, as
numpy.linalg.eigvals.Complex whatever they are, as NumPy 2.5’s; the same values as
eig()’s, to the bit.- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)) without b or homogeneous_eigvals: a Tensor or an array-like.b – The generalized problem’s matrix, as
scipy.linalg.eigvals(eig()’s).overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
homogeneous_eigvals – Return the pairs
(alpha, beta)stacked, aseig()’s.
- Returns:
The eigenvalues, complex (complex64 for a single-precision matrix); for a stack, one row per matrix.
- Return type:
- Raises:
LinAlgError – if a is not square (or a stack of square matrices) or holds an infinite or NaN entry.
ValueError – if, with b, a is not a square matrix or b is not of its shape.
Examples
>>> import numerical >>> numerical.eigvals([[0.0, -1.0], [1.0, 0.0]]) numerical.Tensor([1j, -1j], dtype=complex128) >>> numerical.eigvals([[2.0, 0.0], [0.0, 3.0]], b=[[1.0, 0.0], [0.0, 0.0]]) numerical.Tensor([(2+0j), (inf+0j)], dtype=complex128)
- numerical.eigh(a, UPLO='L', *, b=None, method='divide_and_conquer', subset_by_index=None, subset_by_value=None, lower=None, eigvals_only=False, overwrite_a=False, overwrite_b=False, type=1, check_finite=True, driver=None)#
The eigenvalues and eigenvectors of a real symmetric or complex Hermitian matrix, as
numpy.linalg.eigh.The eigenvalues are real and ascending, the eigenvectors the columns of the second matrix. With b, a positive-definite matrix of a’s order, the pencil
a x = λ b x, asscipy.linalg.eigh(a, b):b = L LᴴandL⁻¹ a L⁻ᴴdiagonalised, the vectorsb-orthonormal (Xᴴ b X = I); each matrix read in the triangle UPLO names. Two matrices, not stacks; b keyword-only, UPLO holding NumPy’s place.A subset of the spectrum (subset_by_index or subset_by_value, as
scipy.linalg.eigh’s) comes from the tridiagonal form, the eigenvalues by bisection, the vectors by inverse iteration (LAPACK’sdstebzanddstein):n² koperations past the reduction forkof them, where method takesn³and more for all; a matrix (and b), not a stack. With eigvals_only or a subset, method is checked but not used.scipy.linalg.eigh’s arguments are taken too: b as the second positional argument (a matrix, where UPLO is a string), lower, eigvals_only, driver, type (2a b x = λ xand 3b a x = λ xbyb = L Lᴴand the eigenpairs ofLᴴ a L, as LAPACK’sxsygv), and overwrite_a, overwrite_b and check_finite.- Parameters:
a – The symmetric or Hermitian matrix, or a stack of them (
(..., n, n)) without b or a subset: a Tensor or an array-like. Only the triangle UPLO names is read.UPLO –
"L"(the default) reads the lower triangle,"U"the upper one, in either case. A matrix there is SciPy’s b.b – The positive-definite matrix of the pencil
a x = λ b x, of a’s order.method – How the tridiagonal form is diagonalised:
"divide_and_conquer"(LAPACK’sdsyevd/zheevd),"tridiagonal_ql"(implicit QL,dsyev’s) or"jacobi"(cyclic Jacobi rotations, real matrices only).subset_by_index –
[lo, hi]: the eigenpairs of indiceslotohi(ascending, from 0).subset_by_value –
[low, high]: the eigenpairs of the eigenvalues in(low, high].lower – SciPy’s name for the triangle: true for
UPLO="L", false for"U"; it overrides UPLO.eigvals_only – Return the eigenvalues alone.
overwrite_a – Accepted for SciPy’s signature; ignored.
overwrite_b – Accepted for SciPy’s signature; ignored.
type – SciPy’s problem type: 1 (
a x = λ b x), 2 (a b x = λ x) or 3 (b a x = λ x).check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
driver – SciPy’s driver, as a method:
"ev"and"gv"the implicit QL,"evd"and SciPy’s others divide and conquer, or the subset’s bisection where one is asked.
- Returns:
(w, v): w the eigenvalues, real, of a’s precision; v the eigenvectors as columns, of a’s dtype (float64 for integers or bools). w alone with eigvals_only.- Return type:
tuple | Tensor
- Raises:
LinAlgError – if a is not square, holds an infinite or NaN entry, b is not positive definite or not of a’s order, or
"jacobi"is asked of a complex matrix.ValueError – for a UPLO, method, driver or type not offered, both subsets, or a subset out of range.
TypeError – if a method’s name is given as the second argument, or b is given twice.
Examples
>>> import numerical >>> w, v = numerical.eigh([[2.0, 0.0], [0.0, 1.0]]) >>> w numerical.Tensor([1.0, 2.0], dtype=float64) >>> v numerical.Tensor([[0.0, 1.0], [1.0, 0.0]], dtype=float64) >>> numerical.eigh([[2.0, 0.0], [0.0, 1.0]], b=[[4.0, 0.0], [0.0, 1.0]], eigvals_only=True) numerical.Tensor([0.5, 1.0], dtype=float64)
- numerical.eigvalsh(a, UPLO='L', *, b=None, subset_by_index=None, subset_by_value=None, lower=None, overwrite_a=False, overwrite_b=False, type=1, check_finite=True, driver=None)#
The eigenvalues alone of a real symmetric or complex Hermitian matrix, as
numpy.linalg.eigvalsh.Real and ascending. With b, those of the pencil
a x = λ b x, aseigh()’s. A subset (subset_by_index or subset_by_value, aseigh()’s) by bisection on the tridiagonal form alone.scipy.linalg.eigvalsh’s arguments aseigh()takes them.- Parameters:
a – The symmetric or Hermitian matrix, or a stack of them (
(..., n, n)) without b or a subset: a Tensor or an array-like. Only the triangle UPLO names is read.UPLO –
"L"(the default) reads the lower triangle,"U"the upper one, in either case. A matrix there is SciPy’s b.b – The positive-definite matrix of the pencil
a x = λ b x, of a’s order.subset_by_index –
[lo, hi]: the eigenvalues of indiceslotohi(ascending, from 0).subset_by_value –
[low, high]: the eigenvalues in(low, high].lower – SciPy’s name for the triangle: true for
UPLO="L", false for"U"; it overrides UPLO.overwrite_a – Accepted for SciPy’s signature; ignored.
overwrite_b – Accepted for SciPy’s signature; ignored.
type – SciPy’s problem type: 1 (
a x = λ b x), 2 (a b x = λ x) or 3 (b a x = λ x).check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
driver – SciPy’s driver: checked against
eigh()’s names, it does not change the computation.
- Returns:
The eigenvalues, real, of a’s precision; for a stack, one row per matrix.
- Return type:
- Raises:
LinAlgError – if a is not square, holds an infinite or NaN entry, or b is not positive definite or not of a’s order.
ValueError – for a UPLO, driver or type not offered, both subsets, or a subset out of range.
TypeError – if a method’s name is given as the second argument, or b is given twice.
Examples
>>> import numerical >>> numerical.eigvalsh([[2.0, 7.0], [0.0, 1.0]]) numerical.Tensor([1.0, 2.0], dtype=float64) >>> numerical.eigvalsh([[2.0, 0.0], [7.0, 1.0]], "U") numerical.Tensor([1.0, 2.0], dtype=float64)
- numerical.svd(a, full_matrices=True, compute_uv=True, hermitian=False, *, method='divide_and_conquer', overwrite_a=False, check_finite=True, lapack_driver=None)#
The singular value decomposition
a = U @ diag(S) @ Vh, asnumpy.linalg.svd.The singular values descending.
hermitian=Truedecomposes a through its eigendecomposition, cheaper: the singular values the magnitudes of the eigenvalues,Vh = (U * sign(w)).conj().T, as NumPy’s.- Parameters:
a – The m×n matrix, or a stack of them (
(..., m, n)): a Tensor or an array-like.full_matrices – U m×m and Vh n×n (true, NumPy’s default: the columns past min(m, n) an orthonormal basis of the complement), or m×k and k×n, k = min(m, n) (false).
compute_uv – Return the factors; false for the singular values alone.
hermitian – Take a as real symmetric or complex Hermitian (its lower triangle read).
method – How the bidiagonal form is decomposed:
"divide_and_conquer"(LAPACK’sdgesdd),"bidiagonal_qr"(implicit-shift QR,dgesvd’s) or"jacobi"(one-sided Jacobi, each singular value to high relative accuracy).overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
lapack_driver –
scipy.linalg.svd’s:"gesdd"(divide and conquer) or"gesvd"(bidiagonal QR); it replaces method.
- Returns:
(U, S, Vh): S real, of a’s precision, U and Vh of a’s dtype (float64 for integers or bools). S alone withcompute_uv=False.- Return type:
tuple | Tensor
- Raises:
LinAlgError – if a is not a matrix (or a stack of them) or holds an infinite or NaN entry.
ValueError – for a method or lapack_driver not offered.
TypeError – if a method’s name is given as the second argument.
Examples
>>> import numerical >>> u, s, vh = numerical.svd([[3.0, 0.0], [0.0, 4.0]]) >>> s numerical.Tensor([4.0, 3.0], dtype=float64) >>> u numerical.Tensor([[0.0, 1.0], [1.0, 0.0]], dtype=float64) >>> numerical.svd([[1.0, 0.0, 0.0], [0.0, 2.0, 0.0]], full_matrices=False)[2].shape (2, 3)
- numerical.svdvals(x, /)#
The singular values of a matrix or of every matrix of a stack, descending, as
numpy.linalg.svdvals.- Parameters:
x – The matrix, or a stack of them (
(..., m, n)): a Tensor or an array-like.- Returns:
The singular values, real, of x’s precision; for a stack, one row per matrix.
- Return type:
- Raises:
LinAlgError – if x is not a matrix (or a stack of them) or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.svdvals([[3.0, 0.0], [0.0, -4.0]]) numerical.Tensor([4.0, 3.0], dtype=float64)
- numerical.norm(x, ord=None, axis=None, keepdims=False)#
A vector or a matrix norm, as
numpy.linalg.norm.With no axis, the 2-norm of every element for no ord, else the ord norm of the vector or the matrix x is; with an integer axis, the vector norms along it; with a pair, the matrix norms over it (
vector_norm(),matrix_norm()).- Parameters:
x – The Tensor or array-like.
ord – The order:
vector_norm()’s for a vector,matrix_norm()’s for a matrix (Nonethe 2-norm, the Frobenius norm for a matrix).axis –
None, an integer (vector norms) or a pair of integers (matrix norms); negative ones count from the end.keepdims – Keep each reduced axis with extent 1.
- Returns:
The norm, real, of x’s precision: a number for a whole reduction, else a Tensor.
- Return type:
float | Tensor
- Raises:
ValueError – for an ord with no axis on a rank other than 1 or 2, an ord not offered, an axis out of range, repeated, or of more than two axes.
LinAlgError – if a singular value norm (2, -2,
"nuc") meets an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.norm([3.0, 4.0]) 5.0 >>> numerical.norm([[1.0, 2.0], [3.0, 4.0]], 1) 6.0 >>> numerical.norm([[3.0, 4.0], [0.0, 0.0]], axis=1) numerical.Tensor([5.0, 0.0], dtype=float64)
- numerical.vector_norm(x, /, *, axis=None, keepdims=False, ord=2)#
The ord norm of x over axis, as
numpy.linalg.vector_norm.Summed at the scale of the largest magnitude, it does not overflow where NumPy’s 2-norm of entries past 1e154 is infinite.
- Parameters:
x – The Tensor or array-like.
axis –
None(every element), an integer or a tuple of them; negative ones count from the end.keepdims – Keep each reduced axis with extent 1.
ord – The order, a real number:
(Σ abs(x)^ord)^(1/ord);infthe largest magnitude,-infthe smallest, 0 how many are not zero.
- Returns:
The norm, real, of x’s precision: a number for a whole reduction, else a Tensor.
- Return type:
float | Tensor
- Raises:
ValueError – for an ord that is not a real number, an axis out of range or repeated, or
ord=-infover no element.
Examples
>>> import numerical >>> numerical.vector_norm([3.0, 4.0]) 5.0 >>> numerical.vector_norm([3.0, -4.0], ord=1) 7.0 >>> numerical.vector_norm([[3.0, 4.0], [0.0, 0.0]], axis=1) numerical.Tensor([5.0, 0.0], dtype=float64)
- numerical.matrix_norm(x, /, *, keepdims=False, ord='fro')#
The ord norm of a matrix or of every matrix of a stack (its last two axes), as
numpy.linalg.matrix_norm:"fro"(Frobenius, without overflow),"nuc"(the sum of the singular values), 2 and -2 (the largest and the smallest singular value), 1 and -1 (the largest and smallest column sum of magnitudes),infand-inf(row sums).
- numerical.cond(x, p=None)#
The condition number of a matrix or of every matrix of a stack in the p norm, as
numpy.linalg.cond.- Parameters:
x – The matrix, or a stack of them (
(..., m, n)): a Tensor or an array-like.p – The norm:
None, 2 and -2 the ratio of the extreme singular values (infinite for a singular matrix), elsenorm(x, p) * norm(inv(x), p)(infinite where x is singular), p one ofmatrix_norm()’s orders for a square matrix.
- Returns:
The condition number; for a stack, a Tensor of its leading shape.
- Return type:
float | Tensor
- Raises:
LinAlgError – if x is not a matrix or a stack of them, is empty, is not square for a p other than
None, 2 and -2, or holds an infinite or NaN entry for those three.ValueError – for a p not offered.
Examples
>>> import numerical >>> numerical.cond([[2.0, 0.0], [0.0, 4.0]]) 2.0 >>> numerical.cond([[1.0, 0.0], [0.0, 0.0]]) inf >>> numerical.cond([[2.0, 0.0], [0.0, 4.0]], 1) 2.0
- numerical.matrix_power(a, n)#
a to the integer power n by repeated squaring, as
numpy.linalg.matrix_power.- Parameters:
a – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like.n – The power, an integer: the identity for 0, the inverse’s powers for a negative n.
- Returns:
ato the power n, of a’s shape and dtype (float64 for integers).- Return type:
- Raises:
LinAlgError – if a is not square (or a stack of square matrices), or singular for a negative n.
TypeError – if n is not an integer, or a is a bool Tensor.
Examples
>>> import numerical >>> numerical.matrix_power([[1.0, 1.0], [0.0, 1.0]], 3) numerical.Tensor([[1.0, 3.0], [0.0, 1.0]], dtype=float64) >>> numerical.matrix_power([[2.0, 0.0], [0.0, 4.0]], -1) numerical.Tensor([[0.5, 0.0], [0.0, 0.25]], dtype=float64)
- numerical.tensorsolve(a, b, axes=None)#
x with
tensordot(a, x, axes=x.ndim) == b, asnumpy.linalg.tensorsolve: a’s leading axes those of b, its others x’s, their products equal (axes, when given, are moved to the end of a first).
- numerical.tensorinv(a, ind=2)#
The inverse of a read as a matrix of its first ind axes by the others, as
numpy.linalg.tensorinv:tensordot(tensorinv(a, ind), a, ind)is the identity of a’s trailing axes.
scipy.linalg: solvers and factors#
- numerical.solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False, overwrite_b=False, check_finite=True)#
The solution x of
a @ x = bfor a triangular a, asscipy.linalg.solve_triangular.The triangle lower names is read and the other never.
n² koperations wheresolve()factorises a first.- Parameters:
a – The triangular square matrix: a Tensor or an array-like.
b – The right-hand side: a vector or a matrix of right-hand sides.
trans – 0 (
'N') solvesa @ x = b, 1 ('T')a.T @ x = b, 2 ('C')a.conj().T @ x = b.lower – Read the lower triangle; by default the upper one.
unit_diagonal – Take the diagonal as ones (it is not read).
overwrite_b – Accepted for SciPy’s signature; ignored (a Tensor is never written through).
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
x, of b’s shape.
- Return type:
- Raises:
LinAlgError – if a diagonal entry read is zero (“singular matrix: resolution failed at diagonal i”, 1-based, as SciPy’s), an entry read is infinite or NaN, or the shapes do not fit.
ValueError – for another trans.
Examples
>>> import numerical >>> numerical.solve_triangular([[2.0, 1.0], [0.0, 4.0]], [4.0, 8.0]) numerical.Tensor([1.0, 2.0], dtype=float64) >>> numerical.solve_triangular([[2.0, 0.0], [1.0, 4.0]], [2.0, 9.0], lower=True) numerical.Tensor([1.0, 2.0], dtype=float64) >>> numerical.solve_triangular([[1.0, 0.0], [1.0, 1.0]], [1.0, 2.0], lower=True, unit_diagonal=True) numerical.Tensor([1.0, 1.0], dtype=float64)
- numerical.solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False, check_finite=True)#
The solution x of
a x = bfor a banded a of l subdiagonals and u superdiagonals, asscipy.linalg.solve_banded: ab its diagonal-ordered form,(l + u + 1, n),ab[u + i - j, j] = a[i, j](its corners not read); b a vector or a matrix of right-hand sides. The LU factorisation with partial pivoting in LAPACK’s band storage (gbsv),O(n l (l + u))operations; forl = u = 1,gtsv, as SciPy. overwrite_ab, overwrite_b and check_finite are accepted and not needed: an infinite or NaN entry raises always.- Raises:
ValueError – if ab has not
l + u + 1rows or b not as many rows as ab has columns.LinAlgError – if a is singular or an entry is infinite or NaN.
- numerical.solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False, check_finite=True)#
The solution x of
a x = bfor a Hermitian positive-definite banded a, asscipy.linalg.solveh_banded: ab its upper diagonal-ordered form,(u + 1, n),ab[u + i - j, j] = a[i, j]fori <= j, or with lower its lower one,ab[i - j, j] = a[i, j]fori >= j(the diagonal’s imaginary part and the corners not read). The band’s Cholesky factor (LAPACK’spbsv); for one off-diagonal,L D Lᴴ(ptsv), as SciPy. overwrite_ab, overwrite_b and check_finite are accepted and not needed.- Raises:
ValueError – if b has not as many rows as ab has columns.
LinAlgError – if a is not positive definite or an entry is infinite or NaN.
- numerical.solve_toeplitz(c_or_cr, b, check_finite=True)#
The solution x of
T x = bfor a Toeplitz T, asscipy.linalg.solve_toeplitz: c_or_cr its first column c, or the pair(c, r)of its first column and first row (r[0]not read;r = c.conj()by default, a Hermitian T); b a vector or a matrix of right-hand sides. Levinson’s recursion,O(n²)a column where a dense solve takesn³ / 3: every leading principal minor must be nonsingular, and it may lose accuracy unless T is well-conditioned and symmetric positive definite, as SciPy’s. check_finite is accepted and not needed.- Raises:
ValueError – if c and r differ in length or b has not as many rows.
LinAlgError – if a leading principal minor is singular or an entry is infinite or NaN.
- numerical.matmul_toeplitz(c_or_cr, x, check_finite=False, workers=None)#
T @ xfor the Toeplitz matrix T of first column c and first row r (r = conj(c)by default; T oflen(c)rows andlen(r)columns), asscipy.linalg.matmul_toeplitzand by its steps: the product by the circulant matrix that embeds T, through the FFT,O((m + n) log(m + n))a column where a product takesm n. In float64 or complex128; x a vector or a matrix. check_finite and workers are SciPy’s and change nothing here.- Raises:
ValueError – if x has not as many rows as T has columns, or more than two axes (SciPy’s batches are not taken).
Examples
>>> import numerical >>> numerical.matmul_toeplitz(([1.0, 2.0, 3.0], [1.0, 4.0]), [1.0, 1.0]) numerical.Tensor([5.0, 3.0, 5.0], dtype=float64)
- numerical.solve_circulant(c, b, singular='raise', tol=None, caxis=-1, baxis=0, outaxis=0)#
The solution x of
C x = bfor the circulant C of first column c, asscipy.linalg.solve_circulant: the Fourier transform diagonalises it,x = ifft(fft(b) / fft(c)),O(n log n)a column. An eigenvaluefft(c)of modulus at most tol (by defaultn eps max |fft(c)|) makes C near singular:singular="raise"refuses it,"lstsq"leaves those terms out (the minimum-norm least-squares solution). Real c and b give a real x. c a vector and b a vector or a matrix of right-hand sides by rows (SciPy’s default axes alone).- Raises:
ValueError – for another singular, axes or shapes.
LinAlgError – if C is near singular under
"raise", or an entry is infinite or NaN.
- numerical.lu(a, permute_l=False, overwrite_a=False, check_finite=True, p_indices=False)#
The pivoted LU factorisation
a = P @ L @ Uof an m × n matrix, asscipy.linalg.lu.A singular matrix factorises (a zero pivot leaves its column of L zero).
- Parameters:
a – The m × n matrix: a Tensor or an array-like.
permute_l – Return the pair
(P @ L, U).overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
p_indices – Return the rows themselves in place of P (
a == L[P] @ U, an int list where SciPy’s is an array).
- Returns:
(P, L, U): P the m × m permutation matrix (real, of a’s precision), L m × k lower trapezoidal with a unit diagonal, U k × n upper trapezoidal,k = min(m, n).(P @ L, U)with permute_l.- Return type:
tuple
- Raises:
LinAlgError – if a is not a matrix or holds an infinite or NaN entry.
Examples
>>> import numerical >>> p, l, u = numerical.lu([[0.0, 1.0], [2.0, 0.0]]) >>> p numerical.Tensor([[0.0, 1.0], [1.0, 0.0]], dtype=float64) >>> u numerical.Tensor([[2.0, 0.0], [0.0, 1.0]], dtype=float64) >>> numerical.lu([[0.0, 1.0], [2.0, 0.0]], p_indices=True)[0] [1, 0]
- numerical.lu_factor(a, overwrite_a=False, check_finite=True)#
The pivoted LU factorisation
P a = L Uof a square matrix, asscipy.linalg.lu_factor.To solve many systems with one factorisation (
lu_solve()). A singular matrix factorises, a zero on U’s diagonal, as SciPy’s (which warns).- Parameters:
a – The square matrix: a Tensor or an array-like.
overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
The pair
(lu, piv): L (unit diagonal not stored) and U in one matrix, and LAPACK’s row interchanges (a tuple of ints, where SciPy’s is an integer array).- Return type:
- Raises:
LinAlgError – if a is not square or holds an infinite or NaN entry.
Examples
>>> import numerical >>> lu, piv = numerical.lu_factor([[0.0, 1.0], [2.0, 0.0]]) >>> lu numerical.Tensor([[2.0, 0.0], [0.0, 1.0]], dtype=float64) >>> piv (1, 1)
- numerical.lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True)#
The solution of a system from
lu_factor()’s factorisation, asscipy.linalg.lu_solve.n² koperations. A zero on U’s diagonal raises, where SciPy’s divides by it.- Parameters:
lu_and_piv –
lu_factor()’s(lu, piv), or any such pair.b – The right-hand side: a vector or a matrix of right-hand sides.
trans – 0 (
'N') solvesa @ x = b, 1 ('T')a.T @ x = b, 2 ('C')a.conj().T @ x = b.overwrite_b – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
x, of b’s shape, in the dtype lu and b promote to.
- Return type:
- Raises:
LinAlgError – for a zero on U’s diagonal, an infinite or NaN entry, or shapes that do not fit.
ValueError – for another trans.
Examples
>>> import numerical >>> factor = numerical.lu_factor([[0.0, 1.0], [2.0, 0.0]]) >>> numerical.lu_solve(factor, [1.0, 4.0]) numerical.Tensor([2.0, 1.0], dtype=float64) >>> numerical.lu_solve(numerical.lu_factor([[1.0, 2.0], [0.0, 4.0]]), [1.0, 4.0], trans=1) numerical.Tensor([1.0, 0.5], dtype=float64)
- class numerical.LUFactor(lu, piv)#
lu_factor()’s answer: the pair(lu, piv)SciPy’slu_factorreturns, unpacked the same way, and the factorisation itself:f.solve(b)islu_solve(f, b).- property lu#
L (its unit diagonal not stored) and U in one matrix.
- property piv#
row
iswapped with rowpiv[i], in turn from the first.- Type:
LAPACK’s row interchanges
- solve(b, trans=0)#
lu_solve()with this factorisation.
- numerical.cho_factor(a, lower=False, overwrite_a=False, check_finite=True)#
The Cholesky factorisation of a Hermitian positive-definite matrix, as
scipy.linalg.cho_factor.For
cho_solve(). The other triangle of the factor is zeros, where SciPy’s leaves whatever a held there.- Parameters:
a – The Hermitian positive-definite matrix: a Tensor or an array-like.
lower – Return the lower factor L (
a = L Lᴴ) read from a’s lower triangle; by default the upper U (a = Uᴴ U) read from its upper one.overwrite_a – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
The pair
(c, lower): c the factor, lower a bool.- Return type:
- Raises:
LinAlgError – if a is not positive definite, not square, or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.cho_factor([[4.0, 2.0], [2.0, 5.0]]) (numerical.Tensor([[2.0, 1.0], [0.0, 2.0]], dtype=float64), False)
- numerical.cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True)#
The solution of
a @ x = bfromcho_factor()’s factorisation, asscipy.linalg.cho_solve.Two triangular solves (
solve_triangular()’s bits),2 n² koperations; only c’s triangle is read, checked once with b, and an overflow between the two solves is the result’s.- Parameters:
c_and_lower –
cho_factor()’s(c, lower), or any such pair.b – The right-hand side: a vector or a matrix of right-hand sides.
overwrite_b – Accepted for SciPy’s signature; ignored.
check_finite – Accepted for SciPy’s signature; ignored (an infinite or NaN entry always raises).
- Returns:
x, of b’s shape.
- Return type:
- Raises:
LinAlgError – for a zero on c’s diagonal, an infinite or NaN entry, or shapes that do not fit.
Examples
>>> import numerical >>> factor = numerical.cho_factor([[4.0, 2.0], [2.0, 5.0]]) >>> numerical.cho_solve(factor, [6.0, 12.0]) numerical.Tensor([0.375, 2.25], dtype=float64)
- class numerical.CholeskyFactor(c, lower)#
cho_factor()’s answer: the pair(c, lower)SciPy’scho_factorreturns, unpacked the same way, and the factorisation itself:f.solve(b)ischo_solve(f, b).- property c#
L in the lower triangle where
lower, else U in the upper one, zeros elsewhere.- Type:
The factor
- solve(b)#
cho_solve()with this factorisation.
- numerical.cholesky_banded(ab, overwrite_ab=False, lower=False, check_finite=True)#
The Cholesky factor of the Hermitian positive-definite band ab, in its own form, as
scipy.linalg.cholesky_banded(LAPACK’spbtrf):U(A = Uᴴ U) of the upper form,L(A = L Lᴴ) of the lower one; the corners outside the band as ab has them.- Raises:
LinAlgError – if A is not positive definite or an entry is infinite or NaN.
- numerical.cho_solve_banded(cb_and_lower, b, overwrite_b=False, check_finite=True)#
The solution x of
A x = bfromcholesky_banded()’s(cb, lower), asscipy.linalg.cho_solve_banded(LAPACK’spbtrs).- Raises:
ValueError – if b has not as many rows as cb has columns.
LinAlgError – if an entry is infinite or NaN.
- numerical.ldl(A, lower=True, hermitian=True, overwrite_a=False, check_finite=True)#
The symmetric indefinite factorisation of a symmetric or Hermitian matrix, as
scipy.linalg.ldl:A = lu @ d @ lu.conj().T(lu.Twhere hermitian is false, a complex symmetric A), Bunch and Kaufman’s diagonal pivoting (LAPACK’ssytrfandhetrf, by panels from order 384) on the lower triangle, or on the upper withlower=False; only that triangle is read. Returns(lu, d, perm): d block diagonal with blocks of order 1 and 2,lu[perm]triangular with a unit diagonal, perm a tuple (SciPy’s an integer array). A Hermitian matrix’s diagonal imaginary parts are ignored with aComplexWarning, as SciPy’s. overwrite_a and check_finite are accepted and not needed.- Raises:
LinAlgError – if A is not square or holds an infinite or NaN entry.
scipy.linalg: decompositions#
- numerical.schur(a, output='real', lwork=None, overwrite_a=False, sort=None, check_finite=True)#
The Schur decomposition
a = Z @ T @ Z.conj().Tof a square matrix, asscipy.linalg.schur: Z orthogonal (unitary), T upper quasi-triangular for a real matrix (a complex pair a 2 × 2 block, its diagonal equal), upper triangular withoutput="complex"("c") or for a complex matrix. Returns(T, Z). Not balanced, as LAPACK’sdgees.With sort, the eigenvalues it selects are moved to the leading block of T and
(T, Z, sdim)returned, sdim their count:"lhp"(real part below 0),"rhp"(at or above 0),"iuc"(modulus at most 1),"ouc"(above 1), or a callable, given the real and imaginary parts of each eigenvalue for a real T and the eigenvalue for a complex one; a complex pair moves, and counts twice, where either of its two is selected. lwork, overwrite_a and check_finite are accepted and not needed.- Raises:
LinAlgError – if a is not square, holds an infinite or NaN entry, two blocks cannot be exchanged, or the exchanges’ rounding leaves a selected eigenvalue after one not selected (real).
ValueError – for another output or sort.
- numerical.rsf2csf(T, Z, check_finite=True)#
The complex Schur form
(T, Z)of the real one, asscipy.linalg.rsf2csf: each 2 × 2 block of T (a conjugate pair) triangularised by a unitary rotation of its rows and columns, Z’s columns turning with it; a subdiagonal entry withinepsof its diagonal neighbours’ magnitudes is taken as 0.- Raises:
ValueError – if T and Z are not square matrices of one shape, or an entry is infinite or NaN.
- numerical.qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False, overwrite_b=False, check_finite=True)#
The generalized Schur decomposition of the pencil
(A, B),A = Q AA ZᴴandB = Q BB Zᴴ, asscipy.linalg.qz(LAPACK’sxgges): Q and Z orthogonal (unitary), BB upper triangular with a non-negative diagonal, AA quasi-triangular for a real pencil (a 2 × 2 block for each conjugate pair of eigenvalues, BB diagonal there) and triangular withoutput="complex"or for a complex one. The operands are first scaled into range asxggesscales them. Returns(AA, BB, Q, Z). lwork, overwrite_a, overwrite_b and check_finite are accepted and not needed.- Raises:
ValueError – if sort is given (as SciPy, which leaves it to
ordqz()) or output is another.LinAlgError – if A and B are not square and of one order, an entry is infinite or NaN, or the iterations do not converge.
- numerical.ordqz(A, B, sort='lhp', output='real', overwrite_a=False, overwrite_b=False, check_finite=True)#
The generalized Schur decomposition of
qz()with the eigenvalues sort selects moved to the leading block, asscipy.linalg.ordqz(LAPACK’sxggesthenxtgsen):"lhp"(real part of α / β below 0),"rhp"(above 0),"iuc"(modulus below 1),"ouc"(above 1, an infinite one included), or a callable given the arrays alpha and beta and returning one truth per eigenvalue; a conjugate pair moved whole where either of its two is selected. Returns(AA, BB, alpha, beta, Q, Z), the eigenvaluesalpha / beta(alpha complex, beta real for a real pencil’s real form).- Raises:
ValueError – for another sort or output; LinAlgError (a ValueError) if two blocks cannot be exchanged, or as
qz().
- numerical.hessenberg(a, calc_q=False, overwrite_a=False, check_finite=True)#
The upper Hessenberg form H of the square a,
A = Q H Qᴴ, and with calc_q the unitary Q, asscipy.linalg.hessenberg(Householder reflections, LAPACK’sgehrd, no balancing); a matrix of order 2 or less is its own, Q the float64 identity, as SciPy’s. overwrite_a and check_finite are accepted and not needed: an infinite or NaN entry raises always.- Raises:
ValueError – if a is not square or holds an infinite or NaN entry.
- numerical.rq(a, overwrite_a=False, lwork=None, mode='full', check_finite=True)#
The RQ factorisation
A = R Qof the M × N a, R upper trapezoidal (its triangle at the right) and Q unitary, asscipy.linalg.rq(LAPACK’sgerqf): from the QR factorisation of(J A)ᴴ, J the reversal,R = J R₁ᴴ JandQ = J Q₁ᴴ.mode="r"gives R alone,"economic"RM × Kand QK × N,K = min(M, N).- Raises:
ValueError – if mode is not one of these, a is not a matrix or holds an infinite or NaN entry.
- numerical.polar(a, side='right')#
The polar decomposition of a matrix, as
scipy.linalg.polar:(u, p)witha = u p(side="right") ora = p u("left"), u with orthonormal columns (rows, for a wide a), p Hermitian positive semidefinite: from the singular value decompositiona = W Σ Vᴴ(full_matrices=False),u = W Vᴴandp = V Σ Vᴴ(right) orW Σ Wᴴ(left), as SciPy computes them.- Raises:
ValueError – if a is not a matrix or side is neither
"right"nor"left".LinAlgError – if a holds an infinite or NaN entry.
- numerical.cdf2rdf(w, v)#
The real block-diagonal eigenvalues and real eigenvectors of a real matrix from its complex ones w and v (
A v = v diag(w), conjugate pairs adjacent), asscipy.linalg.cdf2rdf:A vr = vr wr, each pair a 2 × 2 block[[re, im], [-im, re]]; over a stack’s leading axes.- Raises:
ValueError – if the shapes do not match or a complex eigenvalue is not in a conjugate pair.
- numerical.matrix_balance(A, permute=True, scale=True, separate=False, overwrite_a=False)#
The square A balanced,
B = T⁻¹ A TwithT = P Da permutation (permute) times powers of two (scale), and T, asscipy.linalg.matrix_balance(LAPACK’sgebal): every entry of B an entry of A scaled exactly. With separate,(scaling, permutation)in place of T, the permutation a list of integers.- Raises:
ValueError – if A is not square or holds an infinite or NaN entry.
- numerical.eigh_tridiagonal(d, e, eigvals_only=False, select='a', select_range=None, check_finite=True, tol=0.0, lapack_driver='auto')#
The eigenvalues, ascending, and with them the orthonormal eigenvectors (columns) of the real symmetric tridiagonal matrix of diagonal d and off-diagonal e, as
scipy.linalg.eigh_tridiagonal: every one by divide and conquer (LAPACK’sstevd, SciPy’s default), or those in the half-open interval(vl, vu]ofselect="v", or those of the indicesil … iuofselect="i", by bisection (stebz, or the whole spectrum’s QL iteration where they are many) and their vectors by inverse iteration (stein). tol and the drivers are accepted (the answer is the same whichever is named, within each driver’s rules); check_finite too: an infinite or NaN entry raises always.- Raises:
ValueError – if d and e are not vectors of lengths n and n − 1, select or select_range is invalid, a driver is named outside its rules, or an entry is infinite or NaN.
TypeError – if d or e is complex.
- numerical.eigvalsh_tridiagonal(d, e, select='a', select_range=None, check_finite=True, tol=0.0, lapack_driver='auto')#
The eigenvalues alone of the real symmetric tridiagonal matrix of diagonal d and off-diagonal e, ascending, as
scipy.linalg.eigvalsh_tridiagonal(eigh_tridiagonal()witheigvals_only=True).
- numerical.eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False, select='a', select_range=None, max_ev=0, check_finite=True)#
The eigenvalues (ascending) and eigenvectors of the real symmetric or complex Hermitian band matrix whose upper diagonal-ordered form is a_band,
(u + 1, n),a_band[u + i - j, j] = a[i, j]fori <= j(with lower its lower form,a_band[i - j, j] = a[i, j]fori >= j), asscipy.linalg.eig_banded: all of them (select “a”), those in(min, max](“v”) or of indicesmintomax(“i”) of select_range. A real tridiagonal band (u = 1) througheigh_tridiagonal(); the eigenvalues alone of a narrow one through its own reduction to real tridiagonal form by plane rotations (LAPACK’ssbtrdandhbtrd:n² uoperations, where the dense matrix takesn³); the rest througheigh()of the matrix it describes. max_ev, overwrite_a_band and check_finite are SciPy’s and change nothing here.- Raises:
ValueError – if a_band is not a matrix, select or select_range is invalid, or an entry is infinite or NaN.
- numerical.eigvals_banded(a_band, lower=False, overwrite_a_band=False, select='a', select_range=None, check_finite=True)#
The eigenvalues alone of a symmetric or Hermitian band matrix, as
scipy.linalg.eigvals_banded(eig_banded()witheigvals_only=True).
scipy.linalg: matrix functions#
- numerical.expm(A)#
The matrix exponential
e^A, asscipy.linalg.expm.Scaling and squaring of a Padé approximant of degree 3 to 13, as Al-Mohy and Higham’s algorithm (2009) that SciPy follows: the same values to rounding, not to the bit. An infinite or NaN entry raises, where SciPy returns NaNs.
- Parameters:
A – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like; integers and booleans asfloat64.- Returns:
e^A, of A’s shape and dtype.- Return type:
- Raises:
LinAlgError – if A is not square (or a stack of square matrices) or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.expm([[0.0, 0.0], [0.0, 0.0]]) numerical.Tensor([[1.0, 0.0], [0.0, 1.0]], dtype=float64) >>> numerical.expm([[0.0, 1.0], [0.0, 0.0]]) numerical.Tensor([[1.0, 1.0], [0.0, 1.0]], dtype=float64)
- numerical.expm_multiply(A, B, start=None, stop=None, num=None, endpoint=None, traceA=None)#
e^{tA} Bwithout forminge^{tA}, asscipy.sparse.linalg.expm_multiply: att = 1, or at each of the timesnumpy.linspace(start, stop, num, endpoint)gives (start,stop,numandendpointaslinspacetakes them, at least two times), stacked along a first axis. Al-Mohy and Higham’s algorithm 3.2 (2011), as SciPy’s: A less its trace over n, then s steps of at most m terms of the Taylor series, each a product of A by B’s block, m and s the fewest products for double’s unit roundoff; the times after the first each a stephfrom the one before, as SciPy’s (its algorithm 5.2), except where the error the steps carry, grown at most‖e^{hA}‖₁times by each (estimated once, asonenormest), would pass2⁻⁴⁰of the action: that time is computed from B again and the steps go on from it. Where A is far from normal or the time negative, the steps alone lose digits by orders (SciPy’s: 7·10⁻¹⁰ where each time from B is right to 10⁻¹⁵). A dense; traceA is accepted (the trace is exact here).- Raises:
LinAlgError – if A is not square, B not a vector or matrix of its rows, or an entry is infinite or NaN.
ValueError – for fewer than two times.
- numerical.expm_frechet(A, E, method=None, compute_expm=True, check_finite=True)#
The Fréchet derivative of the matrix exponential at A along E, as
scipy.linalg.expm_frechet:(expm(A), L), or L alone where compute_expm is false.method=Noneor"SPS"is Al-Mohy and Higham’s algorithm 6.4 (2009) as SciPy’s: the Padé approximant of degree 3, 5, 7 or 9 where‖A‖₁is within its bound, else of degree 13 on2⁻ˢ A, then s squarings of the pair;"blockEnlarge"the exponential of the block matrix[[A, E], [0, A]], whose blocks areexpm(A)and L. Matrices only (SciPy’s batches are not taken); check_finite is accepted and not needed.- Raises:
LinAlgError – if A or E is not square, their shapes differ, or an entry is infinite or NaN.
ValueError – for another method.
- numerical.expm_cond(A, check_finite=True)#
The relative condition number of the matrix exponential in the Frobenius norm, as
scipy.linalg.expm_cond:‖K‖₂ ‖A‖_F / ‖expm(A)‖_F, K then² × n²Kronecker form of the Fréchet derivative (oneexpm_frechet()a column). Matrices only; check_finite is accepted and not needed.- Raises:
LinAlgError – if A is not square or holds an infinite or NaN entry.
- numerical.logm(A)#
The principal matrix logarithm, as
scipy.linalg.logm.An upper triangular A directly, else its Schur form (a real matrix’s real form made complex) and
Z log(T) Zᴴ,log Tby Al-Mohy and Higham’s inverse scaling and squaring (2012); the norms that choose the square roots and the Padé degree are exact where SciPy estimates them (onenormest). Warns as SciPy does:LogmExactlySingularWarningwhere an eigenvalue is 0 (taken as 1e-20),LogmNearlySingularWarningwhere one is below 1e-20, and aRuntimeWarningwhere‖expm(F) − A‖₁ / ‖A‖₁is not below 1000 ε.- Parameters:
A – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like.- Returns:
The logarithm, real where A is and the imaginary parts are negligible, else complex; a stack’s matrices each (complex for all where any is).
- Return type:
- Raises:
LinAlgError – if A is not square (or a stack of square matrices) or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.logm([[1.0, 1.0], [0.0, 1.0]]) numerical.Tensor([[0.0, 1.0], [0.0, 0.0]], dtype=float64)
- numerical.sqrtm(A)#
The principal square root X of a square matrix, as
scipy.linalg.sqrtm.X @ X = A, its eigenvalues of nonnegative real part. By the Schur method, in real arithmetic for a real matrix (Higham, 1987), whose root is real unless it has a real eigenvalue below 0, then complex (for a whole stack); where there is no square root (a zero eigenvalue in a Jordan block), the entries that would need one infinite, as SciPy’s. SciPy’s deprecated disp and blocksize are not taken.- Parameters:
A – The square matrix, or a stack of them (
(..., n, n)): a Tensor or an array-like; integers and booleans asfloat64.- Returns:
X, of A’s shape: real or complex as above.
- Return type:
- Raises:
LinAlgError – if A is not square (or a stack of square matrices) or holds an infinite or NaN entry.
Examples
>>> import numerical >>> numerical.sqrtm([[4.0, 0.0], [0.0, 9.0]]) numerical.Tensor([[2.0, 0.0], [0.0, 3.0]], dtype=float64) >>> numerical.sqrtm([[-4.0, 0.0], [0.0, 9.0]]) numerical.Tensor([[2j, 0j], [0j, (3+0j)]], dtype=complex128)
- numerical.fractional_matrix_power(A, t)#
A to the real power t, as
scipy.linalg.fractional_matrix_power: a whole t by repeated squaring; elseA^a A^b, a the floor or the ceiling of t as A’s condition chooses it,A^b(|b| < 1) by Higham and Lin’s Schur–Padé algorithm (2013) on the Schur form, the diagonal and superdiagonal written exactly after each squaring (SciPy writes them before the first only). Where A is singular, a positive t falls back tofunm(), as SciPy’s; a negative one raises (SciPy answers a matrix of NaN). Real where A is and every imaginary part is 0, else complex.- Raises:
LinAlgError – if A is not square, holds an infinite or NaN entry, or is singular for a negative t.
ValueError – if t is infinite or NaN.
- numerical.funm(A, func, disp=True)#
A function of a square matrix, as
scipy.linalg.funm.The Schur form
A = Z T Zᴴ(a real matrix’s real form made complex), func called with T’s diagonal, then Parlett’s recurrence for the rest off(T)andZ f(T) Zᴴ. Where eigenvalues gather (within 0.1 of the largest modulus, or of 1), Davies and Higham’s Schur–Parlett algorithm: the Schur form reordered by clusters, each cluster’s block by Cauchy’s integral on a circle about it (func is then called again with those circles’ points, more of them where an integral’s own estimate asks: it must be analytic on their disks), the rest by the block recurrence; where no circle can keep the other clusters out, or the estimate stays past1e3 eps, the clusters within 0.01 instead. A Hermitian A:V f(Λ) Vᴴfrom its eigendecomposition.- Parameters:
A – The square matrix: a Tensor or an array-like.
func – The scalar function, called with an array of points (a NumPy array where NumPy is installed, else a
Tensor); it returns one value per point.disp – With true (the default) a likely inaccurate result (an estimate past
1000 eps) is reported on standard output, as SciPy’s; with false the estimate is returned with the result.
- Returns:
f(A), real where A is and the imaginary parts are negligible, single precision for a single-precision A. Withdisp=False,(F, err), err the estimate of‖error‖₁ / ‖A‖₁: the recurrence run again on its own roundings and the integrals’ errors, never below SciPy’s (which far from normality can say 10⁻¹³ of an error of 10⁻²).- Return type:
Tensor | tuple
- Raises:
LinAlgError – if A is not a square matrix or holds an infinite or NaN entry, or func does not return one value per point.
Examples
>>> import numerical >>> numerical.funm([[1.0, 0.0], [0.0, 4.0]], lambda x: x * x) numerical.Tensor([[1.0, 0.0], [0.0, 16.0]], dtype=float64)
- numerical.cosm(A)#
The matrix cosine, as
scipy.linalg.cosm: the real part ofexpm(iA)for a real A.
- numerical.sinm(A)#
The matrix sine, as
scipy.linalg.sinm: the imaginary part ofexpm(iA)for a real A.
- numerical.tanm(A)#
The matrix tangent,
cosm(A)⁻¹ sinm(A), asscipy.linalg.tanm: the exponentialscosm()andsinm()take, computed once for both.
- numerical.coshm(A)#
The matrix hyperbolic cosine,
(expm(A) + expm(-A)) / 2, asscipy.linalg.coshm.
- numerical.sinhm(A)#
The matrix hyperbolic sine,
(expm(A) − expm(-A)) / 2, asscipy.linalg.sinhm; where‖A‖₁ ≤ 1its series, which does not cancel.
- numerical.tanhm(A)#
The matrix hyperbolic tangent,
coshm(A)⁻¹ sinhm(A), asscipy.linalg.tanhm: the exponentialscoshm()andsinhm()take, computed once for both. An A Hermitian to rounding (each entry within8 n ε max|A|of its conjugate transpose’s) takesV tanh(Λ) Vᴴfromeigh()of its Hermitian part instead: the quotient of exponentials lost all past norm 40 or so (a positive definite matrix of norm 76, relative error 3.6, SciPy’s 21), where tanh of each eigenvalue is exact. Any other finite A past‖A‖₁ = 1takesfunm()of tanh: the quotient’s error grows as the exponentials’ conditioning, far from normality (V D V⁻¹,Din [−30, 30], V unit triangular with entries to ±7: SciPy’s and the quotient’s relative errors of 5 and over), where the Schur–Parlett algorithm holds 10⁻¹¹, eigenvalues near tanh’s polesiπ(k + ½)included. Below norm 1 the quotient, of a series for the sine, is the more exact.
- numerical.signm(A, disp=True)#
The matrix sign function, as
scipy.linalg.signm: Newton’s iterationS ← (μ S + (μ S)⁻¹) / 2with determinantal scaling, 12 to 20 steps of one inverse each; where it does not converge in 30 (an eigenvalue on or near the imaginary axis), SciPy’s algorithm:funm()of the sign of each eigenvalue’s real part (0 within1e3 epsof the largest), then, where its error estimate passes1e3 eps, the unscaled iteration from A shifted by half the reciprocal of its largest singular value. Withdisp=Falsethe error estimate beside the answer:‖P² − P‖₁of the projectorP = (S² + S) / 2, as SciPy’s, which grows as‖S‖²with the sign’s conditioning; only the fallback reports an inaccurate answer on standard output, as SciPy’s does.
scipy.linalg: matrix equations#
- numerical.solve_sylvester(a, b, q)#
The solution X of the Sylvester equation
A X + X B = Q, asscipy.linalg.solve_sylvester: Bartels and Stewart’s method, the Schur forms of a and b and the triangular equation between them solved by blocks (LAPACK’strsyl); complex where an operand is. Where a and-bshare an eigenvalue there is no unique solution, and the answer grows as LAPACK’s does.- Raises:
LinAlgError – if a or b is not square, q is not
a.shape[0] × b.shape[0], or an entry is infinite or NaN.
- numerical.solve_continuous_lyapunov(a, q)#
The solution X of
A X + X Aᴴ = Q, asscipy.linalg.solve_continuous_lyapunov: one Schur formA = U R Uᴴ, which givesAᴴ = U Rᴴ Uᴴtoo, thenR Y + Y Rᴴ = Uᴴ Q Uby blocks (LAPACK’strsyl) andX = U Y Uᴴ; complex where an operand is.- Raises:
LinAlgError – if a is not square, q not of its shape, or an entry is infinite or NaN.
- numerical.solve_lyapunov(a, q)#
The solution X of
A X + X Aᴴ = Q, asscipy.linalg.solve_continuous_lyapunov: one Schur formA = U R Uᴴ, which givesAᴴ = U Rᴴ Uᴴtoo, thenR Y + Y Rᴴ = Uᴴ Q Uby blocks (LAPACK’strsyl) andX = U Y Uᴴ; complex where an operand is.- Raises:
LinAlgError – if a is not square, q not of its shape, or an entry is infinite or NaN.
- numerical.solve_discrete_lyapunov(a, q, method=None)#
The solution X of
A X Aᴴ − X + Q = 0, asscipy.linalg.solve_discrete_lyapunov:method="direct"(by default below order 10, as SciPy’s) solves the Kronecker system(I − A ⊗ conj(A)) vec(X) = vec(Q),"bilinear"(from order 10) the continuous equation the bilinear transformation gives,Bᴴ X + X B = −CforB = (Aᴴ − I)(Aᴴ + I)⁻¹andC = 2 (A + I)⁻¹ Q (Aᴴ + I)⁻¹, from one LU factorisation ofA + I.- Raises:
LinAlgError – if a is not square or q not of its shape, an entry is infinite or NaN, or
I − A ⊗ conj(A)(direct) orA + I(bilinear) is singular.ValueError – for another method.
- numerical.solve_continuous_are(a, b, q, r, e=None, s=None, balanced=True)#
The stabilising solution X of the continuous algebraic Riccati equation
Aᴴ X E + Eᴴ X A − (Eᴴ X B + S) R⁻¹ (Bᴴ X E + Sᴴ) + Q = 0(E = IandS = 0when e and s are None), asscipy.linalg.solve_continuous_are: the extended Hamiltonian pencil, balanced unless balanced is false, its stable deflating subspace from the generalized Schur form sorted with the left half-plane first, R never inverted. Complex where an operand is. With e, the balancing scales e as it scales the pencil (SciPy 1.18 does not, and answers a wrong X or raises there when the balancing is not trivial: scipy/scipy#26555).- Raises:
LinAlgError – if a shape is not
am×m,bm×n,qm×m,rn×n,em×m,sm×n (m, n ≥ 1), an entry is infinite or NaN, q or r is not Hermitian, e is numerically singular, there is no finite solution, or the pencil has eigenvalues too close to the imaginary axis.
- numerical.solve_discrete_are(a, b, q, r, e=None, s=None, balanced=True)#
The stabilising solution X of the discrete algebraic Riccati equation
Aᴴ X A − Eᴴ X E − (Aᴴ X B + S) (R + Bᴴ X B)⁻¹ (Bᴴ X A + Sᴴ) + Q = 0(E = IandS = 0when e and s are None), asscipy.linalg.solve_discrete_are: the extended symplectic pencil, balanced unless balanced is false, its stable deflating subspace from the generalized Schur form sorted with the inside of the unit circle first, nothing inverted. Complex where an operand is; with e, the balancing scales it assolve_continuous_are()’s. A pencil with eigenvalues on the unit circle is refused also where SciPy, in real arithmetic withm = 1, answers.- Raises:
LinAlgError – as
solve_continuous_are()’s, the eigenvalues too close to the unit circle.
scipy.linalg: special matrices#
- numerical.toeplitz(c, r=None)#
The Toeplitz matrix of first column c and first row r, as
scipy.linalg.toeplitz:T[i, j] = c[i - j]fori >= j,r[j - i]above (r[0]not read);r = conj(c)by default, a Hermitian matrix. Integers and booleans asfloat64.
- numerical.hankel(c, r=None)#
The Hankel matrix of first column c and last row r, as
scipy.linalg.hankel:H[i, j] = c[i + j]whilei + j < len(c),r[i + j - len(c) + 1]past it (r[0]not read); r zeros by default.
- numerical.circulant(c)#
The circulant matrix of first column c, as
scipy.linalg.circulant:C[i, j] = c[(i - j) % n].
- numerical.block_diag(*arrs)#
The block diagonal matrix of arrs, in order, as
scipy.linalg.block_diag: each a matrix (a vector one row, a number one entry), zeros off the blocks, one dtype as NumPy promotes them; none gives a1 × 0matrix.
- numerical.hilbert(n)#
The n × n Hilbert matrix,
H[i, j] = 1 / (i + j + 1), asscipy.linalg.hilbert.
- numerical.invhilbert(n, exact=False)#
The inverse of the n × n Hilbert matrix, as
scipy.linalg.invhilbert: its integer entries computed exactly and each rounded once to float64 (SciPy rounds the binomials it multiplies where exact is false, and gives integers where it is true; float64 holds them exactly up to 2**53, about n = 14).
- numerical.pascal(n, kind='symmetric', exact=True)#
The n × n Pascal matrix, as
scipy.linalg.pascal: binomial coefficients,lowerC(i, j),upperits transpose,symmetricC(i + j, i); float64, each entry exact and rounded once (exact integers up to 2**53).
- numerical.invpascal(n, kind='symmetric', exact=True)#
The inverse of the n × n Pascal matrix, as
scipy.linalg.invpascal: float64, each entry exact and rounded once.
- numerical.hadamard(n, dtype='float64')#
The n × n Hadamard matrix of Sylvester’s construction (n a power of 2), as
scipy.linalg.hadamard: its ±1 entries in dtype (float64 by default, where SciPy’s is an integer).
- numerical.helmert(n, full=False)#
The n × n Helmert matrix, or its last n - 1 rows unless full, as
scipy.linalg.helmert.
- numerical.leslie(f, s)#
The Leslie matrix of fecundities f and survival rates s (one fewer), as
scipy.linalg.leslie: f its first row, s its subdiagonal.
- numerical.companion(a)#
The companion matrix of the polynomial of coefficients a (highest degree first), as
scipy.linalg.companion:-a[1:] / a[0]its first row, ones on its subdiagonal.
- numerical.fiedler(a)#
The symmetric Fiedler matrix of a,
F[i, j] = |a[i] - a[j]|, asscipy.linalg.fiedler(along the last axis of a stack).
- numerical.fiedler_companion(a)#
The Fiedler companion matrix of the polynomial of coefficients a (highest degree first), as
scipy.linalg.fiedler_companion: pentadiagonal, its eigenvalues the polynomial’s roots.
- numerical.convolution_matrix(a, n, mode='full')#
The Toeplitz matrix whose product with a vector of length n is its convolution with a, as
scipy.linalg.convolution_matrix:full(len(a) + n - 1rows),same(max(n, len(a))) orvalid(max(n, len(a)) - min(n, len(a)) + 1).
- numerical.dft(n, scale=None)#
The n × n discrete Fourier transform matrix,
exp(-2πi jk / n), asscipy.linalg.dft: divided bysqrt(n)(scale="sqrtn") or n ("n").
- numerical.khatri_rao(a, b)#
The column-wise Kronecker product of a (m × k) and b (p × k),
(m p) × k, asscipy.linalg.khatri_rao.
- numerical.diagsvd(s, M, N)#
The M × N matrix of the singular values s on its diagonal, as
scipy.linalg.diagsvd(s of length M or N).
scipy.linalg: subspaces and tests#
- numerical.null_space(A, rcond=None, *, overwrite_a=False, check_finite=True, lapack_driver='gesdd')#
An orthonormal basis of the null space of A (its columns), as
scipy.linalg.null_space: the right singular vectors of the singular values at most rcond times the largest (eps max(M, N)by default).
- numerical.orth(A, rcond=None)#
An orthonormal basis of the range of A (its columns), as
scipy.linalg.orth: the left singular vectors of the singular values above rcond times the largest (eps max(M, N)by default).
- numerical.subspace_angles(A, B)#
The principal angles between the column spaces of A and B, largest first, as
scipy.linalg.subspace_angles(Knyazev and Argentati’s algorithm, the sines for the small angles).
- numerical.orthogonal_procrustes(A, B, check_finite=True)#
The unitary R nearest to mapping A onto B (minimising
‖A R − B‖_F) and the sum of the singular values ofAᴴ B, asscipy.linalg.orthogonal_procrustes.
- numerical.pinvh(a, atol=None, rtol=None, lower=True, return_rank=False, check_finite=True)#
The pseudo-inverse of the Hermitian matrix a from its eigendecomposition, as
scipy.linalg.pinvh: the eigenvalues aboveatol + rtol max|λ|inverted (rtolmax(M, N) epsby default), with the rank where return_rank.
- numerical.bandwidth(a)#
The lower and upper bandwidths of the matrix a (the farthest diagonals below and above the main one holding a nonzero entry, 0 where none), as
scipy.linalg.bandwidth.
- numerical.issymmetric(a, atol=None, rtol=None)#
Whether the square matrix a equals its transpose: exactly, or within
atol + rtol |aᵀ|where a tolerance is given, asscipy.linalg.issymmetric.
- numerical.ishermitian(a, atol=None, rtol=None)#
Whether the square matrix a equals its conjugate transpose: exactly, or within
atol + rtol |aᴴ|where a tolerance is given, asscipy.linalg.ishermitian.
Errors and warnings#
- exception numerical.error#
- exception numerical.LinAlgError(*args, **kwargs)#
Raised by the linear-algebra functions when they cannot compute their answer: a singular matrix, one not positive definite, an infinite or NaN entry, an iteration that did not converge, or an operand of the wrong shape. As
numpy.linalg.LinAlgErrorit is aValueError; it is also anumerical.error, so code catching that keeps working. Where NumPy is loaded, it is also anumpy.linalg.LinAlgError(and so SciPy’s, the same class): code written for them catches it as theirs, without NumericAL importing NumPy.
- exception numerical.AxisError(*args, **kwargs)#
Raised for an axis out of a tensor’s range, as
numpy.exceptions.AxisError: aValueErrorand anIndexErroras NumPy’s, and anumerical.error. Where NumPy is loaded, it is also anumpy.exceptions.AxisError, without NumericAL importing NumPy.
- exception numerical.LinAlgWarning#
The warning
scipy.linalg.LinAlgWarningnames: an ill-conditioned operation whose answer may be inaccurate. Where SciPy’s linalg is loaded, the warning issued is also ascipy.linalg.LinAlgWarning, so a filter set on SciPy’s class takes it.
- exception numerical.LogmRankWarning#
A warning of
logm()about a singular or nearly singular matrix, as SciPy’s.
Threads, kernels and memory#
- numerical.set_num_threads(n)#
Cap the threads a kernel uses at n, the caller’s included;
0lifts the cap. At1no thread is started. For a process per core, say, so that together they do not ask for more threads than the machine has, asOMP_NUM_THREADScaps BLAS.
- numerical.get_num_threads() int#
The threads a kernel may use.
- numerical.gemm_path()#
The kernel float64 matrix products run on:
"portable"(the compiler’s vectors),"neon"(arm64’s vectors, each multiply-add fused),"avx2","avx512"(x86-64, chosen at run time from cpuid) or"amx"(Apple M1 to M4, an undocumented coprocessor, used only on a known chip that passes a self-test, the products it does not suit on NEON; see numerical/amx.hpp).
- numerical.limit_gemm_path(most)#
Keep float64 matrix products on most or a more portable path (one of
gemm_path()’s names): the most capable path at or below it that runs on this processor."amx"restores the best;"portable"keeps products on the compiler’s own vectors. Paths below the cap are not probed (under"avx512"or below, the Apple AMX’s self-test never runs). Returns the path now in use.
- numerical.release_memory()#
Free the workspaces NumericAL keeps between calls: the calling thread’s and the thread pool’s, then the blocks kept for reuse (as oneMKL’s mkl_free_buffers). Another thread’s stay, its own to free.
- numerical.get_include()#
Return the directory to add to a C++ include path for NumericAL’s headers.
#include <numerical/numerical.hpp>resolves against this directory. NumericAL is header-only and shipped inside the installed package, so a project can compile against it located through its Python install. NumericAL is a leaf library — it needs no other include paths.- Returns:
Absolute path to NumericAL’s include directory.
- Return type:
str
- numerical.get_config()#
Return metadata for embedding the C++ library.
- Returns:
version(str),include(str, seeget_include()),cxx_standard(str),gemm_path(str, the kernel float64 matrix products run on, seegemm_path()) andthreads(int).- Return type:
dict
- numerical.blas_library()#
Return the path of the numerical_blas shared library, or
Nonewhere the package carries none.The library exports 39 BLAS and LAPACK routines under their Fortran names and calling convention:
?gemm_,?gesv_,?getrf_,?getrs_,?potrf_and?potrs_in every precision (s,d,c,z),sdot_,ddot_,cdotu_,cdotc_,zdotu_andzdotc_, anddsyrk_,dgemv_,dtrsm_,dsyevd_,dgesdd_,dgeqrf_,dorgqr_,dgelsd_anddgeev_in double precision; each with 32-bit integers (LP64), and again under its name ending in64_with 64-bit ones (ILP64, as OpenBLAS’s64_build), which Julia’s libblastrampoline takes:BLAS.lbt_forward(path; clear=false, suffix_hint="64_") Preloaded ahead of the system's BLAS and LAPACK, it answers those calls and leaves the others to them:: LD_PRELOAD=$(python -c "import numerical; print(numerical.blas_library())") python script.py
A program reaches it only through a BLAS it calls by those names: a NumPy or SciPy installed by the system’s package manager or switched by FlexiBLAS, not the wheels from PyPI, whose OpenBLAS is renamed inside them. Importing
numericalnever loads it. It is built for Linux alone; elsewhere this returnsNone. Experimental: its routines are checked by NumPy’s and SciPy’s linear algebra suites, and more may join.- Returns:
Absolute path to
libnumerical_blas.so, orNone.- Return type:
str | None
numerical.linalg#
numpy.linalg’s names, each the function of that name at the root (the same object), but for cross and
outer, which take numpy.linalg’s operands alone: 3-vectors, and vectors.
- numerical.linalg.cross(x1, x2, /, *, axis=-1)#
The cross product of 3-vectors along axis, broadcast over the other axes, as
numpy.linalg.cross(NumPy 2.5’s):numerical.cross()along one axis for both operands and the result.
- numerical.linalg.outer(x1, x2, /)#
The outer product of two vectors,
x1[i] * x2[j], asnumpy.linalg.outer:numerical.outer()of vectors alone.
numerical.fft#
numpy.fft’s names, and scipy.fft’s discrete cosine and sine transforms.
- numerical.fft.fft(a, n=None, axis=-1, norm=None, out=None)#
The discrete Fourier transform of a along axis, as
numpy.fft.fft(): n points, the axis cut or padded with zeros to them; scaled as norm says (none by default).
- numerical.fft.ifft(a, n=None, axis=-1, norm=None, out=None)#
The inverse discrete Fourier transform of a along axis, as
numpy.fft.ifft()(scaled by 1/n by default).
- numerical.fft.fft2(a, s=None, axes=(-2, -1), norm=None, out=None)#
The two-dimensional discrete Fourier transform of a, as
numpy.fft.fft2().
- numerical.fft.ifft2(a, s=None, axes=(-2, -1), norm=None, out=None)#
The two-dimensional inverse discrete Fourier transform of a, as
numpy.fft.ifft2().
- numerical.fft.fftn(a, s=None, axes=None, norm=None, out=None)#
The n-dimensional discrete Fourier transform of a, as
numpy.fft.fftn().
- numerical.fft.ifftn(a, s=None, axes=None, norm=None, out=None)#
The n-dimensional inverse discrete Fourier transform of a, as
numpy.fft.ifftn().
- numerical.fft.rfft(a, n=None, axis=-1, norm=None, out=None)#
The discrete Fourier transform of real a along axis, its
n // 2 + 1non-negative frequencies, asnumpy.fft.rfft().
- numerical.fft.irfft(a, n=None, axis=-1, norm=None, out=None)#
The inverse of
rfft(), n real points (2 * (m - 1)by default), asnumpy.fft.irfft().
- numerical.fft.rfft2(a, s=None, axes=(-2, -1), norm=None, out=None)#
The two-dimensional transform of real a, as
numpy.fft.rfft2().
- numerical.fft.irfft2(a, s=None, axes=(-2, -1), norm=None, out=None)#
The inverse of
rfft2(), asnumpy.fft.irfft2().
- numerical.fft.rfftn(a, s=None, axes=None, norm=None, out=None)#
The n-dimensional transform of real a, as
numpy.fft.rfftn():rfft()along the last axis, thenfft()along the others, the last first.
- numerical.fft.irfftn(a, s=None, axes=None, norm=None, out=None)#
The inverse of
rfftn(), asnumpy.fft.irfftn():ifft()along each axis but the last, in order, thenirfft()along the last.
- numerical.fft.hfft(a, n=None, axis=-1, norm=None, out=None)#
The transform of a signal of Hermitian symmetry, n real points, as
numpy.fft.hfft().
- numerical.fft.ihfft(a, n=None, axis=-1, norm=None, out=None)#
The inverse of
hfft(), asnumpy.fft.ihfft().
- numerical.fft.fftfreq(n, d=1.0, device=None, *, dtype=None)#
The sample frequencies of a transform of n points, d apart, as
numpy.fft.fftfreq(): 0, 1, …, ⌈n/2⌉ − 1, then −⌊n/2⌋, …, −1, each times 1/(n·d); in dtype where given (the array API’s), float64 else.
- numerical.fft.rfftfreq(n, d=1.0, device=None, *, dtype=None)#
The sample frequencies of a real transform of n points, d apart, as
numpy.fft.rfftfreq(): 0, 1, …, ⌊n/2⌋, each times 1/(n·d); in dtype where given (the array API’s), float64 else.
- numerical.fft.fftshift(x, axes=None)#
x with its zero frequency moved to the middle, as
numpy.fft.fftshift().
- numerical.fft.ifftshift(x, axes=None)#
The inverse of
fftshift(), asnumpy.fft.ifftshift().
- numerical.fft.dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, orthogonalize=None)#
The discrete cosine transform of x along axis, as
scipy.fft.dct(): type 1, 2 (the default), 3 or 4, each by a real or complex Fourier transform; n points (the axis cut or padded with zeros); norm"backward"(none),"ortho"or"forward"; orthogonalize the first (and type 1’s last) point and value weighted by √2, by default where norm is"ortho". A complex x its real and imaginary parts each. overwrite_x and workers are accepted and not needed: x is never written, and the threads are the library’s.
- numerical.fft.idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, orthogonalize=None)#
The inverse of
dct()of the same type, asscipy.fft.idct(): types 2 and 3 each other’s inverse, 1 and 4 their own, scaled by1/2n(1/2(n - 1), type 1) by default.
- numerical.fft.dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, workers=None, orthogonalize=None)#
dct()along each of axes (every axis by default), s their points, asscipy.fft.dctn().
- numerical.fft.idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, workers=None, orthogonalize=None)#
idct()along each of axes, asscipy.fft.idctn().
- numerical.fft.dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, orthogonalize=None)#
The discrete sine transform of x along axis, as
scipy.fft.dst()(seedct()): orthogonalize the last point (type 3) or value (type 2) weighted by √2.
- numerical.fft.idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, orthogonalize=None)#
The inverse of
dst()of the same type, asscipy.fft.idst()(1/2(n + 1)for type 1).
- numerical.fft.dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, workers=None, orthogonalize=None)#
dst()along each of axes, asscipy.fft.dstn().
- numerical.fft.idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, workers=None, orthogonalize=None)#
idst()along each of axes, asscipy.fft.idstn().
- numerical.fft.next_fast_len(target, real=False)#
The smallest length at least target whose prime factors are 2, 3, 5, 7 and 11 (2, 3 and 5 for a real transform), as
scipy.fft.next_fast_len: the lengths SciPy’s transforms take fastest, to pad an input to; 0 for 0. NumericAL’s own transforms run in O(n log n) at any length.