Class np.linalg
- Namespace
- NumSharp
- Assembly
- NumSharp.dll
NumPy's numpy.linalg module.
[ModuleName("np.linalg")]
public static class np.linalg
- Inheritance
-
np.linalg
- Inherited Members
Remarks
Most of this module needs a matrix backend and raises OpenBlasMissingBackendException without one. NumSharp.Core is 100 % managed C# and carries no LU, QR, SVD or eigensolver, so — unlike the matrix products, which always have a managed kernel to fall back on — a factorisation has nothing to compute with until something assigns Blas. The validation in front of the throw is NumPy-exact, so shape, rank and argument errors are the real ones. An EMPTY operand (an empty matrix or a zero-size batch) is the exception: NumPy's answer for it needs no arithmetic (shapes, zeros, and the identity that a full SVD or a complete QR of an empty matrix carries), so every factorisation gives it without a backend (NumSharp.Backends.LinAlgEmpty).
What works today, because it composes out of primitives NumSharp already has:
multi_dot(NDArray[], NDArray), matrix_power(NDArray, int) at a NON-NEGATIVE exponent, the
Array-API forms matmul(NDArray, NDArray)/outer(NDArray, NDArray)/tensordot(NDArray, NDArray, int)/
trace(NDArray, int, DType)/diagonal(NDArray, int)/cross(NDArray, NDArray, int)/
matrix_transpose(NDArray)/vecdot(NDArray, NDArray, int), and every
norm(NDArray, object, int?, bool) order except the three that are defined through singular values
(matrix ord 2, -2 and 'nuc').
The Array-API forms are NOT aliases of their main-namespace twins — NumPy gives
them different signatures and different defaults, and the differences are observable:
np.linalg.trace reduces the LAST two axes where np.trace reduces the
first two, np.linalg.outer demands 1-D operands where np.outer flattens
anything, and np.linalg.cross requires 3-vectors where np.cross still
accepts 2-vectors. Each is implemented against its own contract.
The bodies are the Linalg sub-engine (LinalgEngine, by default
DefaultLinalgEngine in Backends/Default/LinearAlgebra/DefaultLinalgEngine*.cs): NumPy's
_linalg.py statements (the argument checks, the dtype rule, the text refusals) around kernels that
stand for NumPy's _umath_linalg gufuncs. A facade here keeps its signature, its documentation (it is
woven for a numpy.matrix or numpy.char.chararray operand), a null check of the operand and one call,
a.TensorEngine.Linalg.X(...), so an engine assigned to Linalg computes every
function of this module.
Methods
cholesky(NDArray, bool)
Cholesky decomposition of a Hermitian positive-definite matrix.
public static NDArray cholesky(NDArray a, bool upper = false)
Parameters
aNDArrayThe Hermitian positive-definite matrix, or a stack of them.
upperboolFalse (the default) returns the LOWER-triangular factor
Lwitha = L L*; true returns the upper-triangularUwitha = U* U.
Returns
- NDArray
The triangular factor, a fresh array (float64 for bool / integer operands).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.cholesky.html
Only the lower triangle of a is read, so a non-Hermitian
operand is interpreted as its own reflection rather than rejected. A matrix that
is not positive definite raises
LinAlgError("Matrix is not positive definite") from the factorisation.
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- LinAlgError
Fewer than two axes, a non-square operand, or a matrix that is not positive definite.
- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.
cond(NDArray, object)
Condition number of a matrix in the given norm.
public static NDArray cond(NDArray x, object p = null)
Parameters
xNDArrayThe matrix, or a stack of them.
pobjectThe order:
null(default) and±2use singular values;±1,±infand"fro"are defined asnorm(x, p) * norm(inv(x), p), and"nuc"as the product of the sums of the singular values of x and of its inverse.
Returns
- NDArray
The condition number, real: a 0-d array for one matrix (NumPy's scalar), one per matrix of a stack; inf for a singular matrix, and since NumPy 2.5 NaN for a matrix holding a NaN (inf for one holding only infinities), each matrix of a stack on its own.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.cond.html
Every order needs a factorisation: the singular-value ones (null, ±2) and "nuc" the SVD, which needs
a matrix backend for a non-empty operand; ±1, ±inf and "fro" the inverse, which the managed LU
computes without one. As in NumPy the inverse runs in float64 (complex128 for a complex operand) whatever
the result dtype, and a singular matrix's inverse is NaN rather than an error, so its condition number is
inf, inside a stack too. NumPy 2.5 reads the singular values the same way (_cond_svdvals, gh-32591):
a non-finite matrix, or one the SVD does not converge on, gives NaN values where np.linalg.svd raises, and
NumPy's tail turns a NaN condition number into inf unless the matrix itself held a NaN.
Exceptions
- OpenBlasMissingBackendException
An SVD-based order (null, ±2,
"nuc") over a non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).- TypeError
An array or list
p: NumPy'sp in {2, -2}hashes it (unhashable type: 'numpy.ndarray'/'list'), after the empty-operand check; a float16, decimal or char operand.- LinAlgError
An empty operand, fewer than two axes, or a non-square operand for an inverse-based order (
"nuc"of a singular matrix is inf since NumPy 2.5, where NumPy 2.4 raisedSVD did not convergefor its NaN inverse).- ValueError
An order the norm refuses.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
xis null.
cross(NDArray, NDArray, int)
Cross product of 3-element vectors.
public static NDArray cross(NDArray x1, NDArray x2, int axis = -1)
Parameters
x1NDArrayThe first operand.
x2NDArrayThe second operand.
axisintThe axis holding the three components. Defaults to the last.
Returns
- NDArray
The cross product, the component axis at
axisof the broadcast result. Anumpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.cross.html
Stricter than cross(NDArray, NDArray, int, int, int, int?): the Array-API form accepts 3-vectors
ONLY, over a single axis, where the main-namespace
cross(NDArray, NDArray, int, int, int, int?) also takes the 2-vector form (deprecated in NumPy 2.0) and a
separate axisa/axisb/axisc per operand. Past the length check it IS
cross(NDArray, NDArray, int, int, int, int?) (NumPy's _core_cross(x1, x2, axis=axis)): the dtypes promote
strongly (promote_types), and the result is a view of a fresh C-ordered array whose
component axis is moved to axis.
Exceptions
- IndexError
axisis out of range for either operand ("tuple index out of range": NumPy indexesx1.shape[axis]before anything else).- ValueError
The component axis of either operand does not have length 3, or the other axes do not broadcast.
- TypeError
Either operand holds text (the multiply has no string loop).
- ArgumentNullException
x1is null.
det(NDArray)
Determinant of a matrix, or of each matrix in a stack.
public static NDArray det(NDArray a)
Parameters
aNDArrayThe square matrix, or a stack of them.
Returns
- NDArray
The determinant: a 0-d array for one matrix, one value per matrix of a stack.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.det.html
Computed from an LU factorisation (getrf), not by expansion — so for a
large or ill-conditioned matrix the product of the pivots can overflow or
underflow where slogdet(NDArray) stays finite.
No matrix backend is needed: without one, NumSharp's managed LU computes it (allclose to NumPy's LAPACK result, bit for bit for small matrices); an installed backend is used first.
Exceptions
- LinAlgError
Fewer than two axes, or a non-square operand.
- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.
diagonal(NDArray, int)
Diagonals of the LAST TWO axes.
public static NDArray diagonal(NDArray x, int offset = 0)
Parameters
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.diagonal.html
As with trace(NDArray, int, DType), the axes differ from diagonal(NDArray, int, int, int)'s
first-two default: a (2,3,3) stack gives (2,3) here and
(3,2) there.
eig(NDArray)
Eigenvalues and right eigenvectors of a general (not necessarily symmetric) matrix.
public static (NDArray eigenvalues, NDArray eigenvectors) eig(NDArray a)
Parameters
aNDArrayThe square matrix, or a stack of them.
Returns
- (NDArray Lhs, NDArray Rhs)
(eigenvalues, eigenvectors), the columns of the second being the vectors.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.eig.html
The result is always complex (NumPy 2.5): a real matrix with real eigenvalues gives
complex values with zero imaginary parts, so the dtype no longer depends on the values
(NumPy 2.4 returned a real dtype then). Use eigh(NDArray, char) where the operand is known
symmetric or Hermitian — it is both faster and gives real eigenvalues; or take
np.real(w) when !np.any(np.imag(w)), NumPy's own recipe for the old result.
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- LinAlgError
Fewer than two axes, a non-square operand, or an operand holding inf / NaN.
- TypeError
A text operand, or a float16, decimal or char operand.
- ArgumentNullException
ais null.
eigh(NDArray, char)
Eigenvalues and eigenvectors of a real symmetric or complex Hermitian matrix.
public static (NDArray eigenvalues, NDArray eigenvectors) eigh(NDArray a, char UPLO = 'L')
Parameters
aNDArrayThe real symmetric / complex Hermitian matrix, or a stack of them.
UPLOcharWhich triangle holds the data —
'L'(default) or'U'. Case insensitive. The other triangle is NOT read, so a non-symmetric operand is silently interpreted as its own reflection rather than rejected.
Returns
- (NDArray Lhs, NDArray Rhs)
(eigenvalues, eigenvectors)with the eigenvalues in ASCENDING order and always REAL — even for a complex operand, where they come back as the real counterpart dtype.
Remarks
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); aUPLOthat is neither 'L' nor 'U'.- LinAlgError
Fewer than two axes, or a non-square operand.
- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.
eigvals(NDArray)
Eigenvalues of a general matrix, without the eigenvectors.
public static NDArray eigvals(NDArray a)
Parameters
aNDArrayThe square matrix, or a stack of them.
Returns
- NDArray
The eigenvalues, always complex (NumPy 2.5), as eig(NDArray)'s.
Remarks
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- LinAlgError
Fewer than two axes, a non-square operand, or an operand holding inf / NaN.
- TypeError
A text operand, or a float16, decimal or char operand.
- ArgumentNullException
ais null.
eigvalsh(NDArray, char)
Eigenvalues of a real symmetric or complex Hermitian matrix, ascending.
public static NDArray eigvalsh(NDArray a, char UPLO = 'L')
Parameters
aNDArrayThe real symmetric / complex Hermitian matrix, or a stack of them.
UPLOcharWhich triangle holds the data —
'L'(default) or'U'. Case insensitive. The other triangle is NOT read, so a non-symmetric operand is silently interpreted as its own reflection rather than rejected.
Returns
- NDArray
(eigenvalues, eigenvectors)with the eigenvalues in ASCENDING order and always REAL — even for a complex operand, where they come back as the real counterpart dtype.
Remarks
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); aUPLOthat is neither 'L' nor 'U'.- LinAlgError
Fewer than two axes, or a non-square operand.
- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.- ArgumentNullException
ais null.
inv(NDArray)
Multiplicative inverse of a matrix, or of each matrix in a stack.
public static NDArray inv(NDArray a)
Parameters
aNDArrayThe square matrix, or a stack of them.
Returns
- NDArray
The inverse, a fresh array (float64 for bool / integer operands).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html
NumPy does not call an explicit inversion routine: it solves a x = I with
gesv, which is why a singular operand surfaces as
LinAlgError("Singular matrix") from the factorisation rather than from a
determinant test.
No matrix backend is needed: without one, NumSharp's managed LU computes the inverse (allclose to NumPy's LAPACK result, bit for bit for small matrices); an installed backend is used first.
Exceptions
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- LinAlgError
Fewer than two axes, a non-square operand, or a singular matrix.
- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.
lstsq(NDArray, NDArray, double?)
Least-squares solution to a x = b.
public static (NDArray Solution, NDArray Residuals, NDArray Rank, NDArray SingularValues) lstsq(NDArray a, NDArray b, double? rcond = null)
Parameters
aNDArrayCoefficient matrix,
(M, N). Exactly 2-D — lstsq does NOT stack.bNDArrayOrdinate values,
(M,)or(M, K).rconddouble?Singular values smaller than
rcondtimes the largest are treated as zero.
Returns
- (NDArray, NDArray, NDArray, NDArray)
(solution, residuals, rank, singularValues)— NumPy's four-tuple. The residuals are EMPTY unless the system is overdetermined and full-rank.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.lstsq.html
Unlike most of this module, lstsq takes a single matrix rather than a stack
— a 3-D operand is rejected with the "must be two-dimensional" message rather than
the "at least two-dimensional" one.
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- LinAlgError
An operand that is not two-dimensional, or
b's rows differ froma's.- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.
matmul(NDArray, NDArray)
Matrix product — the Array-API spelling of matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char).
public static NDArray matmul(NDArray x1, NDArray x2)
Parameters
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.matmul.html
This one really is the same operation as its main-namespace twin, unlike the rest of the forms in this file.
Exceptions
- ArgumentNullException
x1is null.
matrix_norm(NDArray, bool, object)
The Array-API matrix norm — always reduces the LAST TWO axes, and defaults to Frobenius.
public static NDArray matrix_norm(NDArray x, bool keepdims = false, object ord = null)
Parameters
xNDArrayThe matrix, or a stack of them (the last two axes).
keepdimsboolLeave the two reduced axes in the result with length 1.
ordobjectThe order.
nullmeans NumPy's default of"fro"— C# cannot spell a non-null default for anobjectparameter, so the sentinel carries it.
Returns
- NDArray
The matrix norm over the last two axes.
Remarks
Exceptions
- ValueError
An invalid matrix order, or a min order of an empty matrix.
- AxisError
An operand of fewer than two axes.
- OpenBlasMissingBackendException
An order 2, -2 or
"nuc"over a non-empty matrix with no matrix backend installed.- ArgumentNullException
xis null.
matrix_power(NDArray, int)
Raises a square matrix to the (integer) power n.
public static NDArray matrix_power(NDArray a, int n)
Parameters
aNDArrayThe square matrix, or a stack of them (the last two axes).
nintAny integer.
0gives the identity, a NEGATIVE power inverts first.
Returns
- NDArray
The power. Footgun (NumPy's own):
n == 1returnsaITSELF, not a copy (np.linalg.matrix_power(a, 1) is a), so writing to the result writes toa;n == -1returns the fresh inverse.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_power.html
Computed by binary exponentiation, so the cost is logarithmic in
n rather than linear — NumPy's own algorithm, and the reason
the first three powers are special-cased before the loop starts.
A negative power is the only route here that needs a matrix backend
(a**-n is inv(a)**n), so it raises
OpenBlasMissingBackendException while none is installed. Non-negative powers
work.
Exceptions
- LinAlgError
ais not at least 2-D, or its last two axes are not square; a negative power of a singular matrix.- TypeError
A text matrix with
nof 2 or more (matmul has no string loop) or a negativen(inv's input cast).- OpenBlasMissingBackendException
A negative power of a matrix the managed LU cannot take with no backend installed.
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- ArgumentNullException
ais null.
matrix_rank(NDArray, double?, bool, double?)
Rank of a matrix — the number of singular values greater than the tolerance.
public static NDArray matrix_rank(NDArray A, double? tol = null, bool hermitian = false, double? rtol = null)
Parameters
ANDArrayThe matrix, or a stack of them.
toldouble?Absolute threshold. Defaults to
S.max() * max(M, N) * eps.hermitianboolAssume the operand is Hermitian.
rtoldouble?Relative threshold; supplying it together with
tolis an error.
Returns
- NDArray
The rank: NumPy's
int(not all(A == 0))below two axes, else the count per matrix.
Remarks
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
Both
tolandrtolset.- LinAlgError
A non-square operand with
hermitian.- TypeError
A float16, decimal or char operand.
- TypeError
A text operand of two or more axes (NumPy's gufunc input-cast refusal).
- ArgumentNullException
Ais null.
matrix_transpose(NDArray)
Transposes the last two axes — the Array-API spelling of matrix_transpose(NDArray). An O(1) view.
public static NDArray matrix_transpose(NDArray x)
Parameters
xNDArray
Returns
Remarks
multi_dot(NDArray[], NDArray)
Chained matrix product, evaluated in the cheapest association order.
public static NDArray multi_dot(NDArray[] arrays, NDArray @out = null)
Parameters
arraysNDArray[]Two or more arrays. With three or more, every one must be 2-D EXCEPT the endpoints, which may be 1-D (a 1-D first operand is a row, a 1-D last a column); a 0-D, a 3-D-or-higher, or a 1-D operand anywhere in the MIDDLE raises LinAlgError "{ndim}-dimensional array given. Array must be two-dimensional". With exactly two arrays this is a plain dot(NDArray, NDArray, NDArray) and imposes no such restriction.
outNDArrayWhere to deposit the answer. NumPy hands
outto the finaldot, so it receives the TWO-DIMENSIONAL product and the returned array is a reshaped view of it —outformulti_dot([v, B, C])is shaped(1, k), not(k,).
Returns
- NDArray
The chain's product:
outitself for a two-array chain given one, else a fresh array or a reshaped view ofout.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.multi_dot.html
Matrix multiplication is associative but its COST is not: chaining
(10000,100) @ (100,1000) @ (1000,5) left to right costs about 10⁹
multiplications and right to left about 10⁷. This picks the order with the
classic O(n³) dynamic program (Cormen et al. 15.2) — except for exactly three
matrices, where the single comparison is done directly.
A 1-D first operand is treated as a ROW vector and a 1-D last operand as a COLUMN
vector, with the added axis removed again afterwards — so the chain's endpoints
behave like np.dot's.
NumPy's one signature, multi_dot(arrays, *, out=None): the arrays are ONE sequence argument
(np.linalg.multi_dot(new[] { A, B, C })). NumPy refuses them as separate arguments
(multi_dot(A, B, C): TypeError "multi_dot() takes 1 positional argument but 3 were given"), and
since API-parity batch 7 NumSharp has no params form that accepted that spelling.
Exceptions
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); fewer than two arrays.- LinAlgError
With three or more arrays, an operand other than a vector end that is not two-dimensional.
norm(NDArray, object, int, bool)
norm(NDArray, object, NDAxis?, bool) with one int axis: the overload a C# integer binds
(an ord must be given positionally or by name with it), forwarding to the NDAxis? form.
public static NDArray norm(NDArray x, object ord, int axis, bool keepdims = false)
Parameters
xNDArrayInput array.
ordobjectThe order (see the NDAxis? form;
nullfor NumPy's default).axisintThe axis of a vector norm (a negative value counts from the end).
keepdimsboolLeave the reduced axis in the result with length 1.
Returns
- NDArray
The norm.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html
Every order works WITHOUT a matrix backend except three — matrix
ord 2, -2 and "nuc", which are defined through singular values and so
raise OpenBlasMissingBackendException. The rest are reductions
(abs(NDArray, NDArray, NDArray, DType), sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray), amax(NDArray, NDAxis?, NDArray, bool, object, NDArray),
np.power(NDArray, NDArray)) and compute normally.
How many axes are being reduced decides which vocabulary of orders applies, which
is why norm(vector, "fro") and norm(matrix, 3) both raise but with
DIFFERENT messages, and a 3-D operand with an explicit ord and no
axis raises a third ("Improper number of dimensions to norm.").
One signature for NumPy's int-or-tuple axis since API-parity batch 6 (norm(x, null, null,
false) was ambiguous between the int? and int[] forms); the int and int[] overloads forward
here. NumPy turns an int into the 1-tuple (axis,), so both reach the engine as one array.
Exceptions
- ValueError
An order that is invalid for the number of reduced axes, duplicate axes (
Duplicate axes given.), no axis or more than two (Improper number of dimensions to norm.), or a min order (-1, -inf, -2) of an empty operand.- ValueError
A text element that does not parse as a float (NumPy's
x.astype(float):could not convert string to float: np.str_('x')).- OpenBlasMissingBackendException
A matrix order 2, -2 or
"nuc"over a non-empty matrix with no matrix backend installed (an empty matrix or a zero-size batch needs none).- AxisError
An axis out of range.
- TypeError
An order that is neither null, a number nor a string.
- ArgumentNullException
xis null.
norm(NDArray, object, int[], bool)
norm(NDArray, object, NDAxis?, bool) with the axes as an int[]: the overload an
int[] and a bare null bind, forwarding to the NDAxis? form (a null array is None, any other
array NumPy's tuple).
public static NDArray norm(NDArray x, object ord, int[] axis, bool keepdims = false)
Parameters
xNDArrayInput array.
ordobjectThe order (see the NDAxis? form).
axisint[]The axes as NumPy's tuple (one for a vector norm, two for a matrix norm), or
null.keepdimsboolLeave the reduced axes in the result with length 1.
Returns
- NDArray
The norm.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html
Every order works WITHOUT a matrix backend except three — matrix
ord 2, -2 and "nuc", which are defined through singular values and so
raise OpenBlasMissingBackendException. The rest are reductions
(abs(NDArray, NDArray, NDArray, DType), sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray), amax(NDArray, NDAxis?, NDArray, bool, object, NDArray),
np.power(NDArray, NDArray)) and compute normally.
How many axes are being reduced decides which vocabulary of orders applies, which
is why norm(vector, "fro") and norm(matrix, 3) both raise but with
DIFFERENT messages, and a 3-D operand with an explicit ord and no
axis raises a third ("Improper number of dimensions to norm.").
One signature for NumPy's int-or-tuple axis since API-parity batch 6 (norm(x, null, null,
false) was ambiguous between the int? and int[] forms); the int and int[] overloads forward
here. NumPy turns an int into the 1-tuple (axis,), so both reach the engine as one array.
Exceptions
- ValueError
An order that is invalid for the number of reduced axes, duplicate axes (
Duplicate axes given.), no axis or more than two (Improper number of dimensions to norm.), or a min order (-1, -inf, -2) of an empty operand.- ValueError
A text element that does not parse as a float (NumPy's
x.astype(float):could not convert string to float: np.str_('x')).- OpenBlasMissingBackendException
A matrix order 2, -2 or
"nuc"over a non-empty matrix with no matrix backend installed (an empty matrix or a zero-size batch needs none).- AxisError
An axis out of range.
- TypeError
An order that is neither null, a number nor a string.
- ArgumentNullException
xis null.
norm(NDArray, object, NDAxis?, bool)
Matrix or vector norm.
public static NDArray norm(NDArray x, object ord = null, NDAxis? axis = null, bool keepdims = false)
Parameters
xNDArrayInput array. Integer and bool operands are computed in float64.
ordobjectThe order:
null(Frobenius for a matrix, 2-norm for a vector), a number (includingdouble.PositiveInfinity), or one of"fro","f","nuc".axisNDAxis?NumPy's
axis:null(the whole array: a vector norm of a 1-D input, a matrix norm of a 2-D one), one axis (NumPy's 1-tuple: a vector norm along it), or a tuple of one or two axes (a vector or a matrix norm). Any other length is NumPy's ValueError.keepdimsboolLeave the reduced axes in the result with length 1.
Returns
- NDArray
The norm: a 0-d array for a whole-array norm, else the reduced array. An EMPTY operand's inf-, 1- and 2-norms are 0.0 (NumPy 2.x reduces those with
initial=0). Anumpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html
Every order works WITHOUT a matrix backend except three — matrix
ord 2, -2 and "nuc", which are defined through singular values and so
raise OpenBlasMissingBackendException. The rest are reductions
(abs(NDArray, NDArray, NDArray, DType), sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray), amax(NDArray, NDAxis?, NDArray, bool, object, NDArray),
np.power(NDArray, NDArray)) and compute normally.
How many axes are being reduced decides which vocabulary of orders applies, which
is why norm(vector, "fro") and norm(matrix, 3) both raise but with
DIFFERENT messages, and a 3-D operand with an explicit ord and no
axis raises a third ("Improper number of dimensions to norm.").
One signature for NumPy's int-or-tuple axis since API-parity batch 6 (norm(x, null, null,
false) was ambiguous between the int? and int[] forms); the int and int[] overloads forward
here. NumPy turns an int into the 1-tuple (axis,), so both reach the engine as one array.
Exceptions
- ValueError
An order that is invalid for the number of reduced axes, duplicate axes (
Duplicate axes given.), no axis or more than two (Improper number of dimensions to norm.), or a min order (-1, -inf, -2) of an empty operand.- ValueError
A text element that does not parse as a float (NumPy's
x.astype(float):could not convert string to float: np.str_('x')).- OpenBlasMissingBackendException
A matrix order 2, -2 or
"nuc"over a non-empty matrix with no matrix backend installed (an empty matrix or a zero-size batch needs none).- AxisError
An axis out of range.
- TypeError
An order that is neither null, a number nor a string.
- ArgumentNullException
xis null.
outer(NDArray, NDArray)
Outer product of two VECTORS.
public static NDArray outer(NDArray x1, NDArray x2)
Parameters
Returns
- NDArray
The
(len(x1), len(x2))outer product, a fresh array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.outer.html
Not a synonym for outer(NDArray, NDArray, NDArray): that one flattens whatever it is given,
while this rejects anything but 1-D. np.outer(ones((2,3)), ones(3)) is a
(6,3) array; np.linalg.outer of the same pair raises.
Exceptions
- ValueError
Either operand is not one-dimensional.
- ArgumentNullException
x1is null.
pinv(NDArray, double?, bool, double?)
Moore-Penrose pseudo-inverse, computed from the singular value decomposition.
public static NDArray pinv(NDArray a, double? rcond = null, bool hermitian = false, double? rtol = null)
Parameters
aNDArrayThe matrix, or a stack of them.
rconddouble?Singular values below
rcond * largestare treated as zero. NumPy's default is1e-15.hermitianboolAssume the operand is Hermitian, allowing the cheaper symmetric eigensolver.
rtoldouble?The Array-API spelling of
rcond. Supplying both is an error, as upstream.
Returns
- NDArray
The pseudo-inverse, shape
(..., N, M).
Remarks
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); bothrcondandrtolset.- TypeError
A text operand, or a float16, decimal or char operand.
- LinAlgError
Fewer than two axes, or a non-square operand with
hermitian.- ArgumentNullException
ais null.
qr(NDArray, string)
QR factorisation — a = Q R with Q orthonormal and R upper-triangular.
public static (NDArray Q, NDArray R) qr(NDArray a, string mode = "reduced")
Parameters
aNDArrayThe matrix, or a stack of them.
modestring"reduced"(default) givesQ:(...,M,K),R:(...,K,N)forK = min(M,N);"complete"gives a squareQ:(...,M,M);"r"returns R alone;"raw"returns LAPACK's packed(h, tau)pair rather than (Q, R).
Returns
Remarks
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); an unknownmode(checked before the operand).- LinAlgError
Fewer than two axes.
- TypeError
A float16, decimal or char operand.
- ArgumentNullException
ais null.
slogdet(NDArray)
Sign and natural log of the absolute determinant — the overflow-safe det(NDArray).
public static (NDArray sign, NDArray logabsdet) slogdet(NDArray a)
Parameters
aNDArrayThe square matrix, or a stack of them.
Returns
- (NDArray Lhs, NDArray Rhs)
(sign, logabsdet), such thatsign * exp(logabsdet)is the determinant. A singular matrix gives(0, -inf); for a complex operand the sign is a unit-modulus complex number rather than ±1.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.slogdet.html
No matrix backend is needed: without one, NumSharp's managed LU computes it (allclose to NumPy's LAPACK result, bit for bit for small matrices); an installed backend is used first.
Exceptions
- LinAlgError
Fewer than two axes, or a non-square operand.
- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.
solve(NDArray, NDArray)
Solves the linear system a x = b for x.
public static NDArray solve(NDArray a, NDArray b)
Parameters
Returns
- NDArray
The solution, a fresh array (float64 for bool / integer operands).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html
NumPy 2.0 tightened the b-is-a-vector rule: b is treated as a
stack of vectors ONLY when it is exactly 1-D. Anything else is a stack of matrices,
so the two gufuncs — (m,m),(m)->(m) and (m,m),(m,n)->(m,n) — are
selected by rank alone and report their own core-dimension errors.
No matrix backend is needed: without one, NumSharp's managed LU computes the solution (allclose to NumPy's LAPACK result, bit for bit for small matrices); an installed backend is used first.
Exceptions
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); a core dimension ofbthat does not matcha.- LinAlgError
Fewer than two axes, a non-square
a, or a singular matrix.- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.
svd(NDArray, bool, bool, bool)
Singular value decomposition — a = U diag(S) Vh.
public static (NDArray U, NDArray S, NDArray Vh) svd(NDArray a, bool full_matrices = true, bool compute_uv = true, bool hermitian = false)
Parameters
aNDArrayThe matrix, or a stack of them.
full_matricesboolTrue (the default) makes U and Vh full square factors; false truncates them to
K = min(M, N)columns/rows.compute_uvboolFalse returns the singular values alone —
UandVhare then null.hermitianboolAssume the operand is Hermitian, allowing the cheaper symmetric eigensolver.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.svd.html
Singular values come back in DESCENDING order. This is the routine behind pinv(NDArray, double?, bool, double?), matrix_rank(NDArray, double?, bool, double?), cond(NDArray, object) and the spectral and nuclear matrix norms — which is why all of those stop here too.
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- LinAlgError
Fewer than two axes, or a non-square operand with
hermitian.- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
ais null.
svdvals(NDArray)
Singular values of a matrix, descending — the Array-API spelling of
svd(x, compute_uv: false).
public static NDArray svdvals(NDArray x)
Parameters
xNDArrayThe matrix, or a stack of them.
Returns
- NDArray
The singular values, descending.
Remarks
Exceptions
- OpenBlasMissingBackendException
A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).
- LinAlgError
Fewer than two axes.
- TypeError
A float16, decimal or char operand.
- TypeError
A text operand (NumPy's gufunc input-cast refusal).
- ArgumentNullException
xis null.
tensordot(NDArray, NDArray, int)
Tensor contraction — the Array-API spelling of tensordot(NDArray, NDArray, int).
public static NDArray tensordot(NDArray x1, NDArray x2, int axes = 2)
Parameters
Returns
Remarks
Exceptions
- ArgumentNullException
x1is null.
tensordot(NDArray, NDArray, (int AxisA, int AxisB))
Tensor contraction pairing ONE axis of x1 with one of x2 — NumPy's
np.linalg.tensordot(x1, x2, axes=(1, 0)), the Array-API spelling of
tensordot(NDArray, NDArray, (int AxisA, int AxisB)).
public static NDArray tensordot(NDArray x1, NDArray x2, (int AxisA, int AxisB) axes)
Parameters
x1NDArrayThe first tensor.
x2NDArrayThe second tensor.
axes(int AxisA, int AxisB)The axis of
x1and the axis ofx2to contract (NumPy'saxes_a, axes_b = axesmakes each a one-element list).
Returns
- NDArray
A new array of
x1's kept axes followed byx2's.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.tensordot.html — NumPy's axes is
keyword-only there; C# cannot refuse a positional pair, so tensordot(x1, x2, (1, 0)) also binds.
Added in API-parity batch 7 (np.tensordot had the pair already).
Exceptions
- ArgumentNullException
x1is null.- IndexError
An axis out of range (
tuple index out of range).- ValueError
Extents that differ (
shape-mismatch for sum).
tensordot(NDArray, NDArray, (int[] AxesA, int[] AxesB))
Tensor contraction pairing a list of axes of x1 with a list of axes of
x2, element by element — NumPy's np.linalg.tensordot(x1, x2, axes=([1, 0], [0, 1])),
the pair as ONE argument: np.linalg.tensordot(x1, x2, axes: (new[] { 1, 0 }, new[] { 0, 1 })).
public static NDArray tensordot(NDArray x1, NDArray x2, (int[] AxesA, int[] AxesB) axes)
Parameters
x1NDArrayThe first tensor.
x2NDArrayThe second tensor.
axes(int[] AxesA, int[] AxesB)NumPy's pair of axis lists:
AxesAofx1,AxesBofx2, paired element by element.
Returns
- NDArray
A new array of
x1's kept axes followed byx2's.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.tensordot.html — the statements are
the Linalg engine's Tensordot(x1, x2, int[], int[]). Until API-parity batch 7 the pair was split into
two parameters, tensordot(x1, x2, int[] axesA, int[] axesB), a four-argument call NumPy refuses
(tensordot() takes 2 positional arguments but 4 were given).
Exceptions
- ArgumentNullException
x1is null.- ValueError
duplicate axes are not allowed in tensordot(checked first), orshape-mismatch for sumfor unequal list lengths and mismatched extents.- IndexError
A contraction axis out of range (
tuple index out of range).- NullReferenceException
An axis list is null.
tensorinv(NDArray, int)
Inverse of an N-dimensional array with respect to a tensordot(NDArray, NDArray, int)
contraction over its last a.ndim - ind axes.
public static NDArray tensorinv(NDArray a, int ind = 2)
Parameters
aNDArrayThe tensor to invert.
indintHow many LEADING axes form the "row" side. Must be positive.
Returns
- NDArray
The inverse, shape
a.shape[ind:] + a.shape[:ind]: a view of the inverse of the square matrix (NumPy'sia.reshape(*invshape)).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.tensorinv.html
The inverse needs no matrix backend (the managed LU computes it). A 0-d operand is inverted as a 1x1
matrix and then refused, as in NumPy: its invshape is empty, and ia.reshape(*invshape) calls
reshape() with no argument.
Exceptions
- ValueError
indis not positive, or the reshape to a square matrix is impossible.- LinAlgError
The reshaped matrix is not square, or is singular.
- TypeError
A float16, decimal or char operand (inv's
_commonType), or a 0-d operand whose 1x1 inverse succeeded (reshape() takes exactly 1 argument (0 given)).- TypeError
A text operand (inv's gufunc input cast, NumPy's UFuncTypeError).
- ArgumentNullException
ais null.
tensorsolve(NDArray, NDArray, int[])
Solves the tensor equation a x = b for x.
public static NDArray tensorsolve(NDArray a, NDArray b, int[] axes = null)
Parameters
aNDArrayThe coefficient tensor; its leading
b.ndimaxes (afteraxesmoved some to the end) index the equations.bNDArrayThe right-hand side.
axesint[]Axes of
ato move to the right before inversion. NumPy uses them as LIST VALUES (allaxes.remove(k)), never normalizing them: a negative axis is not found, so only0 .. a.ndim - 1are accepted.
Returns
- NDArray
The solution, of NumPy's
oldshape = a.shape[-(a.ndim - b.ndim):](after the axis move): the trailinga.ndim - b.ndimaxes, or the WHOLE shape ofawhen the two have as many axes. A view of the 1-D solution (NumPy 2.5'sres.reshape(oldshape):owndataFalse; NumPy 2.4's in-placeres.shape = oldshapereturned an owning array). Anumpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.tensorsolve.html
A reshape of solve(NDArray, NDArray): a is collapsed to a square
matrix whose side is prod(oldshape), solved against b.ravel(), and the
solution relabelled to oldshape in place. The slice's edges are NumPy's: with
as many axes in a as in b only an operand of 0
or 1 elements passes the size check (an empty or 1x1 system), and with more axes in
b the system is 1x1. The solve needs no matrix backend (the managed
LU computes it).
Exceptions
- ValueError
An axis that is not one of
0 .. a.ndim - 1: Python's "list.remove(x): x not in list" (a negative axis included; NumPy raises no AxisError here); or a right-hand side that does not match the square system (solve's gufunc text).- LinAlgError
a.sizeis notprod(oldshape) ** 2, or the system is singular.- TypeError
A float16, decimal or char operand (solve's
_commonType).- TypeError
A text operand (solve's gufunc input cast, NumPy's UFuncTypeError).
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- ArgumentNullException
ais null.
trace(NDArray, int, DType)
Sum along the diagonals of the LAST TWO axes.
public static NDArray trace(NDArray x, int offset = 0, DType dtype = null)
Parameters
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.trace.html
The axes differ from trace(NDArray, int, int, int, DType, NDArray)'s, which defaults to the FIRST
two — so on a (2,3,3) stack this returns shape (2,) (one trace per
matrix) where np.trace returns (3,). Neither is wrong; they are
different functions.
Exceptions
- ArgumentNullException
xis null.
vecdot(NDArray, NDArray, int)
Vector dot product over axis, conjugating the first operand.
public static NDArray vecdot(NDArray x1, NDArray x2, int axis = -1)
Parameters
Returns
Remarks
Exceptions
- ArgumentNullException
x1is null.
vector_norm(NDArray, int, bool, object)
vector_norm(NDArray, NDAxis?, bool, object) with one int axis: the overload a C#
integer binds, forwarding to the NDAxis? form (NumPy's integer branch: norm along that axis).
public static NDArray vector_norm(NDArray x, int axis, bool keepdims = false, object ord = null)
Parameters
xNDArrayInput array.
axisintThe reduced axis (a negative value counts from the end).
keepdimsboolLeave the reduced axis in the result with length 1.
ordobjectThe vector order;
nullmeans NumPy's default of 2.
Returns
- NDArray
The norm along
axis.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.vector_norm.html
An integer axis is NOT the one-element tuple: NumPy hands an int to norm as it is, while its tuple branch,
statement for statement, is normalize_axis_tuple(axis, x.ndim), the reduced axes moved to the front
(transpose(x, axis + rest), the axes AS GIVEN) and merged into one
(reshape((prod(shape[axis]), *shape[rest]))), then norm's ONE-axis branch over axis 0 - a vector
norm whatever the tuple's length. Both reach the vector branch, in different reduction layouts, so the
engine keeps them apart. Handing a 2-tuple to norm(NDArray, object, NDAxis?, bool) directly
would reach its MATRIX branch instead (the largest singular value, not sqrt(sum(|x|^2))).
One signature for NumPy's int-or-tuple axis since API-parity batch 6; the int and
int[] overloads forward here.
Exceptions
- AxisError
An axis is out of range (a 0-d input has no axis).
- ValueError
An axis appears twice ("repeated axis"), a text order, or -inf of an empty operand.
- TypeError
An order that is neither null, a number nor a string.
- ArgumentNullException
xis null.
vector_norm(NDArray, int[], bool, object)
vector_norm(NDArray, NDAxis?, bool, object) with the axes as an int[]: the overload an
int[] and a bare null bind, forwarding to the NDAxis? form (a null array is the flattened
array, any other array NumPy's tuple branch).
public static NDArray vector_norm(NDArray x, int[] axis, bool keepdims = false, object ord = null)
Parameters
xNDArrayInput array.
axisint[]The reduced axes as NumPy's tuple, or
nullfor the flattened array.keepdimsboolLeave the reduced axes in the result with length 1.
ordobjectThe vector order;
nullmeans NumPy's default of 2.
Returns
- NDArray
The vector norm over the axes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.vector_norm.html
An integer axis is NOT the one-element tuple: NumPy hands an int to norm as it is, while its tuple branch,
statement for statement, is normalize_axis_tuple(axis, x.ndim), the reduced axes moved to the front
(transpose(x, axis + rest), the axes AS GIVEN) and merged into one
(reshape((prod(shape[axis]), *shape[rest]))), then norm's ONE-axis branch over axis 0 - a vector
norm whatever the tuple's length. Both reach the vector branch, in different reduction layouts, so the
engine keeps them apart. Handing a 2-tuple to norm(NDArray, object, NDAxis?, bool) directly
would reach its MATRIX branch instead (the largest singular value, not sqrt(sum(|x|^2))).
One signature for NumPy's int-or-tuple axis since API-parity batch 6; the int and
int[] overloads forward here.
Exceptions
- AxisError
An axis is out of range (a 0-d input has no axis).
- ValueError
An axis appears twice ("repeated axis"), a text order, or -inf of an empty operand.
- TypeError
An order that is neither null, a number nor a string.
- ArgumentNullException
xis null.
vector_norm(NDArray, NDAxis?, bool, object)
The Array-API vector norm — axis defaults to flattening and ord to 2.
public static NDArray vector_norm(NDArray x, NDAxis? axis = null, bool keepdims = false, object ord = null)
Parameters
xNDArrayInput array. Integer and bool operands are computed in float64.
axisNDAxis?NumPy's
axis:null(the flattened array), one axis, or a tuple of any number of axes (negative values count from the end;()reduces nothing: the elementwise magnitude).keepdimsboolLeave the reduced axes in the result with length 1.
ordobjectThe order.
nullmeans NumPy's default of 2 — C# cannot spell a non-null default for anobjectparameter, so the sentinel carries it.
Returns
- NDArray
The vector norm over the axes; with
keepdimsa view of it (NumPy's reshape, which does not own its data). Anumpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linalg.vector_norm.html
An integer axis is NOT the one-element tuple: NumPy hands an int to norm as it is, while its tuple branch,
statement for statement, is normalize_axis_tuple(axis, x.ndim), the reduced axes moved to the front
(transpose(x, axis + rest), the axes AS GIVEN) and merged into one
(reshape((prod(shape[axis]), *shape[rest]))), then norm's ONE-axis branch over axis 0 - a vector
norm whatever the tuple's length. Both reach the vector branch, in different reduction layouts, so the
engine keeps them apart. Handing a 2-tuple to norm(NDArray, object, NDAxis?, bool) directly
would reach its MATRIX branch instead (the largest singular value, not sqrt(sum(|x|^2))).
One signature for NumPy's int-or-tuple axis since API-parity batch 6; the int and
int[] overloads forward here.
Exceptions
- AxisError
An axis is out of range (a 0-d input has no axis).
- ValueError
An axis appears twice ("repeated axis"), a text order, or -inf of an empty operand.
- TypeError
An order that is neither null, a number nor a string.
- ArgumentNullException
xis null.