Class np
- Namespace
- NumSharp
- Assembly
- NumSharp.dll
API bridge between NumSharp and Python NumPy
[ModuleName("np")]
[SuppressMessage("ReSharper", "StaticMemberInitializerReferesToMemberBelow")]
public static class np
- Inheritance
-
np
- Inherited Members
Fields
bool
public static readonly DType @bool
Field Value
bool8
NumPy 1.x's np.bool8: the bool_ descriptor. Kept on purpose, so code written against
NumPy 1.x compiles and runs unchanged, although NumPy 1.24 deprecated the name and NumPy 2.0 removed it
(np.bool8 raises AttributeError: module 'numpy' has no attribute 'bool8'). New code writes
bool_.
public static readonly DType bool8
Field Value
Remarks
Only the member is kept: the dtype STRING follows NumPy 2.x, so np.dtype("bool8") raises NumPy's
Alias 'bool8' was removed in NumPy 2.0. Use a name without a digit at the end.
bool_
public static readonly DType bool_
Field Value
byte
public static readonly DType @byte
Field Value
bytes_
NumPy's np.bytes_ as a dtype spelling: the UNSIZED fixed-width bytes descriptor dtype('S'). It has
no C# Type spelling — typeof(byte[]) is a uint8 array, as for every C# array type — so
this field, "S"/"S5" or BytesDType are the ways to request it.
public static readonly DType bytes_
Field Value
cdouble
public static readonly DType cdouble
Field Value
clongdouble
numpy.clongdouble (complex long double, char 'G', type number 16) — its own class over the
complex128 lane, two 8-byte parts (see longdouble): equal to complex128, not the
same class.
public static readonly DType clongdouble
Field Value
complex128
public static readonly DType complex128
Field Value
complex_
NumPy 1.x's np.complex_: the complex128 descriptor. Kept on purpose, so code written
against NumPy 1.x compiles and runs unchanged, although NumPy 2.0 removed it (np.complex_ raises
AttributeError: ). New
code writes complex128.np.complex_ was removed in the NumPy 2.0 release. Use np.complex128 instead.
public static readonly DType complex_
Field Value
Remarks
Only the member is kept: the dtype STRING follows NumPy 2.x, which has no such name, so
np.dtype("complex_") is NumPy's data type 'complex_' not understood.
decimal
NumSharp-only: the decimal descriptor (no NumPy counterpart).
public static readonly DType @decimal
Field Value
double
public static readonly DType @double
Field Value
float16
public static readonly DType float16
Field Value
float32
public static readonly DType float32
Field Value
float64
public static readonly DType float64
Field Value
float_
NumPy 1.x's np.float_: the float64 descriptor. Kept on purpose, so code written against
NumPy 1.x compiles and runs unchanged, although NumPy 2.0 removed it (np.float_ raises
AttributeError: ). New code
writes float64.np.float_ was removed in the NumPy 2.0 release. Use np.float64 instead.
public static readonly DType float_
Field Value
Remarks
Only the member is kept: the dtype STRING follows NumPy 2.x, which has no such name, so
np.dtype("float_") is NumPy's data type 'float_' not understood.
half
public static readonly DType half
Field Value
int0
NumPy 1.x's np.int0 (an alias of np.intp): the int64 descriptor, intp's width on a
64-bit host. Kept on purpose, so code written against NumPy 1.x compiles and runs unchanged, although NumPy
1.24 deprecated the name and NumPy 2.0 removed it (np.int0 raises
AttributeError: module 'numpy' has no attribute 'int0'). New code writes intp or
int64.
public static readonly DType int0
Field Value
Remarks
Only the member is kept: the dtype STRING follows NumPy 2.x, so np.dtype("int0") raises NumPy's
Alias 'int0' was removed in NumPy 2.0. Use a name without a digit at the end.
int16
public static readonly DType int16
Field Value
int32
public static readonly DType int32
Field Value
int64
public static readonly DType int64
Field Value
int8
public static readonly DType int8
Field Value
int_
public static readonly DType int_
Field Value
intc
numpy.intc (C int, char 'i', type number 5): on Windows its own class beside
int32 (which is the C long there) — equal to it (np.dtype(np.intc) ==
np.dtype(np.int32), the same 32-bit lane) but not the same class (np.issubdtype(np.int32,
np.intc) is False); on Linux and macOS the int32 descriptor itself.
public static readonly DType intc
Field Value
intp
public static readonly DType intp
Field Value
long
public static readonly DType @long
Field Value
longdouble
numpy.longdouble (C long double, char 'g', type number 13) — its own class
(np.dtypes.LongDoubleDType, scalar class numpy.longdouble) over the float64 storage lane. NumSharp
has no extended precision, so it is the 8-byte double of NumPy's win-amd64 build on every platform:
np.dtype(np.longdouble) == np.dtype('d') and a cast between them is a no-op, while
np.issubdtype(np.float64, np.longdouble) is False, as in NumPy.
public static readonly DType longdouble
Field Value
Remarks
An array created with this dtype keeps it (np.zeros(3, np.longdouble).dtype.@char is 'g'), and
so do its views, copies and casts to it; an operation computes in the float64 lane and returns float64 where
NumPy keeps longdouble (equal descriptors, so result.dtype == np.longdouble still holds). Linux
NumPy's longdouble is an 80-bit type in 16 bytes (float128); NumSharp's is not.
longlong
numpy.longlong (C long long, char 'q', type number 9): on Linux and macOS its own class
beside int64 (which is the C long there) — equal to it, the same 64-bit lane, but not the
same class; on Windows the int64 descriptor itself.
public static readonly DType longlong
Field Value
newaxis
A convenient alias for None, useful for indexing arrays.
public static readonly Slice newaxis
Field Value
Remarks
https://numpy.org/doc/stable/user/basics.indexing.html
https://stackoverflow.com/questions/42190783/what-does-three-dots-in-python-mean-when-indexing-what-looks-like-a-number
sbyte
public static readonly DType @sbyte
Field Value
short
public static readonly DType @short
Field Value
single
public static readonly DType single
Field Value
str_
NumPy's np.str_ as a dtype spelling: the UNSIZED fixed-width Unicode descriptor dtype('<U')
(the same object np.dtype("U") and np.dtype(typeof(string)) return). As a dtype= argument
it means "Unicode, length chosen from the data" — np.array(new[] {"ab", "c"}, np.str_) is
<U2, and an allocation with no data to measure (np.zeros(3, np.str_)) is <U1.
public static readonly DType str_
Field Value
ubyte
public static readonly DType ubyte
Field Value
uint
public static readonly DType @uint
Field Value
uint0
NumPy 1.x's np.uint0 (an alias of np.uintp): the uint64 descriptor, uintp's width
on a 64-bit host. Kept on purpose, so code written against NumPy 1.x compiles and runs unchanged, although
NumPy 1.24 deprecated the name and NumPy 2.0 removed it (np.uint0 raises
AttributeError: module 'numpy' has no attribute 'uint0'). New code writes uintp or
uint64.
public static readonly DType uint0
Field Value
Remarks
Only the member is kept: the dtype STRING follows NumPy 2.x, so np.dtype("uint0") raises NumPy's
Alias 'uint0' was removed in NumPy 2.0. Use a name without a digit at the end.
uint16
public static readonly DType uint16
Field Value
uint32
public static readonly DType uint32
Field Value
uint64
public static readonly DType uint64
Field Value
uint8
public static readonly DType uint8
Field Value
uintc
public static readonly DType uintc
Field Value
uintp
public static readonly DType uintp
Field Value
ulong
public static readonly DType @ulong
Field Value
ulonglong
numpy.ulonglong (C unsigned long long, char 'Q'): its own class on Linux and macOS, uint64 on Windows (see longlong).
public static readonly DType ulonglong
Field Value
ushort
public static readonly DType @ushort
Field Value
Properties
BackendEngine
public static BackendType BackendEngine { get; set; }
Property Value
False_
public static bool False_ { get; }
Property Value
Inf
public static double Inf { get; }
Property Value
Infinity
public static double Infinity { get; }
Property Value
NAN
public static double NAN { get; }
Property Value
NINF
public static double NINF { get; }
Property Value
NaN
public static double NaN { get; }
Property Value
PINF
public static double PINF { get; }
Property Value
ScalarType
numpy.ScalarType: every scalar class NumPy knows, as one read-only list — Python's int,
float, complex, bool, bytes, str and memoryview first, then each class
of NumPy's sctypeDict once, sorted by kind and item size the way NumPy sorts them (31 classes on Windows:
[int, float, complex, bool, bytes, str, memoryview, numpy.bool, numpy.complex64, numpy.complex128,
numpy.clongdouble, numpy.float16, …, numpy.uint64, numpy.void]).
public static IReadOnlyList<NDScalarType> ScalarType { get; }
Property Value
Remarks
NumPy's construction, reproduced: ScalarType = [int, float, complex, bool, bytes, str, memoryview] +
sorted(dict.fromkeys(sctypeDict.values()), key=lambda t: (dtype(t).kind.lower(), dtype(t).itemsize)) — a
STABLE sort, so classes of one kind and size keep their sctypeDict order (intc before
int32 on Windows). The classes NumSharp has no dtype for (complex64, object_,
void) are in it, as in NumPy; NumSharp's own decimal and char classes are not (they are no NumPy
name). The C-integer classes follow the host's C long: Windows lists intc and int32,
Linux int64 and longlong.
A port of isinstance(x, np.ScalarType) is np.ScalarType.Any(t => t.__instancecheck__(x)), and of
type(x) in np.ScalarType a membership test of the class (NDScalarTypes compare by identity).
True_
numpy.True_: NumPy's bool scalar True. NumSharp's bool scalar is the C# bool, so
this is true (the same rule as nan being a double).
public static bool True_ { get; }
Property Value
c_
Builds arrays by stacking columns — see np.CClass.
public static np.CClass c_ { get; }
Property Value
Remarks
char
NumPy's numpy.char module (CharModule): np.char.equal(a, b) is spelled
np.@char.equal(a, b), since char is a C# keyword. The object also converts implicitly to the
Char dtype descriptor this field held before the module existed, so every DType use of
np.@char — astype(np.@char), a.dtype == np.@char, a DType[] initializer, a
(DType, DType) tuple key — keeps compiling and keeps its meaning.
public static CharModule @char { get; }
Property Value
Remarks
What changed for a DType user. The member's TYPE is now CharModule, so code that reads
a descriptor member straight off it (np.@char.itemsize) or compares references
(ReferenceEquals(x, np.@char)) must convert first: ((DType)np.@char).itemsize. Boxing it to
object boxes the module, not the descriptor.
https://numpy.org/doc/stable/reference/routines.char.html
character
numpy.character: the fixed-width string classes bytes_ and str_.
public static NDScalarType character { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises Converting .np.character to a dtype is not allowed
chars
public static DType chars { get; }
Property Value
complex64
numpy.complex64 (two float32 parts): a class under complexfloating with no NumSharp dtype —
NumSharp's one complex width is complex128. Type tests work (np.issubdtype(np.complex64,
np.inexact) is True, np.isdtype(np.complex64, "complex floating") True), np.finfo(np.complex64)
is float32's, and np.dtype(np.complex64) raises NotSupportedException.
public static NDScalarType complex64 { get; }
Property Value
Remarks
np.zeros(3, np.complex64) does not compile: a class converts to a descriptor only explicitly, and
NumSharp cannot allocate complex64 storage. Use complex128.
complexfloating
numpy.complexfloating: complex128 (NumSharp has no complex64).
public static NDScalarType complexfloating { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises Converting np.complex to a dtype is not allowed.
csingle
numpy.csingle: NumPy's other name for complex64 — the same class object.
public static NDScalarType csingle { get; }
Property Value
e
public static double e { get; }
Property Value
emath
Mathematical functions with automatic domain — the port of Python's
numpy.emath module (a.k.a. numpy.lib.scimath). Accessed exactly like Python:
np.emath.sqrt(-1), np.emath.log(-1), np.emath.arccos(2), etc. Mirrors
the fft / random facade shape (a lowercase property returning a
module object whose methods are the functions).
public static EmathModule emath { get; }
Property Value
Remarks
https://numpy.org/doc/stable/reference/routines.emath.html
These are the branch-cut-aware siblings of the ordinary np.* functions: where
sqrt(NDArray, NDArray, NDArray, DType) returns nan for a negative real
input, sqrt(NDArray) returns the mathematically valid complex value
(np.emath.sqrt(-1) == 1j). The promotion is a WHOLE-ARRAY decision — if ANY element is
out of the real-valued domain, the ENTIRE array is promoted to complex128 before the standard
ufunc runs — matching NumPy's _fix_real_lt_zero / _fix_real_abs_gt_1 exactly.
euler_gamma
public static double euler_gamma { get; }
Property Value
fft
Discrete Fourier Transform namespace — the port of Python's numpy.fft module.
Accessed exactly like Python: np.fft.fft(x), np.fft.rfft(x),
np.fft.fftfreq(n), etc. Mirrors the random facade shape (a lowercase
property returning a module object whose methods are the functions).
public static FourierModule fft { get; }
Property Value
Remarks
flexible
numpy.flexible: the classes whose instances carry a length — the string classes (under character) and void.
public static NDScalarType flexible { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises Converting (NumPy's text for both classes).np.generic to a dtype is not allowed.
floating
numpy.floating: float16, float32, float64, and NumSharp's decimal.
public static NDScalarType floating { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises Converting .np.inexact or np.floating to a dtype not allowed
generic
numpy.generic: the base of every NumPy scalar class — np.issubdtype(x, np.generic) holds for
every dtype.
public static NDScalarType generic { get; }
Property Value
Remarks
Abstract: np.dtype(np.generic) raises NumPy's TypeError (Converting ).np.generic to a dtype is not allowed.
index_exp
NumPy's always-a-tuple twin of s_. Identical in C# — see np.IndexExpression for why.
public static np.IndexExpression index_exp { get; }
Property Value
Remarks
inexact
numpy.inexact: the floating-point and complex classes (the dtypes with a np.finfo).
public static NDScalarType inexact { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises Converting .np.inexact or np.floating to a dtype not allowed
inf
public static double inf { get; }
Property Value
infinity
public static double infinity { get; }
Property Value
infty
public static double infty { get; }
Property Value
integer
numpy.integer: the signed and unsigned integer classes — NumPy's most common type test,
np.issubdtype(a.dtype, np.integer). timedelta64 is an integer (a signed integer with a unit); bool is
not.
public static NDScalarType integer { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises Converting 'np.integer' or 'np.signedinteger' to a dtype is not allowed.
little_endian
NumPy's np.little_endian: whether this machine stores multi-byte numbers least-significant byte first,
which decides what a native byte order ('=') means for a dtype (< here, > on a
big-endian host). Reads IsLittleEndian.
public static bool little_endian { get; }
Property Value
Remarks
Every platform .NET runs NumSharp on today is little-endian (x64, Arm64, WebAssembly), so this is
true in practice. It describes the PROCESS, not an array: an array's byte order is its dtype's
(byteorder), and a non-native one ('>f8') stays non-native whatever this says.
https://numpy.org/doc/stable/reference/generated/numpy.little_endian.html
ma
Masked-array namespace — the port of Python's numpy.ma module. Accessed exactly like
Python: np.ma.add(a, b), np.ma.abs(a), np.ma.sqrt(a), etc. Mirrors the
fft/random facade shape (a lowercase property returning a module
object whose methods are the functions).
A NDMaskedArray pairs an ordinary NDArray of DATA with a boolean
NDArray MASK (True = "this element is invalid / ignore it"). The masked ufuncs
here do NOT re-implement arithmetic: exactly like NumPy they call the underlying
np.* ufunc on the raw data and only propagate the mask around it, so every layout,
dtype, promotion rule and SIMD/IL kernel of the base op is inherited for free.
public static MaskedArrayModule ma { get; }
Property Value
Remarks
mgrid
Returns a dense multi-dimensional "meshgrid" when indexed — see np.MGridClass.
public static np.MGridClass mgrid { get; }
Property Value
Remarks
nan
public static double nan { get; }
Property Value
number
numpy.number: every numeric class — the integers, floats and complex numbers. bool is NOT a number in
NumPy 2.x (np.issubdtype(np.bool_, np.number) is False).
public static NDScalarType number { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises NumPy's Converting (NumPy's own text names those two classes for np.inexact or np.floating to a dtype not allowednp.number too).
object_
numpy.object_: a class directly under generic with no NumSharp dtype (NumSharp has no
arrays of Python objects); np.dtype(np.object_) raises NotSupportedException.
public static NDScalarType object_ { get; }
Property Value
ogrid
Returns an open multi-dimensional "meshgrid" when indexed — see np.OGridClass.
public static np.OGridClass ogrid { get; }
Property Value
Remarks
pi
public static double pi { get; }
Property Value
polynomial
The numpy.polynomial package: power, Chebyshev, Legendre, Laguerre and both Hermite series,
each as a submodule with NumPy's names — var C = np.polynomial.chebyshev; is the port of
from numpy.polynomial import chebyshev as C.
public static PolynomialModule polynomial { get; }
Property Value
Remarks
Coefficient order: every function of this package takes its coefficients LOW degree
first (c[0] + c[1]*x + …). The legacy polyval(NDArray, NDArray) family takes
them HIGH degree first and its arguments in the other order — the two are different functions that
happen to share names.
https://numpy.org/doc/stable/reference/routines.polynomials-package.html
r_
Builds arrays by concatenating along the first axis — see np.RClass.
public static np.RClass r_ { get; }
Property Value
Remarks
random
public static NumPyRandom random { get; }
Property Value
s_
Builds reusable index tuples: np.s_["2::2"] returns the index itself rather than
applying it, so it can be stored and handed to arr[…] later.
public static np.IndexExpression s_ { get; }
Property Value
Examples
var every2nd = np.s_["2::2"];
np.array(new[] {0, 1, 2, 3, 4})[every2nd]; // array([2, 4])
Remarks
sctypeDict
numpy.sctypeDict: every name NumPy resolves to a scalar class, mapped to NumSharp's spelling of that
class — the dtype descriptor (np.sctypeDict["float64"] is float64 itself, as NumPy's is
np.float64), so a value can be passed as dtype= directly or tested with
np.issubdtype(value, np.floating).
public static IReadOnlyDictionary<string, DType> sctypeDict { get; }
Property Value
Remarks
Keys in NumPy 2.4.2's order for the host's C long model (the C integer names: Windows lists
intc, uintc, int32, long, …, Linux int32, intc, uint32, uintc, …), values resolved on this
platform: "long" / "ulong" follow the C long (32-bit on Windows, 64-bit on LP64 Linux and
macOS), "intp", "int_", "int", "uintp" and "uint" the pointer size. Linux
NumPy's "float128" / "complex256" (its 16-byte long double) are absent: NumSharp's long double
is 8 bytes, as on Windows.
The string names map to the UNSIZED string descriptors, the objects bytes_ and
str_ are ("bytes_", "bytes" to dtype('S'); "str_",
"str", "unicode" to dtype('<U')), as NumPy's np.dtype(np.sctypeDict["str"]) is.
Differences from NumPy, all from NumSharp's dtype set: the names of the classes NumSharp has no dtype for are
absent (complex64, csingle, void, object_, object) — the values here are
descriptors, and those classes (complex64, object_, void) have none.
The C-type names map to their own classes, as in NumPy ("longdouble" is longdouble,
equal to but not the class of float64; "intc" is intc, its own class on
Windows). "datetime64" / "timedelta64" map to the generic-unit descriptors
(dtype('<M8'), the object np.dtype("M") returns). Read-only, for the reason
typecodes is; a missing key — NumPy 2.5's removed 'a' included — raises NumPy's
KeyError ('a').
signedinteger
numpy.signedinteger: int8, int16, int32, int64 and timedelta64.
public static NDScalarType signedinteger { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises Converting 'np.integer' or 'np.signedinteger' to a dtype is not allowed.
typecodes
numpy.typecodes: NumPy's one-character type codes by group, verbatim —
{'Character': 'c', 'Integer': 'bhilqnp', 'UnsignedInteger': 'BHILQNP', 'Float': 'efdg', 'Complex': 'FDG',
'AllInteger': 'bBhHiIlLqQnNpP', 'AllFloat': 'efdgFDG', 'Datetime': 'Mm', 'All': '?bhilqnpBHILQNPefdgFDGSUVOMm'},
in that order. Use it the way NumPy code does: np.typecodes["AllFloat"].Contains(a.dtype.@char).
public static IReadOnlyDictionary<string, string> typecodes { get; }
Property Value
Remarks
The strings are NumPy's and describe NumPy's codes, including the ones NumSharp has no dtype for (F,
V, O). Read-only, where NumPy's is a plain dict: the table is shared process-wide, and a write
would change every reader's answer. A missing key raises NumPy's KeyError ('x'), as the
dict does.
unsignedinteger
numpy.unsignedinteger: uint8, uint16, uint32, uint64, and NumSharp's char (stored as a 16-bit unsigned integer).
public static NDScalarType unsignedinteger { get; }
Property Value
Remarks
Abstract: converting it to a dtype raises Converting .np.unsignedinteger to a dtype is not allowed
void
numpy.void: a class under flexible with no NumSharp dtype (NumSharp has no raw-byte or
structured arrays); np.dtype(np.void) raises NotSupportedException.
public static NDScalarType @void { get; }
Property Value
Methods
abs(NDArray, NDArray, NDArray, DType)
Calculate the absolute value element-wise (alias of absolute(NDArray, NDArray, NDArray, DType)).
Mirrors NumPy's ufunc signature: absolute(x, /, out=None, *, where=True, dtype=None).
public static NDArray abs(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput value.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the input must be same_kind-castable to it; for complex input it selects the magnitude dtype (float kinds only).
Returns
- NDArray
The absolute value of each element, in the input's dtype (a complex input gives its float magnitude), or
outitself when given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.absolute.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.abs(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.abs(x))</code>), as for every other ufunc.</p>
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.).
absolute(NDArray, NDArray, NDArray, DType)
Calculate the absolute value element-wise.
Mirrors NumPy's ufunc signature: absolute(x, /, out=None, *, where=True, dtype=None).
public static NDArray absolute(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput value.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the input must be same_kind-castable to it; for complex input it selects the magnitude dtype (float kinds only).
Returns
- NDArray
The absolute value of each element, in the input's dtype (a complex input gives its float magnitude), or
outitself when given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.absolute.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.absolute(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.absolute(x))</code>), as for every other ufunc.</p>
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.).
acos(NDArray, NDArray, NDArray, DType)
Trigonometric inverse cosine, element-wise (NumPy's np.acos,
the Array-API name NumPy 2.0 added: np.acos is np.arccos, the
same ufunc object, so this forwards to arccos(NDArray, NDArray, NDArray, DType) and answers bit for bit as it does).
public static NDArray acos(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array (a C# scalar converts to a 0-d array marked as the Python scalar it stands for).
outNDArrayA location into which the result is stored (NumPy ufunc
out=);nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=);nullis NumPy'swhere=True.dtypeDTypeThe loop dtype (NumPy ufunc
dtype=); only non-integer dtypes have a loop.
Returns
- NDArray
The result of arccos(NDArray, NDArray, NDArray, DType):
outitself when it was given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.acos.html
<p>One signature, the ufunc form of the original's; the original's own extra overloads (if any) are not
copied, so the alias never carries a second overload.</p>
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.).
acosh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic cosine, element-wise (Array-API alias of arccosh(NDArray, NDArray, NDArray, DType), added in NumPy 2.0).
public static NDArray acosh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
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.).
add(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray add(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayx2NDArrayoutNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDType
Returns
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).
all(NDArray)
Test whether all array elements evaluate to True.
public static bool all(NDArray a)
Parameters
aNDArrayInput array or object that can be converted to an array.
Returns
- bool
True if all elements evaluate to True (non-zero); True for an empty array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.all.html — the reduction is the engine's
(TensorEngine.All). The C# bool of NumPy's np.all(a) (its np.bool
scalar), kept beside the axis signature below as C# programs read it (if (np.all(mask))); with
any argument after a C# binds the axis signature, whose answer is an array.
Exceptions
- ArgumentNullException
ais null.- SystemError
A
Uarray holding a unit above U+10FFFF (NumPy's bool cast of the text).
all(NDArray, int, NDArray, bool, NDArray)
all(NDArray, NDAxis?, NDArray, bool, NDArray) with the axis as one int: the
overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray all(NDArray a, int axis, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array (any dtype; a text element is true when non-empty).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayNumPy's
out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an intoutstores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.all(a, 0, true)) is NumPy'sTypeError: return arrays must be of ArrayType: writekeepdims: true.keepdimsboolIf True, the reduced axes are left as dimensions with size one, so the result broadcasts against
a.whereNDArrayNumPy's
where=: a bool mask that broadcasts TOa's shape. Elements where it is False are left out of the reduction (they count as True, the identity ofall). A mask of any other dtype raises, as in NumPy. Null for no mask.
Returns
- NDArray
outitself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (anNDArray<bool>instance:AsGeneric<bool>()gives the typed view), read-only when 0-d (NumPy'snp.boolscalar). Anumpy.matrixoperand gives NumPy'smatrix.allanswer: the scalar without an axis, otherwise a matrix that keeps the reduced axes with length one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.all.html
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
out= overloads and the three typed NDArray<bool> forms ((nd, int axis, keepdims),
(nd, int[] axis, keepdims), (nd, bool keepdims)). The typed forms could not return NumPy's
answer for an out of another dtype or for a matrix operand (they returned a plain
array); np.all(a, null) was ambiguous (CS0121). A former np.all(a, 0, true) (keepdims)
now binds out and raises NumPy's TypeError: name the keyword.
Exceptions
- ArgumentNullException
ais null.- ValueError
outis read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts);wherehas more axes thanaor would makeastretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).- ArgumentException
whereis not a bool array (NumPy'sTypeErrortext: the mask must cast to bool under thesaferule).- AxisError
An axis is out of bounds (the first one in order, as given).
- IncorrectShapeException
whereoroutdoes not broadcast againsta.- TypeError
outis a C# scalar (return arrays must be of ArrayType); anumpy.matrixoperand withkeepdims: trueor a mask: NumPy calls the matrix method, which has no such keyword (matrix.all() got an unexpected keyword argument 'keepdims'), or with anout(Cannot construct a dtype from an array).- SystemError
A
Uarray holding a unit above U+10FFFF.
all(NDArray, int[], NDArray, bool, NDArray)
all(NDArray, NDAxis?, NDArray, bool, NDArray) with the axes as an int[]: the
overload an int[] binds, and a bare null too (null converts to int[] better than to
NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple
(new int[0] is ()).
public static NDArray all(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array (any dtype; a text element is true when non-empty).
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayNumPy's
out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an intoutstores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.all(a, 0, true)) is NumPy'sTypeError: return arrays must be of ArrayType: writekeepdims: true.keepdimsboolIf True, the reduced axes are left as dimensions with size one, so the result broadcasts against
a.whereNDArrayNumPy's
where=: a bool mask that broadcasts TOa's shape. Elements where it is False are left out of the reduction (they count as True, the identity ofall). A mask of any other dtype raises, as in NumPy. Null for no mask.
Returns
- NDArray
outitself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (anNDArray<bool>instance:AsGeneric<bool>()gives the typed view), read-only when 0-d (NumPy'snp.boolscalar). Anumpy.matrixoperand gives NumPy'smatrix.allanswer: the scalar without an axis, otherwise a matrix that keeps the reduced axes with length one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.all.html
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
out= overloads and the three typed NDArray<bool> forms ((nd, int axis, keepdims),
(nd, int[] axis, keepdims), (nd, bool keepdims)). The typed forms could not return NumPy's
answer for an out of another dtype or for a matrix operand (they returned a plain
array); np.all(a, null) was ambiguous (CS0121). A former np.all(a, 0, true) (keepdims)
now binds out and raises NumPy's TypeError: name the keyword.
Exceptions
- ArgumentNullException
ais null.- ValueError
outis read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts);wherehas more axes thanaor would makeastretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).- ArgumentException
whereis not a bool array (NumPy'sTypeErrortext: the mask must cast to bool under thesaferule).- AxisError
An axis is out of bounds (the first one in order, as given).
- IncorrectShapeException
whereoroutdoes not broadcast againsta.- TypeError
outis a C# scalar (return arrays must be of ArrayType); anumpy.matrixoperand withkeepdims: trueor a mask: NumPy calls the matrix method, which has no such keyword (matrix.all() got an unexpected keyword argument 'keepdims'), or with anout(Cannot construct a dtype from an array).- SystemError
A
Uarray holding a unit above U+10FFFF.
all(NDArray, NDAxis?, NDArray, bool, NDArray)
NumPy's np.all(a, axis=None, out=None, keepdims=False, *, where=True): whether every element evaluates to True
along the given axes (every axis by default), as NumPy's
np.logical_and.reduce(a, axis, bool, out, keepdims=keepdims, where=where).
public static NDArray all(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array (any dtype; a text element is true when non-empty).
axisNDAxis?NumPy's
axis:null(None, the default) reduces every axis; one axis (0,-1) reduces that axis; a tuple ((0, 2)ornew[] { 0, 2 }) reduces each of its axes, and the empty tuple reduces none (the truth values ina's shape). Negative axes count from the end. A 0-datakes the integer axis 0 or -1 (the ufunc reduction's special case) and the empty tuple.outNDArrayNumPy's
out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an intoutstores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.all(a, 0, true)) is NumPy'sTypeError: return arrays must be of ArrayType: writekeepdims: true.keepdimsboolIf True, the reduced axes are left as dimensions with size one, so the result broadcasts against
a.whereNDArrayNumPy's
where=: a bool mask that broadcasts TOa's shape. Elements where it is False are left out of the reduction (they count as True, the identity ofall). A mask of any other dtype raises, as in NumPy. Null for no mask.
Returns
- NDArray
outitself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (anNDArray<bool>instance:AsGeneric<bool>()gives the typed view), read-only when 0-d (NumPy'snp.boolscalar). Anumpy.matrixoperand gives NumPy'smatrix.allanswer: the scalar without an axis, otherwise a matrix that keeps the reduced axes with length one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.all.html
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
out= overloads and the three typed NDArray<bool> forms ((nd, int axis, keepdims),
(nd, int[] axis, keepdims), (nd, bool keepdims)). The typed forms could not return NumPy's
answer for an out of another dtype or for a matrix operand (they returned a plain
array); np.all(a, null) was ambiguous (CS0121). A former np.all(a, 0, true) (keepdims)
now binds out and raises NumPy's TypeError: name the keyword.
Exceptions
- ArgumentNullException
ais null.- ValueError
outis read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts);wherehas more axes thanaor would makeastretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).- ArgumentException
whereis not a bool array (NumPy'sTypeErrortext: the mask must cast to bool under thesaferule).- AxisError
An axis is out of bounds (the first one in order, as given).
- IncorrectShapeException
whereoroutdoes not broadcast againsta.- TypeError
outis a C# scalar (return arrays must be of ArrayType); anumpy.matrixoperand withkeepdims: trueor a mask: NumPy calls the matrix method, which has no such keyword (matrix.all() got an unexpected keyword argument 'keepdims'), or with anout(Cannot construct a dtype from an array).- SystemError
A
Uarray holding a unit above U+10FFFF.
allclose(NDArray, NDArray, double, double, bool)
Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers.The
relative difference (rtol * abs(b)) and the absolute difference
atol are added together to compare against the absolute difference
between a and b.
If either array contains one or more NaNs, False is returned.
Infs are treated as equal if they are in the same place and of the same
sign in both arrays.
public static bool allclose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
Parameters
aNDArrayInput array to compare with b
bNDArrayInput array to compare with a.
rtoldoubleThe relative tolerance parameter(see Notes)
atoldoubleThe absolute tolerance parameter(see Notes)
equal_nanboolWhether to compare NaN's as equal. If True, NaN's in
awill be considered equal to NaN's inbin the output array.
Returns
amax(NDArray, int, NDArray, bool, object, NDArray)
amax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axis as one int:
the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray amax(NDArray a, int axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayThe array the result is written into and returned (any dtype; a narrowing one is lossy, see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the third positional parameter, so
np.amax(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null; requiresinitial.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer (see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)).
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.max() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.
amax(NDArray, int[], NDArray, bool, object, NDArray)
amax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static NDArray amax(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates.
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayThe array the result is written into and returned (any dtype; a narrowing one is lossy, see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the third positional parameter, so
np.amax(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null; requiresinitial.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer (see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)).
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.max() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.
amax(NDArray, NDAxis?, NDArray, bool, object, NDArray)
Return the maximum of an array or the maximum along an axis — NumPy's np.amax, an alias of
max(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the same signature (NumPy's
(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)).
This is the only overload.
public static NDArray amax(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates.
axisNDAxis?The axis to reduce (negative counts from the end), or
nullfor every axis. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).outNDArrayThe array the result is written into and returned (any dtype; a narrowing one is lossy, see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the third positional parameter, so
np.amax(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null; requiresinitial.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer (see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)).
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.max() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.
amin(NDArray, int, NDArray, bool, object, NDArray)
amin(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axis as one int:
the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray amin(NDArray a, int axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.amin(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null.whereNDArrayA bool mask of the elements to reduce, or
null; requiresinitial.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer (see min(NDArray, NDAxis?, NDArray, bool, object, NDArray)).
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See min(NDArray, NDAxis?, NDArray, bool, object, NDArray). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.
amin(NDArray, int[], NDArray, bool, object, NDArray)
amin(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static NDArray amin(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates.
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.amin(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null.whereNDArrayA bool mask of the elements to reduce, or
null; requiresinitial.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer (see min(NDArray, NDAxis?, NDArray, bool, object, NDArray)).
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See min(NDArray, NDAxis?, NDArray, bool, object, NDArray). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.
amin(NDArray, NDAxis?, NDArray, bool, object, NDArray)
Return the minimum of an array or the minimum along an axis — NumPy's np.amin, an alias of
min(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the same signature (NumPy's
(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)).
This is the only overload.
public static NDArray amin(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates.
axisNDAxis?The axis to reduce (negative counts from the end), or
nullfor every axis. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.amin(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null.whereNDArrayA bool mask of the elements to reduce, or
null; requiresinitial.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer (see min(NDArray, NDAxis?, NDArray, bool, object, NDArray)).
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See min(NDArray, NDAxis?, NDArray, bool, object, NDArray). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.
angle(NDArray, bool)
Return the angle (phase) of the complex argument, element-wise — the counterclockwise angle
from the positive real axis, in the range (-pi, pi]. One of the four basic complex-number
accessors (with real(NDArray), imag(NDArray) and conjugate(NDArray, NDArray, NDArray, DType)) — the
standard post-FFT PHASE spectrum: for A = np.fft.fft(a), np.angle(A) is the
phase spectrum.
public static NDArray angle(NDArray z, bool deg = false)
Parameters
zNDArrayA complex number or sequence of complex numbers (any real dtype is also accepted).
degboolReturn the angle in degrees if
true, radians (default) iffalse.
Returns
- NDArray
The phase angle, computed as
arctan2(imag, real)element-wise (so it follows the arctan2(NDArray, NDArray, NDArray, NDArray, DType) IEEE conventions at magnitude zero and at the infinities). complex128 -> float64. A REAL input yields0for a positive value andpifor a negative one (arctan2(0, z)), with NumPy's per-dtype float tier: bool/int32+/float64/complex -> float64, int8/uint8/float16 -> float16, int16/uint16/float32 -> float32.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.angle.html. The facade only calls the engine's Angle(NDArray, bool), NumPy's body (the ufunc mechanism answers for a subclass operand).
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.).- TypeError
Text:
arctan2has no string loop (NumPy's no-loop text forStringDType, the legacy resolver's text forS/U).
any(NDArray)
Test whether any array element evaluates to True.
public static bool any(NDArray a)
Parameters
aNDArrayInput array or object that can be converted to an array.
Returns
- bool
True if any element evaluates to True (non-zero); False for an empty array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.any.html — the reduction is the engine's
(TensorEngine.Any). The C# bool of NumPy's np.any(a) (its np.bool
scalar), kept beside the axis signature below as C# programs read it (if (np.any(mask))); with
any argument after a C# binds the axis signature, whose answer is an array.
Exceptions
- ArgumentNullException
ais null.- SystemError
A
Uarray holding a unit above U+10FFFF (NumPy's bool cast of the text).
any(NDArray, int, NDArray, bool, NDArray)
any(NDArray, NDAxis?, NDArray, bool, NDArray) with the axis as one int: the
overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray any(NDArray a, int axis, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array (any dtype; a text element is true when non-empty).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayNumPy's
out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an intoutstores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.any(a, 0, true)) is NumPy'sTypeError: return arrays must be of ArrayType: writekeepdims: true.keepdimsboolIf True, the reduced axes are left as dimensions with size one, so the result broadcasts against
a.whereNDArrayNumPy's
where=: a bool mask that broadcasts TOa's shape. Elements where it is False are left out of the reduction (they count as False, the identity ofany). A mask of any other dtype raises, as in NumPy. Null for no mask.
Returns
- NDArray
outitself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (anNDArray<bool>instance:AsGeneric<bool>()gives the typed view), read-only when 0-d (NumPy'snp.boolscalar). Anumpy.matrixoperand gives NumPy'smatrix.anyanswer: the scalar without an axis, otherwise a matrix that keeps the reduced axes with length one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.any.html
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
out= overloads and the three typed NDArray<bool> forms ((nd, int axis, keepdims),
(nd, int[] axis, keepdims), (nd, bool keepdims)). The typed forms could not return NumPy's
answer for an out of another dtype or for a matrix operand (they returned a plain
array); np.any(a, null) was ambiguous (CS0121). A former np.any(a, 0, true) (keepdims)
now binds out and raises NumPy's TypeError: name the keyword.
Exceptions
- ArgumentNullException
ais null.- ValueError
outis read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts);wherehas more axes thanaor would makeastretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).- ArgumentException
whereis not a bool array (NumPy'sTypeErrortext: the mask must cast to bool under thesaferule).- AxisError
An axis is out of bounds (the first one in order, as given).
- IncorrectShapeException
whereoroutdoes not broadcast againsta.- TypeError
outis a C# scalar (return arrays must be of ArrayType); anumpy.matrixoperand withkeepdims: trueor a mask: NumPy calls the matrix method, which has no such keyword (matrix.any() got an unexpected keyword argument 'keepdims'), or with anout(Cannot construct a dtype from an array).- SystemError
A
Uarray holding a unit above U+10FFFF.
any(NDArray, int[], NDArray, bool, NDArray)
any(NDArray, NDAxis?, NDArray, bool, NDArray) with the axes as an int[]: the
overload an int[] binds, and a bare null too (null converts to int[] better than to
NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple
(new int[0] is ()).
public static NDArray any(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array (any dtype; a text element is true when non-empty).
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayNumPy's
out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an intoutstores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.any(a, 0, true)) is NumPy'sTypeError: return arrays must be of ArrayType: writekeepdims: true.keepdimsboolIf True, the reduced axes are left as dimensions with size one, so the result broadcasts against
a.whereNDArrayNumPy's
where=: a bool mask that broadcasts TOa's shape. Elements where it is False are left out of the reduction (they count as False, the identity ofany). A mask of any other dtype raises, as in NumPy. Null for no mask.
Returns
- NDArray
outitself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (anNDArray<bool>instance:AsGeneric<bool>()gives the typed view), read-only when 0-d (NumPy'snp.boolscalar). Anumpy.matrixoperand gives NumPy'smatrix.anyanswer: the scalar without an axis, otherwise a matrix that keeps the reduced axes with length one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.any.html
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
out= overloads and the three typed NDArray<bool> forms ((nd, int axis, keepdims),
(nd, int[] axis, keepdims), (nd, bool keepdims)). The typed forms could not return NumPy's
answer for an out of another dtype or for a matrix operand (they returned a plain
array); np.any(a, null) was ambiguous (CS0121). A former np.any(a, 0, true) (keepdims)
now binds out and raises NumPy's TypeError: name the keyword.
Exceptions
- ArgumentNullException
ais null.- ValueError
outis read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts);wherehas more axes thanaor would makeastretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).- ArgumentException
whereis not a bool array (NumPy'sTypeErrortext: the mask must cast to bool under thesaferule).- AxisError
An axis is out of bounds (the first one in order, as given).
- IncorrectShapeException
whereoroutdoes not broadcast againsta.- TypeError
outis a C# scalar (return arrays must be of ArrayType); anumpy.matrixoperand withkeepdims: trueor a mask: NumPy calls the matrix method, which has no such keyword (matrix.any() got an unexpected keyword argument 'keepdims'), or with anout(Cannot construct a dtype from an array).- SystemError
A
Uarray holding a unit above U+10FFFF.
any(NDArray, NDAxis?, NDArray, bool, NDArray)
NumPy's np.any(a, axis=None, out=None, keepdims=False, *, where=True): whether any element evaluates to True
along the given axes (every axis by default), as NumPy's
np.logical_or.reduce(a, axis, bool, out, keepdims=keepdims, where=where).
public static NDArray any(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array (any dtype; a text element is true when non-empty).
axisNDAxis?NumPy's
axis:null(None, the default) reduces every axis; one axis (0,-1) reduces that axis; a tuple ((0, 2)ornew[] { 0, 2 }) reduces each of its axes, and the empty tuple reduces none (the truth values ina's shape). Negative axes count from the end. A 0-datakes the integer axis 0 or -1 (the ufunc reduction's special case) and the empty tuple.outNDArrayNumPy's
out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an intoutstores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.any(a, 0, true)) is NumPy'sTypeError: return arrays must be of ArrayType: writekeepdims: true.keepdimsboolIf True, the reduced axes are left as dimensions with size one, so the result broadcasts against
a.whereNDArrayNumPy's
where=: a bool mask that broadcasts TOa's shape. Elements where it is False are left out of the reduction (they count as False, the identity ofany). A mask of any other dtype raises, as in NumPy. Null for no mask.
Returns
- NDArray
outitself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (anNDArray<bool>instance:AsGeneric<bool>()gives the typed view), read-only when 0-d (NumPy'snp.boolscalar). Anumpy.matrixoperand gives NumPy'smatrix.anyanswer: the scalar without an axis, otherwise a matrix that keeps the reduced axes with length one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.any.html
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
out= overloads and the three typed NDArray<bool> forms ((nd, int axis, keepdims),
(nd, int[] axis, keepdims), (nd, bool keepdims)). The typed forms could not return NumPy's
answer for an out of another dtype or for a matrix operand (they returned a plain
array); np.any(a, null) was ambiguous (CS0121). A former np.any(a, 0, true) (keepdims)
now binds out and raises NumPy's TypeError: name the keyword.
Exceptions
- ArgumentNullException
ais null.- ValueError
outis read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts);wherehas more axes thanaor would makeastretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).- ArgumentException
whereis not a bool array (NumPy'sTypeErrortext: the mask must cast to bool under thesaferule).- AxisError
An axis is out of bounds (the first one in order, as given).
- IncorrectShapeException
whereoroutdoes not broadcast againsta.- TypeError
outis a C# scalar (return arrays must be of ArrayType); anumpy.matrixoperand withkeepdims: trueor a mask: NumPy calls the matrix method, which has no such keyword (matrix.any() got an unexpected keyword argument 'keepdims'), or with anout(Cannot construct a dtype from an array).- SystemError
A
Uarray holding a unit above U+10FFFF.
append(NDArray, NDArray, int?)
Append values to the end of arr.
public static NDArray append(NDArray arr, NDArray values, int? axis = null)
Parameters
arrNDArrayInput array (a C# number is NumPy's Python number: see the remarks).
valuesNDArrayValues to append: an array, a C# array (its own dtype), or a C# number, bool or string (NumPy's Python scalar). Shape must match
arron all dimensions exceptaxiswhenaxisis given; otherwise it is flattened.axisint?Axis along which to append.
null(default) flattens botharrandvaluesto 1-D before concatenation.
Returns
- NDArray
A new array with
valuesappended toarralongaxis: a plain array fornumpy.char.chararrayoperands too (NumPy'snp.concatenatedrops the class).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.append.html
NumPy's statements are the array object's (NDArray.append), which releases the raveled copies
(or views) of a multi-dimensional arr or values, exceptions included,
and yields the concatenated result. A 1-D input is passed to concatenate as-is.
A C# number is NumPy's Python number. NumPy's asanyarray(arr) and ravel(values)
build an ARRAY of a Python scalar, in the Python number's default dtype - int64 (uint64 past the int64
range), float64, complex128 - whatever the C# width of the literal: np.append(int32_array, 5) and
np.append(uint8_array, 300) are int64, np.append(float32_array, 1.5f) float64. A bool stays
bool and a string is its U array, as in NumPy. A typed value keeps its dtype: pass
np.array(new byte[] { 3 }) to append a uint8.
API-parity batch 12: one signature. The object values overload is removed (a C# array, number or
string binds this one through the implicit conversions; a List is passed as
np.array(list)), and the C# number's dtype is NumPy's (it was the C# width: int32 for 5).
Exceptions
- ArgumentNullException
arrorvaluesis null.- 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 0-d input with an axis (zero-dimensional arrays cannot be concatenated).- AxisError
axisis out of range for the inputs' rank.- IncorrectShapeException
With an axis, the inputs' ranks or other axes differ.
- InvalidCastException
An input that does not cast to the result dtype.
apply_along_axis(Func<NDArray, NDArray>, int, NDArray)
Applies func1d to each 1-D slice of arr taken
along axis, then reassembles the results. The FIRST slice's result
fixes the output dtype and the block of new dimensions that REPLACE axis:
a scalar-returning func drops the axis (one fewer dimension), a 1-D-returning func
keeps the rank, a higher-D func inserts those dimensions in the axis' place. So the
output shape is arr.shape[:axis] + func_result.shape + arr.shape[axis+1:].
public static NDArray apply_along_axis(Func<NDArray, NDArray> func1d, int axis, NDArray arr)
Parameters
func1dFunc<NDArray, NDArray>Applied to each 1-D slice; must accept a 1-D NDArray and return an NDArray (a scalar result is a 0-d array). Called once per slice in logical C-order over the non-axis dimensions. Every call is expected to return the same shape and dtype as the first — a differing result is broadcast and unsafe-cast into the first result's slot (NumPy's
buff[ind] = ressemantics), so a shape that cannot broadcast raises.axisintAxis of
arrto slice along; negative counts from the end. The slice handed tofunc1dis one-dimensional with lengtharr.shape[axis].arrNDArrayInput array, of any rank (≥ 1) and any memory layout.
Returns
- NDArray
A freshly allocated array holding the reassembled results, with the first result's dtype - NumPy's
asanyarrayof it, so a TEXT SCALAR result (an elementv[0]of a<U5slice,np.sumof a StringDType slice) gives an array as wide as that first value (<U1for'3') and later, longer results are truncated to it, as in NumPy. The result is a transposed view over a fresh contiguous buffer (as in NumPy), so it does not own its data (flags.owndatais False).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.apply_along_axis.html
Ownership. Every array func1d returns — and every slice handed to
it — stays the CALLER's: this method copies each result into its own buffer and never disposes
one, because a callback may return an array it keeps using (the slice itself, a held constant).
A func1d that ALLOCATES a fresh result per slice therefore leaves those to a
GC — run the call inside an NDScope (yielding the result) when deterministic
release matters. This method's own buffer and views are released before it returns.
Exceptions
- ArgumentNullException
func1dorarris null.- AxisError
axisis out of bounds forarr's rank (reports the original axis).- ValueError
Any non-axis (iteration) dimension is zero —
"Cannot apply_along_axis when any iteration dimensions are 0", verbatim with NumPy — because there is then no first slice to determine the result shape.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
apply_along_axis(Func<NDArray, object[], NDArray>, int, NDArray, params object[])
The *args overload — forwards extra positional arguments to every
func1d call, mirroring NumPy's apply_along_axis(func1d, axis,
arr, *args, **kwargs). Wraps the two-argument delegate into the single-argument
form; a call with no extra arguments passes an empty array, exactly as NumPy passes an
empty *args.
public static NDArray apply_along_axis(Func<NDArray, object[], NDArray> func1d, int axis, NDArray arr, params object[] args)
Parameters
func1dFunc<NDArray, object[], NDArray>Applied as
func1d(slice, args)to each 1-D slice.axisintAxis to slice along; negative counts from the end.
arrNDArrayInput array.
argsobject[]Extra positional arguments forwarded to every
func1dcall.
Returns
- NDArray
See the primary overload.
Remarks
Exceptions
- ArgumentNullException
func1dorarris null.- AxisError
axisis out of bounds forarr's rank.- ValueError
Any iteration dimension is zero.
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
apply_over_axes(Func<NDArray, int, NDArray>, NDArray, NDAxis)
Applies func once per entry of axes, threading
each result into the next call as func(result, axis). Intended for reductions:
func must return an array with either the same rank as its input
(a keepdims-style reduction) or exactly one fewer dimension — in which case the reduced
axis is re-inserted (as size 1) before the next call, so the rank is preserved across
the whole sequence. The result therefore has the SAME number of dimensions as
a, with the sizes along axes collapsed to 1.
public static NDArray apply_over_axes(Func<NDArray, int, NDArray> func, NDArray a, NDAxis axes)
Parameters
funcFunc<NDArray, int, NDArray>Called as
func(current, axis). Must return an NDArray of the input's rank or one less; any other rank raises (see below). A drop of one dimension is the common case (a plain reduction), which this method re-expands for you.aNDArrayInput array.
axesNDAxisNumPy's
axes: one axis or a tuple of axes, applied in order (an int is NumPy's(axes,);()applies nothing and returnsaitself; a repeat appliesfuncagain). Negative axes count from the end usinga's ORIGINAL rank (matching NumPy — the normalization does not track the running result's rank, which the re-expansion keeps equal anyway).
Returns
- NDArray
The array after applying
funcover every axis; same rank asa, sizes alongaxesreduced (typically to 1).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.apply_over_axes.html
Ownership. Every array func returns stays the CALLER's: this method
never disposes one, because a callback may return an array it keeps using. With a reduction that
allocates (np.sum), the intermediate result of each axis but the last is therefore released
only by a GC — run the call inside an NDScope (yielding the final result) when
deterministic release matters. The re-expanded views this method creates are its own and are
released as soon as they are superseded.
One signature for NumPy's int-or-tuple axes since API-parity batch 6; the int and
int[] overloads forward here.
Exceptions
- ArgumentNullException
funcorais null.- ValueError
funcreturns an array whose rank is neither equal to nor exactly one less than its input's, so the reduced axis cannot be re-inserted —"function is not returning an array of the correct shape", verbatim with NumPy.
apply_over_axes(Func<NDArray, int, NDArray>, NDArray, int)
apply_over_axes(Func<NDArray, int, NDArray>, NDArray, NDAxis) with one int axis: the
overload a C# integer binds (NumPy's array(axes).ndim == 0 branch, the 1-tuple), forwarding to the NDAxis
form, so every answer and error is that one's.
public static NDArray apply_over_axes(Func<NDArray, int, NDArray> func, NDArray a, int axes)
Parameters
funcFunc<NDArray, int, NDArray>Called as
func(current, axis); see the NDAxis form.aNDArrayInput array.
axesintThe single axis to apply
funcover; negative counts from the end.
Returns
- NDArray
See the NDAxis form.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.apply_over_axes.html
Ownership. Every array func returns stays the CALLER's: this method
never disposes one, because a callback may return an array it keeps using. With a reduction that
allocates (np.sum), the intermediate result of each axis but the last is therefore released
only by a GC — run the call inside an NDScope (yielding the final result) when
deterministic release matters. The re-expanded views this method creates are its own and are
released as soon as they are superseded.
One signature for NumPy's int-or-tuple axes since API-parity batch 6; the int and
int[] overloads forward here.
Exceptions
- ArgumentNullException
funcorais null.- ValueError
funcreturns an array whose rank is neither equal to nor exactly one less than its input's, so the reduced axis cannot be re-inserted —"function is not returning an array of the correct shape", verbatim with NumPy.
apply_over_axes(Func<NDArray, int, NDArray>, NDArray, int[])
apply_over_axes(Func<NDArray, int, NDArray>, NDArray, NDAxis) with the axes as an
int[]: the overload an int[] (and a bare null) binds, forwarding to the NDAxis form as
NumPy's tuple. NumPy's axes has no None, so a null array throws, as the NDAxis conversion does.
public static NDArray apply_over_axes(Func<NDArray, int, NDArray> func, NDArray a, int[] axes)
Parameters
funcFunc<NDArray, int, NDArray>Called as
func(current, axis); see the NDAxis form.aNDArrayInput array.
axesint[]The axes, in order (not null;
new int[0]applies nothing).
Returns
- NDArray
See the NDAxis form.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.apply_over_axes.html
Ownership. Every array func returns stays the CALLER's: this method
never disposes one, because a callback may return an array it keeps using. With a reduction that
allocates (np.sum), the intermediate result of each axis but the last is therefore released
only by a GC — run the call inside an NDScope (yielding the final result) when
deterministic release matters. The re-expanded views this method creates are its own and are
released as soon as they are superseded.
One signature for NumPy's int-or-tuple axes since API-parity batch 6; the int and
int[] overloads forward here.
Exceptions
- ArgumentNullException
axesis null.- ArgumentNullException
funcorais null.- ValueError
funcreturns an array whose rank is neither equal to nor exactly one less than its input's, so the reduced axis cannot be re-inserted —"function is not returning an array of the correct shape", verbatim with NumPy.
arange(NDArray, NDArray, NDArray, DType, string)
NumPy's np.arange([start,] stop[, step], dtype=None, *, device=None), reading its arguments as NumPy
does: evenly spaced values in the half-open interval [start, stop), in the dtype NumPy discovers from
the arguments themselves.
public static NDArray arange(NDArray start = null, NDArray stop = null, NDArray step = null, DType dtype = null, string device = null)
Parameters
startNDArrayThe start, or with no
stopthe stop (np.arange(5)is[0, 5)). A C# number is the Python number it is written as (afloatis a Python float, aulonga Python int by its value); a NumPy scalar (np.float32(0.1)) or a 0-d array is itself.stopNDArrayThe stop (excluded), or null: then
startis the stop and 0 the start.stepNDArrayThe spacing, or null for 1 (
np.arange(5, step: 2)is[0, 2, 4]).dtypeDTypeThe result dtype, or null for NumPy's discovery: int64 promoted with each argument's own dtype - int64 for Python ints, float64 for a Python float, a float32 scalar or a uint64 value, complex128 for a complex.
devicestringOnly
"cpu"and null are accepted (Array-API parity).
Returns
- NDArray
A new 1-D array; empty when the interval holds no value.
Remarks
NumPy's array_arange then PyArray_ArangeObj
(ArangeObj(NDArray, NDArray, NDArray, DType)): the length is
ceil((stop - start) / step) computed in the arguments' own arithmetic - exact for Python ints, NEP 50
for a NumPy scalar (np.arange(0, 1, np.float32(0.1)) divides in float32) -, the first two elements
are start and start + step stored into the dtype, and the rest start + i * delta in the
dtype's own arithmetic. A complex dtype takes the smaller ceiling of the quotient's two parts
(np.arange(new Complex(1, 2)) is [0j]).
The typed overloads stay beside this one and win for plain C# numbers (np.arange(5),
np.arange(0.0, 1.0, 0.1), np.arange(5, np.float32)), with the same answers for those numbers;
this signature is the one NumPy's keywords reach (step:, device: alone), and the one a NumPy
scalar, a complex or a 0-d array binds. C# cannot tell np.arange(start: 5) from np.arange(5):
both read 5 as the stop, where NumPy raises the TypeError for the keyword form. A C# number argument becomes a
small 0-d array per call.
https://numpy.org/doc/stable/reference/generated/numpy.arange.html
Exceptions
- TypeError
Neither
startnorstopgiven (arange() requires stop to be specified.); a text dtype or a text argument (arange() not supported for inputs with DType ...); bool with more than two elements; a complex interval into a real dtype (must be real number, not complex); an argument with dimensions (only 0-dimensional arrays can be converted to Python scalars).- ZeroDivisionError
A zero Python step (
division by zero,float division by zero,complex division by zero).- ValueError
deviceis not"cpu"; a NaN length (arange: cannot compute length); a length past npy_intp, a NumPy scalar's zero step or a Python int out of a NumPy integer's bounds (Maximum allowed size exceeded); an argument of more than one element or none (NumPy's truth-value texts); an allocation past the byte limit.- OverflowError
The first or second element does not fit
dtype(Python integer 1000 out of bounds for int8).- NotSupportedException
dtypehas no NumSharp storage yet (datetime64, timedelta64).
arange(double)
Return evenly spaced values within a given interval.
public static NDArray arange(double stop)
Parameters
stopdoubleEnd of interval (exclusive).
Returns
- NDArray
Array of evenly spaced double values.
Exceptions
- ValueError
The length is NaN or past npy_intp, or the array is past the byte limit.
arange(double, DType, string)
Return evenly spaced values within a given interval.
public static NDArray arange(double stop, DType dtype, string device = null)
Parameters
stopdoubleEnd of interval (exclusive).
dtypeDTypeThe dtype of the output array (a Type, NPTypeCode, dtype string or DType — all convert implicitly).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of evenly spaced values from 0 to stop-1.
Remarks
Exceptions
- ValueError
deviceis not"cpu"; the length is NaN or past npy_intp; or the array is past the byte limit.- TypeError
dtypeis a text dtype, or bool with more than two elements.- NotSupportedException
dtypehas no NumSharp storage yet (datetime64, timedelta64).
arange(double, double, DType, string)
Return evenly spaced values within a given interval.
public static NDArray arange(double start, double stop, DType dtype, string device = null)
Parameters
startdoubleStart of interval (inclusive).
stopdoubleEnd of interval (exclusive).
dtypeDTypeThe dtype of the output array (a Type, NPTypeCode, dtype string or DType — all convert implicitly).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of evenly spaced values.
Remarks
Exceptions
- ValueError
deviceis not"cpu"; the length is NaN or past npy_intp; or the array is past the byte limit.- TypeError
dtypeis a text dtype, or bool with more than two elements.- OverflowError
startorstart+ 1 does not fit an integer dtype.- NotSupportedException
dtypehas no NumSharp storage yet (datetime64, timedelta64).
arange(double, double, double)
Return evenly spaced values within a given interval.
public static NDArray arange(double start, double stop, double step = 1)
Parameters
startdoubleStart of interval (inclusive).
stopdoubleEnd of interval (exclusive).
stepdoubleSpacing between values. Default is 1.
Returns
- NDArray
Array of evenly spaced double values.
Exceptions
- ValueError
The length is NaN or past npy_intp, or the array is past the byte limit.
- ZeroDivisionError
stepis zero (NumPy'sZeroDivisionError: float division by zero).
arange(double, double, double, DType, string)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop).
public static NDArray arange(double start, double stop, double step, DType dtype, string device = null)
Parameters
startdoubleStart of interval, a Python float. The interval includes this value.
stopdoubleEnd of interval, a Python float. The interval does not include this value.
stepdoubleSpacing between values, a Python float. Default is 1.
dtypeDTypeThe dtype of the output array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. If null, NumPy's discovery from Python floats: float64.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of evenly spaced values.
Remarks
NumPy's PyArray_ArangeObj (ArangeObj(double, double, double, DType)): the
length is ceil((stop - start) / step) in float arithmetic, the first two elements are start and
start + step stored into the dtype, and the rest are start + i * delta computed in the dtype's
own arithmetic, with delta the difference of the two stored elements. So np.arange(0.1, 2, 0.3)[3]
is 1.0000000000000002, a float32 ramp is computed in float32 and a float16 ramp in float32 rounded per
element, as in NumPy; an integer ramp wraps in the dtype past its first two elements.
https://numpy.org/doc/stable/reference/generated/numpy.arange.html
Exceptions
- ValueError
deviceis not"cpu"; the length is NaN (arange: cannot compute length) or past npy_intp (Maximum allowed size exceeded); the array is past the byte limit; or a NaN is stored into an integer dtype.- ZeroDivisionError
stepis zero (NumPy'sZeroDivisionError: float division by zero).- TypeError
dtypeis a text dtype (arange() not supported for inputs with DType ...), or bool with more than two elements.- OverflowError
startorstart+stepdoes not fit an integer dtype (Python integer 300 out of bounds for int8).- NotSupportedException
dtypehas no NumSharp storage yet (datetime64, timedelta64).
arange(int)
Return evenly spaced values within a given interval.
public static NDArray arange(int stop)
Parameters
stopintEnd of interval (exclusive).
Returns
- NDArray
Array of evenly spaced int64 values.
Remarks
NumPy 2.x returns int64 for integer arange.
Exceptions
- ValueError
The array is past the byte limit (
array is too big).
arange(int, int, int)
Return evenly spaced values within a given interval.
public static NDArray arange(int start, int stop, int step = 1)
Parameters
startintStart of interval (inclusive).
stopintEnd of interval (exclusive).
stepintSpacing between values. Default is 1.
Returns
- NDArray
Array of evenly spaced int64 values.
Remarks
NumPy 2.x returns int64 for integer arange.
Exceptions
- ValueError
The array is past the byte limit (
array is too big).- ZeroDivisionError
stepis zero (NumPy'sZeroDivisionError: division by zero).
arange(long)
Return evenly spaced values within a given interval.
public static NDArray arange(long stop)
Parameters
stoplongEnd of interval (exclusive).
Returns
- NDArray
Array of evenly spaced int64 values.
Remarks
NumPy 2.x returns int64 for integer arange.
Exceptions
- ValueError
The array is past the byte limit (
array is too big).
arange(long, long, long)
Return evenly spaced values within a given interval.
public static NDArray arange(long start, long stop, long step = 1)
Parameters
startlongStart of interval (inclusive), a Python int.
stoplongEnd of interval (exclusive), a Python int.
steplongSpacing between values, a Python int. Default is 1.
Returns
- NDArray
Array of evenly spaced int64 values.
Remarks
NumPy 2.x returns int64 for integer arange. NumPy's PyArray_ArangeObj over Python ints
(ArangeObj(long, long, long, DType)): the length is the ceiling of Python's
correctly rounded (stop - start) / step and the elements are exact at every magnitude
(np.arange(260, 260 + 3) has three); a quotient whose ceiling is exactly 2**63 gives an empty
array, as NumPy's on x86.
Exceptions
- ZeroDivisionError
stepis zero (NumPy'sZeroDivisionError: division by zero).- ValueError
The array is past the byte limit (
array is too big).
arange(float)
Return evenly spaced values within a given interval.
public static NDArray arange(float stop)
Parameters
stopfloatEnd of interval (exclusive), a Python float (its exact float32 value).
Returns
- NDArray
Array of evenly spaced float64 values (NumPy's dtype for a float argument).
Remarks
float64 since API-parity batch 13 (parity QA-02), as arange(float, float, float).
Exceptions
- ValueError
The length is NaN or past npy_intp, or the array is past the byte limit.
arange(float, float, float)
Return evenly spaced values within a given interval.
public static NDArray arange(float start, float stop, float step = 1)
Parameters
startfloatStart of interval (inclusive), a Python float (its exact float32 value).
stopfloatEnd of interval (exclusive), a Python float.
stepfloatSpacing between values, a Python float. Default is 1.
Returns
- NDArray
Array of evenly spaced float64 values:
np.arange(0f, 1f, 0.1f)[3]is0.30000000447034836, NumPy'snp.arange(np.float32(0), np.float32(1), np.float32(0.1))[3].
Remarks
A C# float is a Python float in NumSharp's boundary map, and NumPy's dtype for Python floats is float64:
the bounds widen exactly, the length and the elements are the float form's
(ArangeObj(double, double, double, DType)). Until API-parity batch 13 (parity
QA-02) this overload returned float32 computed in float32. For a float32 result pass the dtype:
np.arange(0, 1, 0.1, np.float32).
Exceptions
- ValueError
The length is NaN or past npy_intp, or the array is past the byte limit.
- ZeroDivisionError
stepis zero (NumPy'sZeroDivisionError: float division by zero).
arange(ulong)
Return evenly spaced values within a given interval.
public static NDArray arange(ulong stop)
Parameters
stopulongEnd of interval (exclusive), a Python int (its exact value).
Returns
- NDArray
Array of evenly spaced values: int64 while
stopfits int64, float64 past it (NumPy's dtype for a Python int beyond int64 promoted with int64).
Remarks
Added in API-parity batch 13 so a C# ulong stays a Python int: it bound the float overload, which
rounded it to float32 first.
Exceptions
- ValueError
A length past npy_intp (
Maximum allowed size exceeded), or the array is past the byte limit.
arange(ulong, ulong, ulong)
Return evenly spaced values within a given interval.
public static NDArray arange(ulong start, ulong stop, ulong step = 1)
Parameters
startulongStart of interval (inclusive), a Python int.
stopulongEnd of interval (exclusive), a Python int.
stepulongSpacing between values, a Python int. Default is 1.
Returns
- NDArray
Array of evenly spaced values: int64 while every bound fits int64, else float64 (NumPy:
np.arange(264 - 6, 264 - 1, 2)is three float64 elements).
Remarks
NumPy's PyArray_ArangeObj over Python ints
(ArangeObj(NDArray, NDArray, NDArray, DType)): the length from exact integer
arithmetic, the dtype from the values (a value past long.MaxValue is uint64 in NumPy's discovery, and
uint64 with int64 is float64). Added in API-parity batch 13 so a C# ulong stays a Python int (it bound
the float overload, whose float32 rounding made np.arange(18446744073709551610UL, 18446744073709551615UL,
2UL) empty). A negative step needs a signed overload: -1 is no ulong.
Exceptions
- ZeroDivisionError
stepis zero (division by zero).- ValueError
A length past npy_intp (
Maximum allowed size exceeded), or the array is past the byte limit.
arccos(NDArray, NDArray, NDArray, DType)
Trigonometric inverse cosine, element-wise.
The inverse of cos so that, if y = cos(x), then x = arccos(y).
public static NDArray arccos(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar.
Remarks
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.).
arccosh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic cosine, element-wise.
The inverse of cosh so that, if y = cosh(x), then x = arccosh(y).
Mirrors NumPy's ufunc signature: arccosh(x, /, out=None, *, where=True, dtype=None).
public static NDArray arccosh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
Array of the same shape as x. This is a scalar if x is a scalar.
Remarks
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.).
arcsin(NDArray, NDArray, NDArray, DType)
Inverse sine, element-wise.
The convention is to return the angle z whose real part lies in [-pi/2, pi/2].
public static NDArray arcsin(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar.
Remarks
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.).
arcsinh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic sine, element-wise.
The inverse of sinh so that, if y = sinh(x), then x = arcsinh(y).
Mirrors NumPy's ufunc signature: arcsinh(x, /, out=None, *, where=True, dtype=None).
public static NDArray arcsinh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
Array of the same shape as x. This is a scalar if x is a scalar.
Remarks
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.).
arctan(NDArray, NDArray, NDArray, DType)
Compute trigonometric inverse tangent, element-wise.
The inverse of tan, so that if y = tan(x) then x = arctan(y).
public static NDArray arctan(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
Return has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar.
Remarks
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.).
arctan2(NDArray, NDArray, NDArray, NDArray, DType)
Compute Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf
public static NDArray arctan2(NDArray y, NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
yNDArrayThe y-coordinates (NumPy's
x1).xNDArrayThe x-coordinates (NumPy's
x2). Ify.shape != x.shape, they must be broadcastable to a common shape (which becomes the shape of the output).outNDArrayA location into which the result is stored (NumPy ufunc out=);
nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.
Remarks
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.).
arctanh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic tangent, element-wise.
The inverse of tanh so that, if y = tanh(x), then x = arctanh(y).
Mirrors NumPy's ufunc signature: arctanh(x, /, out=None, *, where=True, dtype=None).
public static NDArray arctanh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
Array of the same shape as x. This is a scalar if x is a scalar.
Remarks
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.).
are_broadcastable(NDArray, NDArray)
Tests if these two two arrays are broadcastable against each other.
public static bool are_broadcastable(NDArray lhs, NDArray rhs)
Parameters
Returns
- bool
True if these can be broadcasted against each other.
Remarks
are_broadcastable(params NDArray[])
Tests if these two two arrays are broadcastable against each other.
public static bool are_broadcastable(params NDArray[] ndArrays)
Parameters
ndArraysNDArray[]The arrays to test for broadcasting.
Returns
- bool
True if these can be broadcasted against each other.
Remarks
are_broadcastable(params Shape[])
Tests if these two two arrays are broadcastable against each other.
public static bool are_broadcastable(params Shape[] shapes)
Parameters
shapesShape[]The shapes to test for broadcasting.
Returns
- bool
True if these can be broadcasted against each other.
Remarks
are_broadcastable(params int[][])
Tests if these two two arrays are broadcastable against each other.
public static bool are_broadcastable(params int[][] shapes)
Parameters
shapesint[][]The shapes to test for broadcasting.
Returns
- bool
True if these can be broadcasted against each other.
Remarks
are_broadcastable(long[], long[])
Tests if these two shapes are broadcastable against each other.
public static bool are_broadcastable(long[] shape1, long[] shape2)
Parameters
Returns
- bool
True if these can be broadcasted against each other.
Remarks
argmax(NDArray)
Returns the index of the maximum value.
public static long argmax(NDArray a)
Parameters
aNDArrayInput array.
Returns
- long
Index of the maximum value in the flattened array.
Remarks
Exceptions
- ValueError
A
numpy.char.chararrayoperand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.
argmax(NDArray, NDAxis?, NDArray, bool)
NumPy's np.argmax(a, axis=None, out=None, *, keepdims=False): the int64 indices of the
maximum values along axis (the first occurrence), or of the C-order flattened array.
public static NDArray argmax(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput array (any dtype, fixed-width text included: compared as NumPy's
STRING_argmax/UNICODE_argmaxcompare it).axisNDAxis?The axis along which to operate, or null (the default) for the flattened array. NumPy's axis type, but ONE axis: a tuple is NumPy's TypeError (np.argmax takes no axis set).
outNDArrayIf provided, the indices are written into this array and the SAME instance is returned: its shape must equal the result's exactly, and its dtype must be bool or an integer that casts safely to int64 (bool through uint32); the int64 indices are then cast into it unsafely, as NumPy writes them.
keepdimsboolIf true, the reduced axis is left in the result with length one (with
axisnull, every axis: the shape(1,) * a.ndim).
Returns
- NDArray
The int64 indices (a 0-d array for the flattened form without
keepdims), orout.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.argmax.html
The order of NumPy's checks (_PyArray_ArgMinMaxCommon): the axis, the empty length, then the out, all
before an element is compared — so an out error comes before a StringDType comparison's refusal
(until 0.80.0 NumSharp compared the text first).
Exceptions
- AxisError
axisis outside the input's rank (rank 1 for a 0-d input, which NumPy ravels first).- ValueError
The reduced length is 0 (
attempt to get argmax of an empty sequence), oroutdoes not have the result's shape (output array does not match result of np.argmax.).- TypeError
out's dtype does not cast safely to int64 (uint64, floats, complex, text).- ValueError
A
StringDTypeline of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy'sCannot compare null that is not a nan-like value).- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ValueError
A
numpy.char.chararrayoperand withoutout: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; withoutthe indices are written.- ArgumentNullException
ais null.- TypeError
axisis a tuple ('tuple' object cannot be interpreted as an integer, the empty tuple and a one-axis tuple included), raised before anything else is looked at; oroutis a C# scalar converted to a 0-d array (output must be an array): the third positional parameter is out=, sonp.argmax(a, 0, true)raises - writekeepdims: trueby name.
argmax(NDArray, int?, NDArray, bool)
argmax(NDArray, NDAxis?, NDArray, bool) with the axis as an int?: the overload a C#
integer, an int?, a bare null and default bind (NumPy's axis here is ONE integer,
so there is no int[] form, and null / default stay None), forwarding to the NDAxis
form, so every answer and error is that overload's.
public static NDArray argmax(NDArray a, int? axis, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput array (any dtype, fixed-width text included: compared as NumPy's
STRING_argmax/UNICODE_argmaxcompare it).axisint?The axis, or
nullfor the flattened array.outNDArrayIf provided, the indices are written into this array and the SAME instance is returned: its shape must equal the result's exactly, and its dtype must be bool or an integer that casts safely to int64 (bool through uint32); the int64 indices are then cast into it unsafely, as NumPy writes them.
keepdimsboolIf true, the reduced axis is left in the result with length one (with
axisnull, every axis: the shape(1,) * a.ndim).
Returns
- NDArray
The int64 indices (a 0-d array for the flattened form without
keepdims), orout.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.argmax.html
The order of NumPy's checks (_PyArray_ArgMinMaxCommon): the axis, the empty length, then the out, all
before an element is compared — so an out error comes before a StringDType comparison's refusal
(until 0.80.0 NumSharp compared the text first).
Exceptions
- AxisError
axisis outside the input's rank (rank 1 for a 0-d input, which NumPy ravels first).- ValueError
The reduced length is 0 (
attempt to get argmax of an empty sequence), oroutdoes not have the result's shape (output array does not match result of np.argmax.).- TypeError
out's dtype does not cast safely to int64 (uint64, floats, complex, text).- ValueError
A
StringDTypeline of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy'sCannot compare null that is not a nan-like value).- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ValueError
A
numpy.char.chararrayoperand withoutout: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; withoutthe indices are written.- ArgumentNullException
ais null.- TypeError
axisis a tuple ('tuple' object cannot be interpreted as an integer, the empty tuple and a one-axis tuple included), raised before anything else is looked at; oroutis a C# scalar converted to a 0-d array (output must be an array): the third positional parameter is out=, sonp.argmax(a, 0, true)raises - writekeepdims: trueby name.
argmin(NDArray)
Returns the index of the minimum value.
public static long argmin(NDArray a)
Parameters
aNDArrayInput array.
Returns
- long
Index of the minimum value in the flattened array.
Remarks
Exceptions
- ValueError
A
numpy.char.chararrayoperand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.
argmin(NDArray, NDAxis?, NDArray, bool)
NumPy's np.argmin(a, axis=None, out=None, *, keepdims=False): the int64 indices of the
minimum values along axis (the first occurrence), or of the C-order flattened array.
public static NDArray argmin(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput array (any dtype, fixed-width text included: compared as NumPy's
STRING_argmin/UNICODE_argmincompare it).axisNDAxis?The axis along which to operate, or null (the default) for the flattened array. NumPy's axis type, but ONE axis: a tuple is NumPy's TypeError (np.argmin takes no axis set).
outNDArrayIf provided, the indices are written into this array and the SAME instance is returned: its shape must equal the result's exactly, and its dtype must be bool or an integer that casts safely to int64 (bool through uint32); the int64 indices are then cast into it unsafely, as NumPy writes them.
keepdimsboolIf true, the reduced axis is left in the result with length one (with
axisnull, every axis: the shape(1,) * a.ndim).
Returns
- NDArray
The int64 indices (a 0-d array for the flattened form without
keepdims), orout.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.argmin.html
The order of NumPy's checks (_PyArray_ArgMinMaxCommon): the axis, the empty length, then the out, all
before an element is compared — so an out error comes before a StringDType comparison's refusal
(until 0.80.0 NumSharp compared the text first).
Exceptions
- AxisError
axisis outside the input's rank (rank 1 for a 0-d input, which NumPy ravels first).- ValueError
The reduced length is 0 (
attempt to get argmin of an empty sequence), oroutdoes not have the result's shape (output array does not match result of np.argmin.).- TypeError
out's dtype does not cast safely to int64 (uint64, floats, complex, text).- ValueError
A
StringDTypeline of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy'sCannot compare null that is not a nan-like value).- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ValueError
A
numpy.char.chararrayoperand withoutout: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; withoutthe indices are written.- ArgumentNullException
ais null.- TypeError
axisis a tuple ('tuple' object cannot be interpreted as an integer, the empty tuple and a one-axis tuple included), raised before anything else is looked at; oroutis a C# scalar converted to a 0-d array (output must be an array): the third positional parameter is out=, sonp.argmin(a, 0, true)raises - writekeepdims: trueby name.
argmin(NDArray, int?, NDArray, bool)
argmin(NDArray, NDAxis?, NDArray, bool) with the axis as an int?: the overload a C#
integer, an int?, a bare null and default bind (NumPy's axis here is ONE integer,
so there is no int[] form, and null / default stay None), forwarding to the NDAxis
form, so every answer and error is that overload's.
public static NDArray argmin(NDArray a, int? axis, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput array (any dtype, fixed-width text included: compared as NumPy's
STRING_argmin/UNICODE_argmincompare it).axisint?The axis, or
nullfor the flattened array.outNDArrayIf provided, the indices are written into this array and the SAME instance is returned: its shape must equal the result's exactly, and its dtype must be bool or an integer that casts safely to int64 (bool through uint32); the int64 indices are then cast into it unsafely, as NumPy writes them.
keepdimsboolIf true, the reduced axis is left in the result with length one (with
axisnull, every axis: the shape(1,) * a.ndim).
Returns
- NDArray
The int64 indices (a 0-d array for the flattened form without
keepdims), orout.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.argmin.html
The order of NumPy's checks (_PyArray_ArgMinMaxCommon): the axis, the empty length, then the out, all
before an element is compared — so an out error comes before a StringDType comparison's refusal
(until 0.80.0 NumSharp compared the text first).
Exceptions
- AxisError
axisis outside the input's rank (rank 1 for a 0-d input, which NumPy ravels first).- ValueError
The reduced length is 0 (
attempt to get argmin of an empty sequence), oroutdoes not have the result's shape (output array does not match result of np.argmin.).- TypeError
out's dtype does not cast safely to int64 (uint64, floats, complex, text).- ValueError
A
StringDTypeline of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy'sCannot compare null that is not a nan-like value).- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ValueError
A
numpy.char.chararrayoperand withoutout: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; withoutthe indices are written.- ArgumentNullException
ais null.- TypeError
axisis a tuple ('tuple' object cannot be interpreted as an integer, the empty tuple and a one-axis tuple included), raised before anything else is looked at; oroutis a C# scalar converted to a 0-d array (output must be an array): the third positional parameter is out=, sonp.argmin(a, 0, true)raises - writekeepdims: trueby name.
argpartition(NDArray, NDArray, int?, string, string)
Indirect partition with the kth indices given as an ARRAY — NumPy's array-kth form (bool kth "Booleans unacceptable as partition index"; non-integer "Partition index must be integer"; >1-D "object too deep for desired array" BEFORE the axis check; uint64 values wrap modulo 2^64 exactly like NumPy's intp cast).
public static NDArray argpartition(NDArray a, NDArray kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
Returns
Remarks
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.).- ValueError
A
numpy.char.chararrayoperand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.- ArgumentNullException
ais null.
argpartition(NDArray, int, int?, string, string)
Perform an indirect partition along the given axis: returns int64 indices of the same
shape that index a along axis in partitioned
order — a[result[kth]] is the element that would sit at kth
in a sorted array (NumPy np.argpartition). The input is only read.
public static NDArray argpartition(NDArray a, int kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayArray to partition indirectly.
kthintElement index to partition by; negative wraps from the end.
axisint?Axis to partition along. -1 (default) = last axis; null flattens first (indices then address the flattened array).
kindstringSelection algorithm — only 'introselect' exists.
orderstringMust stay null (no structured dtypes).
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.argpartition.html
A 0-d input ravels to shape (1,) first — NumPy's arg-side quirk (its axis/kth errors
then report dimension/size 1, and the result is [0]), unlike np.partition which
raises AxisError on 0-d. NaN floats partition to the end (their indices keep encounter
order, the same policy as argsort's NaN tail).
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.).- ValueError
A
numpy.char.chararrayoperand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.- ArgumentNullException
ais null.
argpartition(NDArray, int[], int?, string, string)
Indirect partition around EVERY index in kth at once (NumPy
np.argpartition with a kth sequence). Returns int64 indices; the input is only read.
public static NDArray argpartition(NDArray a, int[] kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
Returns
Remarks
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.).- ValueError
A
numpy.char.chararrayoperand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.- ArgumentNullException
ais null.
argsort(NDArray, int?, string, object, bool?, bool?)
Returns the indices that would sort a along axis (default last;
null flattens). Returns int64 indices. NumPy's
np.argsort(a, axis=-1, kind=None, order=None, *, stable=None, descending=False).
public static NDArray argsort(NDArray a, int? axis = -1, string kind = null, object order = null, bool? stable = null, bool? descending = null)
Parameters
aNDArrayArray to sort.
axisint?Axis to sort along; null sorts the flattened array.
kindstringThe sort algorithm (see argsort(int?, string, object, bool?, bool?)): over text the default and heapsort kinds give NumPy's introsort tie order, the stable kinds the stable one.
orderobjectField names; any value is refused (no NumSharp dtype has fields).
stablebool?True asks for the stable kind; cannot be combined with
kind.descendingbool?NumPy 2.5's
descending: true orders the largest value first, NaN still last, ties in input order for the stable kind and in NumPy's introsort order for the default kind; cannot be combined withkind.
Returns
- NDArray
A fresh, C-contiguous int64 array of indices.
Exceptions
- ValueError
An unknown
kind,kindgiven withstableordescending, or anorder; or anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- AxisError
The axis is out of bounds.
- RuntimeError
A
StringDTypearray sorted descending (unsupported sort kind).- ValueError
A
StringDTypeline of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy'sCannot compare null that is not a nan-like value, raised after the lines before it were sorted).- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
argwhere(NDArray)
Find the indices of array elements that are non-zero, grouped by element.
public static NDArray argwhere(NDArray a)
Parameters
aNDArrayInput array.
Returns
- NDArray
Indices of elements that are non-zero, grouped per element. The result is a 2-D array of shape
(N, a.ndim)whereNis the number of non-zero elements. Each row contains the coordinates of one non-zero element. Result dtype isint64. For 0-d input, returns shape(1, 0)when the value is truthy and(0, 0)otherwise. For empty input of shape(0, d1, ..., dn), returns shape(0, ndim). 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.argwhere.html
Equivalent to np.transpose(np.nonzero(a)) with a special case for 0-d input.
Distinct from nonzero(NDArray) which returns a tuple of column arrays.
around(NDArray, int, NDArray)
Evenly round to the given number of decimals (NumPy's np.around, the documented alias of
round(NDArray, int, NDArray): the same signature and the same result).
public static NDArray around(NDArray a, int decimals = 0, NDArray @out = null)
Parameters
aNDArrayInput array (NumPy's keyword
a; a C# scalar converts to a 0-d array).decimalsintNumber of decimal places to round to (default 0). Half is rounded to even; a negative value rounds to positions left of the decimal point.
outNDArrayA location into which the result is stored; must be the correct shape, returned as-is (out= only — see round(NDArray, int, NDArray)).
Returns
- NDArray
An array of the same dtype as
a, containing the rounded values (NumPy's read-only scalar for a 0-d input);outitself when it was given. The real and imaginary parts of complex numbers are rounded separately.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.around.html
NumPy's signature around(a, decimals=0, out=None), keyword for keyword: the input was x
and a NumSharp-only dtype parameter followed out until 2026-11-11.
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.).
array(NDArray, bool)
Create an array from an existing NDArray. Matches NumPy's default
np.array(a) which always copies (NumPy 2.x: copy=True by default) into a FRESH, WRITEABLE array
laid out in the source's K order — copy(NDArray, char, bool)'s route with order='K', so a
read-only, F-ordered or broadcast source gives a writeable copy that keeps the source's memory order (a
(0, 8)-strided broadcast copies F-contiguous).
public static NDArray array(NDArray nd, bool copy = true)
Parameters
ndNDArraySource array.
copyboolWhen
true(default) the data is copied as described above; whenfalsethe storage is shared (alias), flags included. For "copy only if needed" semantics use asarray(NDArray, DType, char?, bool?, NDArray, string).
Returns
- NDArray
A new array object, a plain array whatever
nd's class (NumPy'ssubok=False). A 0-d source that was built as an explicit 0-d ARRAY (NumSharp.NDArray.IsExplicitZeroDimArray) gives an explicit 0-d array again, as NumPy'snp.array(np.array(2))is a 0-d array; so does the copy of a NumPy scalar (a read-only 0-d array that is no explicit array), asnp.array(np.float64(1.5))is.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Until parity QA-35 the copy was a storage clone that kept the source's flags: a read-only C, F or 0-d source gave a READ-ONLY copy (a write raised "assignment destination is read-only"), and a broadcast source came back C-ordered where NumPy's K-order copy is F-contiguous.
Exceptions
- NullReferenceException
ndisnull.
array(MemoryView, bool)
Create an array from a np.MemoryView (obtained from data) —
the consumer round-trip of ndarray.data. Matches NumPy's np.array(a.data),
which reads the buffer's shape/strides/dtype and (by default) COPIES, preserving the
source's N-D shape and layout. Equivalent to np.array(buffer.obj, copy); a copy is
always writeable, even from a read-only (broadcast) source.
public static NDArray array(np.MemoryView buffer, bool copy = true)
Parameters
buffernp.MemoryViewA np.MemoryView over an array.
copyboolWhen
true(default) the source storage is cloned; whenfalsethe storage is shared (alias).
Returns
Remarks
array(Array, DType, int, bool, char)
Creates an NDArray from an array with an unknown size or dtype.
[SuppressMessage("ReSharper", "InvalidXmlDocComment")]
public static NDArray array(Array array, DType dtype = null, int ndmin = 0, bool copy = true, char order = 'C')
Parameters
arrayArraydtypeDTypendminintSpecifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
copyboolAlways copies if the array is larger than 1-d.
ordercharMemory layout: 'C' (row-major, default), 'F' (column-major), 'A'/'K' (resolved from source).
Returns
Remarks
array(string)
Creates a 0-d fixed-width Unicode array holding value — NumPy's np.array('abc'),
array('abc', dtype='<U3') with shape (). The width is the value's length in code points (a surrogate
pair counts once); an empty value is <U1, NumPy's minimum.
public static NDArray array(string value)
Parameters
valuestringThe text.
Returns
- NDArray
A 0-d
Uarray, marked an explicit ARRAY (NumSharp.NDArray.IsExplicitZeroDimArray): NumPy's ndarray, not annp.str_scalar.
Remarks
Breaking (NumPy parity): this overload used to build a 1-D char vector of the characters.
That conversion remains available as FromString(string) and
np.array(value.ToCharArray()).
The result is an ndarray as np.array('x') is (API-parity batch 12's finding, fixed in batch 13):
np.isscalar(np.array("x")) is False, and a reader of NumPy's scalar / array difference (np.interp's
float() of a fill value, the scalar-type isinstance rule) sees the array NumPy has. A C# string
LITERAL converted implicitly stays NumPy's Python str (NumSharp.NDArray.WasPythonStr).
Exceptions
- ArgumentNullException
valueis null.
array(string, DType)
Creates a 0-d fixed-width string array holding value with the given string dtype —
NumPy's np.array('abc', dtype='U5') / dtype='S'. Under the character dtype
np.dtype("c") a text whose length is not 1 is a sequence, as NumPy reads it: np.array("abc",
np.dtype("c")) is the (3,) |S1 array of its characters.
public static NDArray array(string value, DType dtype)
Parameters
valuestringThe text.
dtypeDTypeA string dtype (
"U","U5","S","c",np.str_,np.bytes_) or null to discover.
Returns
- NDArray
A 0-d
S/Uarray, or the 1-D character array under"c"(0-d for one character); a 0-d result is marked an explicit ARRAY (NumSharp.NDArray.IsExplicitZeroDimArray), NumPy's ndarray.
Exceptions
- ArgumentNullException
valueis null.- UnicodeEncodeError
Non-ASCII text into
S.- ValueError
A numeric dtype and text that does not parse as that number (
could not convert string to float: 'x', NumPy'sint()/float()texts).- OverflowError
An integer text outside an integer dtype's range.
array(string[])
Creates a 1-D fixed-width Unicode array from strArray — NumPy's
np.array(['a', 'bb']), array(['a', 'bb'], dtype='<U2'): the width is the longest value in code
points (at least 1), each element NUL-padded.
public static NDArray array(string[] strArray)
Parameters
strArraystring[]The values. A null entry is Python's
None, which NumPy would only store in anobjectarray, so it is refused here; pass a string dtype through array(Array, DType, int, bool, char) to store it as the text"None".
Returns
- NDArray
The
Uarray.
Remarks
Breaking (NumPy parity): this overload used to encode the strings into a char vector
("N l1 l2:contents"), read back by the NDArray.AsStringArray layout parser.
Exceptions
- ArgumentNullException
strArrayis null.- NotSupportedException
An entry is null.
array2string(NDArray, int?, int?, bool?, string, string, int?, int?, char?, string, string)
Return a string representation of an array (NumPy's np.array2string).
public static string array2string(NDArray a, int? max_line_width = null, int? precision = null, bool? suppress_small = null, string separator = " ", string prefix = "", int? threshold = null, int? edgeitems = null, char? sign = null, string floatmode = null, string suffix = "")
Parameters
aNDArrayInput array.
max_line_widthint?Inserts newlines if text is longer than this. Defaults to the current linewidth.
precisionint?Floating point precision. Defaults to the current precision.
suppress_smallbool?Represent numbers very close to zero as zero. Defaults to the current option.
separatorstringInserted between elements (default " ").
prefixstringUsed to align/wrap the output; its content is not included.
thresholdint?Total number of elements which trigger summarization.
edgeitemsint?Number of items at the beginning and end of each dimension in summary.
signchar?'-', '+', or ' '.
floatmodestringOne of "fixed", "unique", "maxprec", "maxprec_equal".
suffixstringUsed to wrap the output; its content is not included.
Returns
Remarks
array_equal(NDArray, NDArray, bool)
True if two arrays have the same shape and all elements are equal, False otherwise.
public static bool array_equal(NDArray a1, NDArray a2, bool equal_nan = false)
Parameters
a1NDArrayFirst input array (NumPy's keyword
a1).a2NDArraySecond input array (NumPy's keyword
a2).equal_nanboolWhen
false(the NumPy default) NaN never compares equal, so an array that holds a NaN is NOT equal even to itself —np.array_equal(a, a)isfalsewhenever the array contains a NaN. Whentrue, NaNs at matching positions are treated as equal; for a complex dtype a value counts as NaN when EITHER its real or imaginary component is NaN.
Returns
- bool
True if the arrays have identical shape and every element is equal.
Remarks
The shapes must match EXACTLY — unlike array_equiv(NDArray, NDArray) this performs
NO broadcasting. Mirrors numpy.array_equal(a1, a2, equal_nan=False) (NumPy 2.4.2), keyword for
keyword (the operands were a / b until 2026-11-11, so a ported named call did not compile).
https://numpy.org/doc/stable/reference/generated/numpy.array_equal.html
Exceptions
- TypeError
A fixed-width string operand with
equal_nanand two different arrays of one shape (NumPy'sisnanhas no string loop). Without it, two strings of one class compare their text and other string pairs are answered from shape and dtype (a shape mismatch, or noequalloop, is False; empty arrays are True). AStringDTypeoperand compares through its own==(NumPy's NA rules: two different NA objects raise its TypeError) and, withequal_nan, itsisnan(a NaN-like NA is a NaN).
array_equiv(NDArray, NDArray)
True if the inputs are shape consistent and all elements are equal.
public static bool array_equiv(NDArray a1, NDArray a2)
Parameters
Returns
- bool
True if equivalent, False otherwise.
Remarks
"Shape consistent" means the two shapes are either equal or one can be BROADCAST to the
other — the key difference from array_equal(NDArray, NDArray, bool), which
requires an exact shape match. NaN never compares equal (there is no equal_nan
option, matching NumPy), so array_equiv(a, a) is false whenever a1
holds a NaN. Empty inputs of a broadcast-consistent shape are equivalent (all() over the
empty comparison is vacuously true). Mirrors numpy.array_equiv(a1, a2) (NumPy 2.4.2):
it converts both to arrays, checks they broadcast together, then returns
bool((a1 == a2).all()).
https://numpy.org/doc/stable/reference/generated/numpy.array_equiv.html
Exceptions
- TypeError
Two
StringDTypeoperands whose NA objects differ (NumPy's comparison refuses the pair).
array_repr(NDArray, int?, int?, bool?)
Return the string representation of an array (NumPy's np.array_repr): array([1.12, 2.5 ]),
with the dtype appended when it is not implied by the values. Each option given here overrides the
current print options for this one call only.
public static string array_repr(NDArray arr, int? max_line_width = null, int? precision = null, bool? suppress_small = null)
Parameters
arrNDArrayThe array to represent (NumPy's keyword
arr).max_line_widthint?The line width at which the text wraps;
nullkeeps the currentlinewidthprint option (75 by default).precisionint?Floating point precision;
nullkeeps the currentprecisionprint option (8 by default).suppress_smallbool?Represent numbers very close to zero as zero;
nullkeeps the currentsuppressprint option.
Returns
- string
The
reprtext ofarr.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array_repr.html
<p>NumPy's signature <code>array_repr(arr, max_line_width=None, precision=None, suppress_small=None)</code>,
keyword for keyword (the array was <code>a</code> until 2026-11-11, so a ported named call did not
compile).</p>
Exceptions
- ArgumentNullException
arris null.
array_split(NDArray, int, int)
Split an array into multiple sub-arrays.
public static NDArray[] array_split(NDArray ary, int indices_or_sections, int axis = 0)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintThe number of sections (sizes differ by at most one).
axisintThe axis along which to split, default is 0.
Returns
- NDArray[]
The sub-arrays, views into
ary. Anumpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
The only difference between split and array_split is that array_split allows indices_or_sections to be an integer that does not equally divide the axis. https://numpy.org/doc/stable/reference/generated/numpy.array_split.html
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.).- ArgumentNullException
aryis null.- IndexError
axisis out of range ("tuple index out of range": NumPy'sNtotal = ary.shape[axis]runs first).- ValueError
indices_or_sectionsis not positive ("number sections must be larger than 0.").
array_split(NDArray, int[], int)
Split an array into multiple sub-arrays.
public static NDArray[] array_split(NDArray ary, int[] indices, int axis = 0)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indicesint[]The split points along
axis:[2, 3]givesary[:2],ary[2:3],ary[3:]. Each point is clamped as a slice bound (a negative one counts from the end), and unsorted points give empty sub-arrays.axisintThe axis along which to split, default is 0.
Returns
- NDArray[]
indices.Length + 1sub-arrays, views intoary. Anumpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
A numpy.char.chararray operand gives chararrays over the results (NumPy creates them as the
subclass).
Exceptions
- ArgumentNullException
aryis null, orindicesis (checked in that order, before the axis).- IndexError
axisis out of range ("tuple index out of range"; a 0-d array refuses every axis).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
array_split(NDArray, long[], int)
Split an array into multiple sub-arrays.
public static NDArray[] array_split(NDArray ary, long[] indices, int axis = 0)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indiceslong[]The split points along
axis:[2, 3]givesary[:2],ary[2:3],ary[3:]. Each point is clamped as a slice bound (a negative one counts from the end), and unsorted points give empty sub-arrays.axisintThe axis along which to split, default is 0.
Returns
- NDArray[]
indices.Length + 1sub-arrays, views intoary. Anumpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
A numpy.char.chararray operand gives chararrays over the results (NumPy creates them as the
subclass).
Exceptions
- ArgumentNullException
aryis null, orindicesis (checked in that order, before the axis).- IndexError
axisis out of range ("tuple index out of range"; a 0-d array refuses every axis).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
array_str(NDArray, int?, int?, bool?)
Return a string representation of the data in an array (NumPy's np.array_str).
public static string array_str(NDArray a, int? max_line_width = null, int? precision = null, bool? suppress_small = null)
Parameters
Returns
Remarks
array<T>(IEnumerable<T>)
Creates a Vector NDArray from given data.
public static NDArray array<T>(IEnumerable<T> data) where T : unmanaged
Parameters
dataIEnumerable<T>The enumeration of data to create NDArray from.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
array<T>(IEnumerable<T>, int)
Creates a vector of exactly size elements, the first size items
of data: NumPy's np.fromiter(data, dtype=T, count=size). Use it to read a
known number of items from a long or endless sequence; an enumeration that holds fewer items is an
error, not a shorter array.
public static NDArray array<T>(IEnumerable<T> data, int size) where T : unmanaged
Parameters
dataIEnumerable<T>The enumeration to read. It is enumerated once, and at most
sizeitems are taken from it (MoveNextis calledsizetimes when it holds that many).sizeintThe number of items to read, and the result's length.
Returns
- NDArray
A fresh 1-D array of
sizeelements.
Type Parameters
TThe element type, one of NumSharp's dtypes; the result's dtype.
Remarks
See array<T>(IEnumerable<T>, long), which this overload calls.
Exceptions
- ValueError
dataholds fewer thansizeitems (NumPy's text,iterator too short: Expected 5 but iterator had only 2 items.), orsizeis negative (negative dimensions are not allowed).- NullReferenceException
datais null.
array<T>(IEnumerable<T>, long)
Creates a vector of exactly size elements, the first size items
of data: NumPy's np.fromiter(data, dtype=T, count=size). Use it to read a
known number of items from a long or endless sequence; an enumeration that holds fewer items is an
error, not a shorter array.
public static NDArray array<T>(IEnumerable<T> data, long size) where T : unmanaged
Parameters
dataIEnumerable<T>The enumeration to read. It is enumerated once, and at most
sizeitems are taken from it (MoveNextis calledsizetimes when it holds that many).sizelongThe number of items to read, and the result's length.
Returns
- NDArray
A fresh 1-D array of
sizeelements.
Type Parameters
TThe element type, one of NumSharp's dtypes; the result's dtype.
Remarks
NumPy's PyArray_FromIter (ctors.c): the array of count elements is allocated
first, one PyIter_Next fills each element and none runs past count (a longer iterator
keeps its remaining items), and an iterator that ends early raises the ValueError above. An
exception the enumeration throws propagates unchanged, as an iterator's error does in NumPy. Either
way the buffer is released before the exception leaves, so a failed call holds no memory.
Until 2026-10-30 a short enumeration returned an array of size elements whose
tail was never written (heap contents).
Not NumPy's: a negative size is refused. NumPy's count=-1 reads every
item, which is array<T>(IEnumerable<T>) here, and its other negative counts return an
empty array without reading.
Exceptions
- ValueError
dataholds fewer thansizeitems (NumPy's text,iterator too short: Expected 5 but iterator had only 2 items.), orsizeis negative (negative dimensions are not allowed).- NullReferenceException
datais null.
array<T>(T)
Creates a scalar (0-dimensional) NDArray from a single value.
public static NDArray array<T>(T scalar) where T : unmanaged
Parameters
scalarTThe scalar value.
Returns
Type Parameters
TThe type of the value, must be compliant to numpy's supported dtypes.
Remarks
NumPy: np.array(42) creates a 0-dimensional array with shape (). https://numpy.org/doc/stable/reference/generated/numpy.array.html
The result is marked as an explicit 0-d ARRAY (NumSharp.NDArray.IsExplicitZeroDimArray), which
one operator reads: matrix * np.array(2) is the product with a 1 x 1 matrix, as in NumPy, and
raises unless the matrix has one column. Use Scalar<T>(T) or a C# number for a
value that must SCALE a matrix; library code that builds a computed scalar must use
Scalar<T>(T) too.
array<T>(T[,,,,,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,], DType)
Creates an NDArray from given data with specified dtype.
public static NDArray array<T>(T[,] data, DType dtype) where T : unmanaged
Parameters
dataT[,]The array to create NDArray from.
dtypeDTypeThe desired dtype for the array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. If different fromT, the data will be cast.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(params T[])
Creates a Vector NDArray from given data.
public static NDArray array<T>(params T[] data) where T : unmanaged
Parameters
dataT[]The array to create NDArray from.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
array<T>(T[], DType)
Creates a Vector NDArray from given data with specified dtype.
public static NDArray array<T>(T[] data, DType dtype) where T : unmanaged
Parameters
dataT[]The array to create NDArray from.
dtypeDTypeThe desired dtype for the array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. If different fromT, the data will be cast.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[] data, bool copy) where T : unmanaged
Parameters
dataT[]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[][])
Creates an NDArray from given data — NumPy's np.array of nested lists:
every row must have the same length.
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public static NDArray array<T>(T[][] data) where T : unmanaged
Parameters
dataT[][]The array to create NDArray from. Its shape is NumPy's discovery (DiscoverJaggedShape(Array)): every row is checked, and no rows at all gives shape
(0,).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
Exceptions
- ValueError
A ragged or null row (NumPy's
setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.): a longer row used to be cut silently and a shorter one to throw IndexOutOfRange (parity QA-45).
array<T>(T[][][])
Creates an NDArray from given data — NumPy's np.array of nested lists:
every child at every level must have its level's length.
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public static NDArray array<T>(T[][][] data) where T : unmanaged
Parameters
dataT[][][]The array to create NDArray from. Its shape is NumPy's discovery (DiscoverJaggedShape(Array)): every child is checked, and the dims end at the first empty level (
[[], []]is(2, 0)).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
Exceptions
- ValueError
A ragged or null child (NumPy's inhomogeneous-shape text, naming the depth the children agreed to).
array<T>(T[][][][])
Creates an NDArray from given data — NumPy's np.array of nested lists:
every child at every level must have its level's length.
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public static NDArray array<T>(T[][][][] data) where T : unmanaged
Parameters
dataT[][][][]The array to create NDArray from. Its shape is NumPy's discovery (DiscoverJaggedShape(Array)): every child is checked, and the dims end at the first empty level.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
Exceptions
- ValueError
A ragged or null child (NumPy's inhomogeneous-shape text, naming the depth the children agreed to).
array<T>(T[][][][][])
Creates an NDArray from given data — NumPy's np.array of nested lists:
every child at every level must have its level's length.
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public static NDArray array<T>(T[][][][][] data) where T : unmanaged
Parameters
dataT[][][][][]The array to create NDArray from. Its shape is NumPy's discovery (DiscoverJaggedShape(Array)): every child is checked, and the dims end at the first empty level.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
Exceptions
- ValueError
A ragged or null child (NumPy's inhomogeneous-shape text, naming the depth the children agreed to).
asanyarray(MemoryView, DType, char?, string, bool?)
Convert a np.MemoryView (obtained from data) to an ndarray, passing ndarray
subclasses through — the consumer round-trip of ndarray.data, NumPy's np.asanyarray(a.data) (a
zero-copy VIEW sharing memory, copying only if a dtype / layout / copy request forces it). Equivalent to
np.asanyarray(a.obj, …).
public static NDArray asanyarray(np.MemoryView a, DType dtype = null, char? order = null, string device = null, bool? copy = null)
Parameters
anp.MemoryViewA np.MemoryView over an array. Null is Python's
None, as for theobjectoverload: C# binds a barenp.asanyarray(null, dtype)HERE (a np.MemoryView is the more specific parameter), so the port of NumPy'snp.asanyarray(None, dtype)must mean the same.dtypeDTypeThe requested dtype; null keeps the source's.
orderchar?'C','F','A'or'K'; null is'K'.devicestringNull or
"cpu".copybool?NumPy's copy mode (see asanyarray(in object, DType, char?, string, bool?)).
Returns
- NDArray
The array the memory view exposes (a view sharing its memory), or a copy when the request forces one.
Remarks
A dedicated overload is required because a np.MemoryView is not otherwise resolvable by the
object converter. Its parameter took NumPy's name a (it was buffer) and its
copy arrived in API-parity batch 8.
Exceptions
- ValueError
An unknown order letter, a device other than
"cpu", orcopyfalse when a copy is needed.- NotSupportedException
ais null anddtypeis null (NumPy's object array).- TypeError
ais null anddtypeis an integer (ordecimal) dtype.
asanyarray(in object, DType, char?, string, bool?)
Convert the input to an ndarray, but pass ndarray subclasses through — NumPy's one signature,
np.asanyarray(a, dtype=None, order=None, *, device=None, copy=None).
public static NDArray asanyarray(in object a, DType dtype = null, char? order = null, string device = null, bool? copy = null)
Parameters
aobjectInput data, in any form that can be converted to an array: scalars, C# arrays and lists (Python lists), tuples, nested object arrays, text, and arrays — an array subclass (NDMatrix, NDCharArray) passes through as its class. Null is Python's
None.dtypeDTypeThe requested dtype; null infers it from
a.orderchar?'C','F','A'or'K'(either case); null is NumPy's None,'K': the operand's own layout is kept.devicestringNull or
"cpu"(the Array-API device; NumPy has no other).copybool?NumPy's copy mode: null (None, the default) copies only when the dtype or layout needs it; true always returns a new array (of the operand's class); false never copies and raises when a copy is needed — always for a scalar, a list or any other non-array input, which must be converted into a new array.
Returns
- NDArray
The array interpretation of
a:aitself when it is an array whose dtype and layout satisfy the request (andcopyis not true), else a new array — ofa's class for a subclass operand.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.asanyarray.html — NumPy's array_asanyarray, over
_array_fromobject_generic with subok.
A null a is Python's None: with a dtype it is the 0-d array NumPy's
np.asanyarray(None, dtype) gives (NaN, nan+nanj, False, 'None', a
StringDType NA object); without one NumPy builds an object array, which NumSharp refuses.
One signature since API-parity batch 8 (2026-11-12): the (a, dtype, device) form without an order
and the (a, dtype, order, device) form whose dtype was required (so np.asanyarray(a, order: 'F')
did not compile) went, and copy arrived. The device moved from the third position to the
fourth.
Exceptions
- ValueError
In NumPy's order:
orderis not one of C, F, A, K (order must be one of 'C', 'F', 'A', or 'K' (got 'X'));deviceis not"cpu";copyis false and a copy is needed (Unable to avoid copy while creating an array as requested.and NumPy's two migration lines); a ragged list; anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- NotSupportedException
ais null anddtypeis null (NumPy's object array).- TypeError
ais null anddtypeis an integer (ordecimal) dtype: Python'sint(None).
asarray(NDArray, DType, char?, bool?, NDArray, string)
Convert the input to an ndarray, matching NumPy 2.x semantics.
If a already satisfies the requested dtype/layout, it is returned as-is — no copy.
public static NDArray asarray(NDArray a, DType dtype = null, char? order = null, bool? copy = null, NDArray like = null, string device = null)
Parameters
aNDArrayInput ndarray. A C# literal (
np.asarray(1000, np.int8), whose 0-d array is marked NumSharp.NDArray.WasPythonLiteral) is NumPy's Python scalar: with adtypeit is packed with NumPy's range checks into a new array, not cast.dtypeDTypeRequested dtype.
nullkeeps the input dtype.orderchar?'C' (row-major), 'F' (column-major), 'A' (any contiguous), 'K' (keep);
null(NumPy'sNone, the default) is 'K'. 'A'/'K' never force a copy on layout grounds.copybool?Tri-state:
null= copy only if needed (default),true= always copy,false= never copy (raises if a copy would be required).likeNDArrayReference array for array-function dispatch — accepted for NumPy parity but has no observable effect in NumSharp.
devicestringTarget device. Only
"cpu"andnullare accepted.
Returns
- NDArray
NDArray with the requested dtype and memory layout. Returns
awhen no copy is needed. Anumpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
Exceptions
- NotSupportedException
ais null (Python'sNone) anddtypeis null: NumPy builds an object array, a dtype NumSharp does not have. With a dtype,Noneis the 0-d array of its setitem value (NaN,nan+nanj,False,'None', aStringDTypeNA object).- ValueError
An unsupported
device(NumPy'sDevice not understood. Only "cpu" is allowed, but received: ...).- ArgumentException
copyisfalseand a copy (or a C# literal's orNone's conversion) is required.- OverflowError
A C# literal out of
dtype's integer range (NumPy's OverflowError texts).- ValueError
A float NaN literal into an integer
dtype.- TypeError
A complex literal into a real
dtype, orNoneinto an integer (ordecimal)dtype.
asarray(MemoryView, DType, char?, bool?, NDArray, string)
Convert a np.MemoryView (obtained from data) to an ndarray —
the consumer round-trip of ndarray.data. Matches NumPy's np.asarray(a.data),
which reads the buffer's shape/strides/dtype and returns a zero-copy VIEW sharing its memory
(copying only if a dtype/layout change forces it), preserving the source's N-D shape and
layout. Equivalent to np.asarray(a.obj, …).
public static NDArray asarray(np.MemoryView a, DType dtype = null, char? order = null, bool? copy = null, NDArray like = null, string device = null)
Parameters
anp.MemoryViewA np.MemoryView over an array.
dtypeDTypeRequested dtype.
nullkeeps the source dtype.orderchar?'C', 'F', 'A', or 'K';
null(NumPy'sNone, the default) is 'K'.copybool?Tri-state copy:
null= if-needed,true= always,false= never (raises).likeNDArrayReference for array-function dispatch — accepted for parity, no effect.
devicestringOnly
"cpu"ornull.
Returns
- NDArray
The array the memory view exposes (a view sharing its memory), or a copy when the dtype / order / copy request forces one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.asarray.html. NumPy's parameter name a since API-parity batch 8 (it was buffer, a name NumPy's asarray refuses as a keyword).
Exceptions
- ArgumentNullException
ais null.- ValueError
An unsupported
device.- ArgumentException
copyisfalseand a copy is required.
asarray(MemoryView, string, char?, bool?, NDArray, string)
Convert a np.MemoryView to an ndarray, taking a NumPy-style dtype string
(e.g. "float32", "<i4"). See
asarray(MemoryView, DType, char?, bool?, NDArray, string).
public static NDArray asarray(np.MemoryView a, string dtype, char? order = null, bool? copy = null, NDArray like = null, string device = null)
Parameters
anp.MemoryViewA np.MemoryView over an array.
dtypestringThe requested dtype as NumPy's dtype string (parsed as
np.dtype(string)does).orderchar?'C', 'F', 'A', or 'K';
null(NumPy'sNone, the default) is 'K'.copybool?Tri-state copy:
null= if-needed,true= always,false= never (raises).likeNDArrayReference for array-function dispatch — accepted for parity, no effect.
devicestringOnly
"cpu"ornull.
Returns
- NDArray
The array the memory view exposes (a view sharing its memory), or a copy when the dtype / order / copy request forces one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.asarray.html. NumPy's parameter name a since API-parity batch 8 (it was buffer, a name NumPy's asarray refuses as a keyword).
Exceptions
- ArgumentNullException
ais null.- TypeError
dtypeis not a dtype string NumPy understands.- ValueError
An unsupported
device.- ArgumentException
copyisfalseand a copy is required.
asarray(string)
NumPy's np.asarray('abc'): a 0-d fixed-width Unicode array holding a (see
array(string)).
public static NDArray asarray(string a)
Parameters
astringThe text.
Returns
- NDArray
A 0-d
Uarray.
Remarks
NumPy's parameter name a since API-parity batch 8 (it was data, a name NumPy's asarray refuses as a keyword).
Exceptions
- ArgumentNullException
ais null.
asarray(string[], int)
NumPy's np.asarray(['a', 'bb']): a 1-D fixed-width Unicode array (see array(string[])).
public static NDArray asarray(string[] a, int ndim = 1)
Parameters
Returns
- NDArray
The
Uarray.
Remarks
NumPy's parameter name a since API-parity batch 8 (it was data, a name NumPy's asarray refuses as a keyword).
Exceptions
- ArgumentNullException
ais null.- NotSupportedException
An entry is null (an
objectarray in NumPy).
asarray_chkfinite(NDArray, DType, char?)
Convert the input to an array, checking for NaNs or Infs.
public static NDArray asarray_chkfinite(NDArray a, DType dtype = null, char? order = null)
Parameters
aNDArrayInput data. No copy is performed if the input is already an ndarray matching the requested dtype/order.
dtypeDTypeBy default, the data-type is inferred from the input data.
orderchar?'C' (row-major), 'F' (column-major), 'A' (any), 'K' (keep);
null(NumPy'sorder=None, the default) is 'K', as NumPy hands None on toasarray.
Returns
- NDArray
Array interpretation of
a. Anumpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
Mirrors NumPy 2.x numpy.asarray_chkfinite(a, dtype=None, order=None): the finiteness
check runs ONLY for float-family dtypes (Half/Single/Double/Complex — NumPy's
typecodes['AllFloat']), since integer, boolean, char and decimal arrays can never
hold inf/NaN. Complex is finite iff both its real and imaginary parts are finite.
https://numpy.org/doc/stable/reference/generated/numpy.asarray_chkfinite.html
Exceptions
- ValueError
If
acontains NaN (Not a Number) or Inf (Infinity).- ArgumentNullException
ais null.
asarray<T>(T)
NumPy's np.asarray(2): a new 0-d array holding one C# value. Like np.array(2), the
result is an explicit 0-d ARRAY (NumSharp.NDArray.IsExplicitZeroDimArray): a matrix multiplied by
it takes NumPy's 1 x 1 matrix route instead of scaling.
public static NDArray asarray<T>(T a) where T : struct
Parameters
aTThe value.
Returns
- NDArray
A new writeable 0-d array that owns its one element.
Type Parameters
TThe value's type; it must map to a NumSharp dtype.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.asarray.html. NumPy's parameter name a since API-parity batch 8 (it was data, a name NumPy's asarray refuses as a keyword).
Exceptions
- NotSupportedException
Thas no NumSharp dtype.
asarray<T>(T[], int)
NumPy's np.asarray([1, 2, 3]) of a C# array of values: a new 1-D array of T's
dtype holding a COPY of a (a C# array is NumPy's Python list, which np.asarray always
converts into a new array).
public static NDArray asarray<T>(T[] a, int ndim = 1) where T : struct
Parameters
aT[]The values (only their count and elements are read: a multi-dimensional C# array binds the NDArray form through its implicit conversion).
ndimintKept for source compatibility; the result is always 1-D.
Returns
- NDArray
A new 1-D array that owns a copy of the values.
Type Parameters
TThe element type; it must map to a NumSharp dtype.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.asarray.html. NumPy's parameter name a since API-parity batch 8 (it was data, a name NumPy's asarray refuses as a keyword).
Exceptions
- NullReferenceException
ais null.- NotSupportedException
Thas no NumSharp dtype.
ascontiguousarray(NDArray, DType)
Return a contiguous array (ndim >= 1) in memory (C order).
public static NDArray ascontiguousarray(NDArray a, DType dtype = null)
Parameters
Returns
- NDArray
Contiguous array of same shape and content as a, with type dtype if specified. A
numpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
ascontiguousarray(MemoryView, DType)
Return a C-contiguous array from a np.MemoryView (obtained from
data) — the consumer round-trip of ndarray.data. Matches NumPy's
np.ascontiguousarray(a.data): a zero-copy VIEW when the source is already C-contiguous,
otherwise a C-order copy. Equivalent to np.ascontiguousarray(a.obj, dtype).
public static NDArray ascontiguousarray(np.MemoryView a, DType dtype = null)
Parameters
anp.MemoryViewA np.MemoryView over an array.
dtypeDTypeBy default, the data-type is inferred from the source.
Returns
- NDArray
The C-contiguous array: a view sharing the source's memory when its layout and dtype already satisfy the request, else a copy.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ascontiguousarray.html. NumPy's parameter name a since API-parity batch 8 (it was buffer, a name NumPy's ascontiguousarray refuses as a keyword).
Exceptions
- ArgumentNullException
ais null.
asfortranarray(NDArray, DType)
Return an array (ndim >= 1) laid out in Fortran order in memory.
public static NDArray asfortranarray(NDArray a, DType dtype = null)
Parameters
Returns
- NDArray
The input a in Fortran, or column-major, order. A
numpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
asfortranarray(MemoryView, DType)
Return a Fortran-ordered array from a np.MemoryView (obtained from
data) — the consumer round-trip of ndarray.data. Matches NumPy's
np.asfortranarray(a.data): a zero-copy VIEW when the source is already F-contiguous,
otherwise an F-order copy. Equivalent to np.asfortranarray(a.obj, dtype).
public static NDArray asfortranarray(np.MemoryView a, DType dtype = null)
Parameters
anp.MemoryViewA np.MemoryView over an array.
dtypeDTypeBy default, the data-type is inferred from the source.
Returns
- NDArray
The F-contiguous array: a view sharing the source's memory when its layout and dtype already satisfy the request, else a copy.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.asfortranarray.html. NumPy's parameter name a since API-parity batch 8 (it was buffer, a name NumPy's asfortranarray refuses as a keyword).
Exceptions
- ArgumentNullException
ais null.
asin(NDArray, NDArray, NDArray, DType)
Inverse sine, element-wise (NumPy's np.asin,
the Array-API name NumPy 2.0 added: np.asin is np.arcsin, the
same ufunc object, so this forwards to arcsin(NDArray, NDArray, NDArray, DType) and answers bit for bit as it does).
public static NDArray asin(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array (a C# scalar converts to a 0-d array marked as the Python scalar it stands for).
outNDArrayA location into which the result is stored (NumPy ufunc
out=);nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=);nullis NumPy'swhere=True.dtypeDTypeThe loop dtype (NumPy ufunc
dtype=); only non-integer dtypes have a loop.
Returns
- NDArray
The result of arcsin(NDArray, NDArray, NDArray, DType):
outitself when it was given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.asin.html
<p>One signature, the ufunc form of the original's; the original's own extra overloads (if any) are not
copied, so the alias never carries a second overload.</p>
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.).
asinh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic sine, element-wise (Array-API alias of arcsinh(NDArray, NDArray, NDArray, DType), added in NumPy 2.0).
public static NDArray asinh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
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.).
asmatrix(NDArray, DType)
Interpret the input as a matrix. Unlike matrix(NDArray, DType, bool),
asmatrix does not copy an array: it returns an NDMatrix VIEW that shares
memory, and a matrix argument is returned itself.
public static NDMatrix asmatrix(NDArray data, DType dtype = null)
Parameters
dataNDArrayInput array.
dtypeDTypeData-type of the output.
nullkeeps the input dtype; another dtype converts, which copies.
Returns
- NDMatrix
datainterpreted as a matrix. A 0-D input becomes shape(1, 1), a 1-D input of length N becomes(1, N), and a 2-D input keeps its shape.
Remarks
Port of NumPy 2.x numpy.asmatrix ≙ matrix(data, dtype=dtype, copy=False). The
dimensional coercion is NumPy's matrix.array_finalize (NumSharp.Shape.AsMatrix()),
including the >2-D behaviour: axes of length 1 are dropped and the result must then be 2-D. The
view is preserved for strided, transposed and reversed inputs (no copy), and it keeps the input's
writeability. The result is an NDMatrix: * is the matrix product on it and it
has .T, .H, .I, .A, .A1; seen through an NDArray
reference it is a plain 2-D array.
https://numpy.org/doc/stable/reference/generated/numpy.asmatrix.html
Exceptions
- ArgumentNullException
dataisnull.- ValueError
More than two axes of
dataare longer than 1 (shape too large to be a matrix.).- IncorrectShapeException
datahas more than two axes and one of extent 0 (NumPy'scannot reshape array of size 0 into shape (1,3)).
asmatrix(Array, DType)
Interpret a C# array as a matrix: a typed array of a NumSharp dtype is converted like
np.array, any other array is a Python list coerced by NumPy's sequence rules. A C# array is
always copied into new memory (as NumPy copies a list).
public static NDMatrix asmatrix(Array data, DType dtype = null)
Parameters
dataArrayThe array, with at most two axes after conversion.
dtypeDTypeData-type of the output, or
nullfor the discovered one.
Returns
- NDMatrix
A new matrix.
Remarks
Exceptions
- ArgumentNullException
dataisnull.- ValueError
More than two axes (
matrix must be 2-dimensional), or a ragged list.- NotSupportedException
A list holding strings,
nullor other objects.
asmatrix(object, DType)
Interpret any other value as a matrix: a tuple or collection (a Python sequence), an array or string held in an object reference, or a boxed number.
public static NDMatrix asmatrix(object data, DType dtype = null)
Parameters
Returns
Remarks
Exceptions
- ArgumentNullException
dataisnull.- ValueError
More than two axes, a ragged sequence, or an array that cannot be a matrix.
- SyntaxError
A matrix literal with a token that is not Python syntax.
- NotSupportedException
Strings or other objects inside a sequence.
asmatrix(string, DType)
Interpret a matrix string as a matrix. Rows are separated by ';' and columns by
commas and/or whitespace, e.g. "1 2; 3 4". Surrounding brackets are ignored. The dtype
is NumPy's discovered dtype (bool, int64, float64 or complex128, by the tokens) unless
dtype is given.
public static NDMatrix asmatrix(string data, DType dtype = null)
Parameters
datastringMatrix string such as
"1 2; 3 4". Each token is one Python literal.dtypeDTypeData-type of the output.
nullinfers it from the values.
Returns
- NDMatrix
A new matrix of shape
(rows, columns);(1, 0)float64 for an empty string.
Remarks
Exceptions
- ArgumentNullException
dataisnull.- ValueError
If the rows are not all the same length (
Rows not the same size.), or a token is Python syntax but not a literal (a name such asnan).- SyntaxError
A token is not Python syntax.
- NotSupportedException
A token is a string,
Noneor..., or an integer beyond uint64.
asscalar(NDArray)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static object asscalar(NDArray nd)
Parameters
ndNDArrayInput NDArray of size 1.
Returns
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
asscalar(Array)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static object asscalar(Array arr)
Parameters
arrArrayInput array of size 1.
Returns
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
asscalar<T>(ArraySlice<T>)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static T asscalar<T>(ArraySlice<T> arr) where T : unmanaged
Parameters
arrArraySlice<T>Input array of size 1.
Returns
- T
Type Parameters
T
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
asscalar<T>(IArraySlice)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static T asscalar<T>(IArraySlice arr) where T : unmanaged
Parameters
arrIArraySliceInput array of size 1.
Returns
- T
Type Parameters
T
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
asscalar<T>(NDArray)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static T asscalar<T>(NDArray nd) where T : unmanaged
Parameters
ndNDArrayInput NDArray of size 1.
Returns
- T
Type Parameters
T
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0. Use NDArray.item() instead: arr.item() or arr.item<T>() https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html
asscalar<T>(Array)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static T asscalar<T>(Array arr)
Parameters
arrArrayInput array of size 1.
Returns
- T
Type Parameters
T
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
astype(NDArray, DType, bool, string)
Copies an array to a specified data type — NumPy 2.1's Array-API function np.astype(x, dtype, /, *,
copy=True, device=None), the function form of astype(DType, char, string, bool).
public static NDArray astype(NDArray x, DType dtype, bool copy = true, string device = null)
Parameters
xNDArrayThe array to cast. NumPy takes an ndarray or a NumPy scalar only (a Python list is its TypeError); the NDArray parameter says so at compile time.
dtypeDTypeThe target dtype — a DType, a C# Type, an NPTypeCode or a dtype string (
"f4") convert implicitly; null is NumPy'sdtype=None, the default float64.copyboolTrue (the default) always returns a new array; false returns
xITSELF when its dtype already isdtype, and a new array otherwise (a cast must copy).devicestringNumPy's Array-API device: null or
"cpu"; anything else is NumPy's ValueError.
Returns
- NDArray
xcast todtypewith the unsafe rule (a float into an int truncates), inx's own layout (the method'sorder='K');xitself for a satisfiedcopy: false. A subclass operand (numpy.matrix) keeps its class, as NumPy'sx.astype(...)dispatch does.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.astype.html — NumPy's body is the two checks, then
x.astype(dtype, copy=copy): the method's defaults order='K' and casting='unsafe' apply, so
this function has neither keyword. Added in API-parity batch 7.
NumPy's method allocates with subok=True, so the result is created as x's class
(np.astype(matrix, float) is a matrix): the cast runs in AsTypeComputation(NDArray, DType, bool), whose
[NewSubtype("x")] tells NumSharp.Build to create a subclass operand's result as its class (the weaver
reads the declaration on the computation the public function calls).
Exceptions
- TypeError
xis null: NumPy'sInput should be a NumPy array or scalar. It is a <class 'NoneType'> instead.- ValueError
deviceis not"cpu":Device not understood. Only "cpu" is allowed, but received: gpu(checked before the cast, as in NumPy).- NotSupportedException
A dtype NumSharp has no storage for (the method's refusal).
atan(NDArray, NDArray, NDArray, DType)
Trigonometric inverse tangent, element-wise (NumPy's np.atan,
the Array-API name NumPy 2.0 added: np.atan is np.arctan, the
same ufunc object, so this forwards to arctan(NDArray, NDArray, NDArray, DType) and answers bit for bit as it does).
public static NDArray atan(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array (a C# scalar converts to a 0-d array marked as the Python scalar it stands for).
outNDArrayA location into which the result is stored (NumPy ufunc
out=);nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=);nullis NumPy'swhere=True.dtypeDTypeThe loop dtype (NumPy ufunc
dtype=); only non-integer dtypes have a loop.
Returns
- NDArray
The result of arctan(NDArray, NDArray, NDArray, DType):
outitself when it was given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.atan.html
<p>One signature, the ufunc form of the original's; the original's own extra overloads (if any) are not
copied, so the alias never carries a second overload.</p>
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.).
atan2(NDArray, NDArray, NDArray, NDArray, DType)
Element-wise arc tangent of y/x choosing the quadrant correctly (NumPy's np.atan2,
the Array-API name NumPy 2.0 added: np.atan2 is np.arctan2, the
same ufunc object, so this forwards to arctan2(NDArray, NDArray, NDArray, NDArray, DType) and
answers bit for bit as it does).
public static NDArray atan2(NDArray y, NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
yNDArrayThe y-coordinates (NumPy's positional
x1).xNDArrayThe x-coordinates (NumPy's positional
x2); broadcast againsty.outNDArrayA location into which the result is stored (NumPy ufunc
out=);nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=);nullis NumPy'swhere=True.dtypeDTypeThe loop dtype (NumPy ufunc
dtype=); only non-integer dtypes have a loop.
Returns
- NDArray
The result of arctan2(NDArray, NDArray, NDArray, NDArray, DType):
outitself when it was given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.atan2.html
<p>One signature, the ufunc form of the original's. A C# literal operand converts to a 0-d array marked as
the Python scalar it stands for, so NEP 50's weak-scalar promotion holds without the original's
<code>object</code> overload (<code>np.atan2(int32_array, 2)</code> stays int32, as NumPy's).</p>
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.).
atanh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic tangent, element-wise (Array-API alias of arctanh(NDArray, NDArray, NDArray, DType), added in NumPy 2.0).
public static NDArray atanh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
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.).
atleast_1d(NDArray)
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
public static NDArray atleast_1d(NDArray arr)
Parameters
arrNDArray
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. A
numpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
atleast_1d(params NDArray[])
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
public static NDArray[] atleast_1d(params NDArray[] arys)
Parameters
arysNDArray[]One or more input arrays.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
Exceptions
- ArgumentNullException
arysis null.
atleast_1d(object)
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
public static NDArray atleast_1d(object arys)
Parameters
arysobjectOne or more input arrays.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.
Remarks
atleast_1d(params object[])
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
public static NDArray[] atleast_1d(params object[] arys)
Parameters
arysobject[]One or more input arrays.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.
Remarks
Exceptions
- ArgumentNullException
arysis null.
atleast_2d(NDArray)
View inputs as arrays with at least two dimensions.
public static NDArray atleast_2d(NDArray arr)
Parameters
arrNDArrayOne or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned. A
numpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
atleast_2d(params NDArray[])
View inputs as arrays with at least two dimensions.
public static NDArray[] atleast_2d(params NDArray[] arys)
Parameters
arysNDArray[]One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
Exceptions
- ArgumentNullException
arysis null.
atleast_2d(object)
View inputs as arrays with at least two dimensions.
public static NDArray atleast_2d(object arys)
Parameters
arysobjectOne or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.
Remarks
atleast_2d(params object[])
View inputs as arrays with at least two dimensions.
public static NDArray[] atleast_2d(params object[] arys)
Parameters
arysobject[]One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.
Remarks
Exceptions
- ArgumentNullException
arysis null.
atleast_3d(NDArray)
View inputs as arrays with at least three dimensions.
public static NDArray atleast_3d(NDArray arr)
Parameters
arrNDArrayThe array.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1). A
numpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
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.).- ArgumentNullException
arris null.
atleast_3d(params NDArray[])
View inputs as arrays with at least three dimensions.
public static NDArray[] atleast_3d(params NDArray[] arys)
Parameters
arysNDArray[]One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1). A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
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.).- ArgumentNullException
arysis null.- NullReferenceException
A null entry.
atleast_3d(object)
View inputs as arrays with at least three dimensions.
public static NDArray atleast_3d(object arys)
Parameters
arysobjectOne or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).
Remarks
atleast_3d(params object[])
View inputs as arrays with at least three dimensions.
public static NDArray[] atleast_3d(params object[] arys)
Parameters
arysobject[]One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).
Remarks
Exceptions
- ArgumentNullException
arysis null.
average(NDArray, int, NDArray, bool, bool)
average(NDArray, NDAxis?, NDArray, bool, bool) with the axis as one int: the overload a
C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so
every answer, error, layout and subclass result is that overload's.
public static np.AverageResult average(NDArray a, int axis, NDArray weights = null, bool returned = false, bool keepdims = false)
Parameters
aNDArrayThe values to average.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).weightsNDArrayThe weights, or null for equal weights (the mean): of
a's shape, or of the averaged axes' extents in the order ofaxis(NumPy transposes an unsorted tuple's weights to the axes' order; thenaxisis required). Anumpy.matrixof weights beside a plain operand computes as a plain array, where NumPy returns a matrix (its weight sum is the matrix method).returnedboolNumPy's
returned: also return the sum of the weights, in the average's dtype and shape (the element count per average without weights) -var (avg, sum_of_weights) = np.average(a, returned: true);.keepdimsboolKeep the averaged axes with length 1, so the result broadcasts against
a.
Returns
- np.AverageResult
An np.AverageResult: the average (float64 for an integer or bool operand, else the common dtype of the operand and the weights; 0-d over every axis; a
numpy.matrixoperand gives the matrix method's answer - the scalar without an axis, otherwise a matrix that keeps the averaged axes with length 1), and withreturnedthe sum of weights (a plain array for a matrix operand too). It converts implicitly to the average's NDArray.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.average.html (NumPy's average, whose body
Average(NDArray, int[], NDArray, bool, bool) runs).
<p>One signature since API-parity batch 4 (2026-11-12): it replaced the <code>int?</code> and <code>int[]</code>
overloads, which made <code>np.average(a, null)</code> ambiguous (CS0121) and had no tuple literal. API-parity batch
11 (the owner's decision 3): NumPy's <code>returned</code> in NumPy's place (before <code>keepdims</code>, which NumPy
takes by keyword only) and the <xref href="NumSharp.np.AverageResult" data-throw-if-not-resolved="false"></xref> return; the NumSharp-only
<code>np.average_returned</code> went.</p>
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of bounds (
axis: axis 2 is out of bounds for array of dimension 2; NumPy names the argument, and checks every axis before the repeat check).- ZeroDivisionError
Weights that sum to zero, or an empty average without weights (NumPy's ZeroDivisionError).
- DTypePromotionError
An operand and weights with no common DType:
StringDTypebeside a number or beside S.- 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 axis that appears twice (repeated axis in); weights not of the averaged axes' extents (axisargumentShape of weights must be consistent with shape of a along specified axis.).- TypeError
A
numpy.matrixoperand withkeepdims: true: NumPy calls the matrix method, which has no such keyword. The text names that method, as inmatrix.sum() got an unexpected keyword argument 'keepdims'fornp.sum. Weights of another shape without an axis (Axis must be specified when shapes of a and weights differ.). Text weights beside a number, or a text operand: NumPy's refusal of the weight sum's text result dtype, or of a text mean.
average(NDArray, int[], NDArray, bool, bool)
average(NDArray, NDAxis?, NDArray, bool, bool) with the axes as an int[]: the overload an
int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new
int[0] is ()).
public static np.AverageResult average(NDArray a, int[] axis, NDArray weights = null, bool returned = false, bool keepdims = false)
Parameters
aNDArrayThe values to average.
axisint[]The axes as NumPy's tuple, or
nullfor None.weightsNDArrayThe weights, or null for equal weights (the mean): of
a's shape, or of the averaged axes' extents in the order ofaxis(NumPy transposes an unsorted tuple's weights to the axes' order; thenaxisis required). Anumpy.matrixof weights beside a plain operand computes as a plain array, where NumPy returns a matrix (its weight sum is the matrix method).returnedboolNumPy's
returned: also return the sum of the weights, in the average's dtype and shape (the element count per average without weights) -var (avg, sum_of_weights) = np.average(a, returned: true);.keepdimsboolKeep the averaged axes with length 1, so the result broadcasts against
a.
Returns
- np.AverageResult
An np.AverageResult: the average (float64 for an integer or bool operand, else the common dtype of the operand and the weights; 0-d over every axis; a
numpy.matrixoperand gives the matrix method's answer - the scalar without an axis, otherwise a matrix that keeps the averaged axes with length 1), and withreturnedthe sum of weights (a plain array for a matrix operand too). It converts implicitly to the average's NDArray.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.average.html (NumPy's average, whose body
Average(NDArray, int[], NDArray, bool, bool) runs).
<p>One signature since API-parity batch 4 (2026-11-12): it replaced the <code>int?</code> and <code>int[]</code>
overloads, which made <code>np.average(a, null)</code> ambiguous (CS0121) and had no tuple literal. API-parity batch
11 (the owner's decision 3): NumPy's <code>returned</code> in NumPy's place (before <code>keepdims</code>, which NumPy
takes by keyword only) and the <xref href="NumSharp.np.AverageResult" data-throw-if-not-resolved="false"></xref> return; the NumSharp-only
<code>np.average_returned</code> went.</p>
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of bounds (
axis: axis 2 is out of bounds for array of dimension 2; NumPy names the argument, and checks every axis before the repeat check).- ZeroDivisionError
Weights that sum to zero, or an empty average without weights (NumPy's ZeroDivisionError).
- DTypePromotionError
An operand and weights with no common DType:
StringDTypebeside a number or beside S.- 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 axis that appears twice (repeated axis in); weights not of the averaged axes' extents (axisargumentShape of weights must be consistent with shape of a along specified axis.).- TypeError
A
numpy.matrixoperand withkeepdims: true: NumPy calls the matrix method, which has no such keyword. The text names that method, as inmatrix.sum() got an unexpected keyword argument 'keepdims'fornp.sum. Weights of another shape without an axis (Axis must be specified when shapes of a and weights differ.). Text weights beside a number, or a text operand: NumPy's refusal of the weight sum's text result dtype, or of a text mean.
average(NDArray, NDAxis?, NDArray, bool, bool)
NumPy's np.average(a, axis=None, weights=None, returned=False, *, keepdims=False): the weighted average
along the given axes, sum(a * weights) / sum(weights), and with returned the sum of
the weights. When weights is null this is the mean over the same axes.
public static np.AverageResult average(NDArray a, NDAxis? axis = null, NDArray weights = null, bool returned = false, bool keepdims = false)
Parameters
aNDArrayThe values to average.
axisNDAxis?NumPy's
axis:null(None, the default) averages every axis; one axis (negative counts from the end) or a tuple ((0, 2),new[] { 0, 2 }) averages those axes, and the empty tuple averages none (a float copy of every element).weightsNDArrayThe weights, or null for equal weights (the mean): of
a's shape, or of the averaged axes' extents in the order ofaxis(NumPy transposes an unsorted tuple's weights to the axes' order; thenaxisis required). Anumpy.matrixof weights beside a plain operand computes as a plain array, where NumPy returns a matrix (its weight sum is the matrix method).returnedboolNumPy's
returned: also return the sum of the weights, in the average's dtype and shape (the element count per average without weights) -var (avg, sum_of_weights) = np.average(a, returned: true);.keepdimsboolKeep the averaged axes with length 1, so the result broadcasts against
a.
Returns
- np.AverageResult
An np.AverageResult: the average (float64 for an integer or bool operand, else the common dtype of the operand and the weights; 0-d over every axis; a
numpy.matrixoperand gives the matrix method's answer - the scalar without an axis, otherwise a matrix that keeps the averaged axes with length 1), and withreturnedthe sum of weights (a plain array for a matrix operand too). It converts implicitly to the average's NDArray.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.average.html (NumPy's average, whose body
Average(NDArray, int[], NDArray, bool, bool) runs).
<p>One signature since API-parity batch 4 (2026-11-12): it replaced the <code>int?</code> and <code>int[]</code>
overloads, which made <code>np.average(a, null)</code> ambiguous (CS0121) and had no tuple literal. API-parity batch
11 (the owner's decision 3): NumPy's <code>returned</code> in NumPy's place (before <code>keepdims</code>, which NumPy
takes by keyword only) and the <xref href="NumSharp.np.AverageResult" data-throw-if-not-resolved="false"></xref> return; the NumSharp-only
<code>np.average_returned</code> went.</p>
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of bounds (
axis: axis 2 is out of bounds for array of dimension 2; NumPy names the argument, and checks every axis before the repeat check).- ZeroDivisionError
Weights that sum to zero, or an empty average without weights (NumPy's ZeroDivisionError).
- DTypePromotionError
An operand and weights with no common DType:
StringDTypebeside a number or beside S.- 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 axis that appears twice (repeated axis in); weights not of the averaged axes' extents (axisargumentShape of weights must be consistent with shape of a along specified axis.).- TypeError
A
numpy.matrixoperand withkeepdims: true: NumPy calls the matrix method, which has no such keyword. The text names that method, as inmatrix.sum() got an unexpected keyword argument 'keepdims'fornp.sum. Weights of another shape without an axis (Axis must be specified when shapes of a and weights differ.). Text weights beside a number, or a text operand: NumPy's refusal of the weight sum's text result dtype, or of a text mean.
bartlett(double)
Return the Bartlett window — a triangular taper whose end points are zero.
public static NDArray bartlett(double M)
Parameters
MdoubleNumber of points in the output window. If zero or less, an empty array is returned.
Returns
- NDArray
The triangular window, maximum normalized to one (the value one appears only when
Mis odd), first and last samples equal to zero.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.bartlett.html
NumPy: where(n <= 0, 1 + n/(M-1), 1 - n/(M-1)) with n = arange(1-M, M, 2); the
statements are Bartlett(double), called on the default engine (a window has no operand to
choose another).
Exceptions
- ValueError
Mis NaN (arange: cannot compute length), +infinity or too large for arange to size (Maximum allowed size exceeded).- OutOfMemoryException
A finite count whose window does not fit in memory.
base_repr(BigInteger, int, int)
Returns the string of an integer in a given base 2–36 (np.base_repr). A negative number gets a leading minus sign (NOT two's complement — that is binary_repr(BigInteger, int?)'s job).
public static string base_repr(BigInteger number, int @base = 2, int padding = 0)
Parameters
numberBigIntegerThe integer to convert (its sign is honoured; only the magnitude is expanded): NumPy's Python int, so any size - every C# integer type converts implicitly.
baseintThe radix, 2–36 inclusive. Digits above 9 use uppercase A–Z.
paddingintNumber of extra leading zeros to prepend (placed AFTER the sign, so
base_repr(-7,5,3)is"-00012"). Non-positive means no padding.
Returns
- string
The base-
baserepresentation ofnumber.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.base_repr.html. One signature since API-parity
batch 6: the long overload, which only cast to this one, is gone.
Exceptions
- ValueError
baseis greater than 36 or less than 2.
binary_repr(BigInteger, int?)
Returns the binary (base-2) string of an integer (np.binary_repr). WITHOUT width
a negative number is rendered with a leading minus sign; WITH width a negative
number is rendered as its two's complement to that width. About 25x faster than
base_repr(BigInteger, int, int) with base 2.
public static string binary_repr(BigInteger num, int? width = null)
Parameters
numBigIntegerThe integer to convert: NumPy's Python int, so any size - every C# integer type (
int,long,ulong, ...) converts implicitly, and values past 64 bits are exact.widthint?Optional field width: the result is left-zero-padded (positive input) or sign-extended with 1s (negative, two's-complement) to at least this many characters. Must be at least the number of significant bits or a ValueError is raised.
Returns
- string
The binary representation, or the two's complement when
numis negative andwidthis given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.binary_repr.html. One signature since API-parity
batch 6: the long overload, which only cast to this one, is gone.
Exceptions
- ValueError
widthis smaller than the number of bits required to representnum.
bincount(NDArray, NDArray, int)
Count the number of occurrences of each non-negative integer in x.
With no weights, bincount(x)[i] is the number of times the
value i appears in x (dtype int64). With
weights, bincount(x, w)[i] is the sum of w[j] for all
j where x[j] == i (dtype float64). The output length is
max(x.max() + 1, minlength).
public static NDArray bincount(NDArray x, NDArray weights = null, int minlength = 0)
Parameters
xNDArray1-D array of non-negative integers. Integer/bool/char dtypes are cast to
int64; a float/complex/decimal input raises (matching NumPy's behaviour for an actualndarrayof a non-integer dtype).weightsNDArrayOptional 1-D array of weights, same length as
x, cast tofloat64. When present the result is a weighted sum per bin instead of a count.minlengthintMinimum length of the output array. Must be non-negative.
Returns
- NDArray
A 1-D array:
int64counts whenweightsis null, otherwisefloat64weighted sums.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.bincount.html
<p>The body is
<xref href="NumSharp.TensorEngine.Bincount(NumSharp.NDArray%2cNumSharp.NDArray%2cSystem.Int32)" data-throw-if-not-resolved="false"></xref> (the np-layer dtype plan); this facade computes a <code>numpy.matrix</code>
operand as a plain array.</p>
Exceptions
- ArgumentNullException
xis null.- IncorrectShapeException
x, or with points the weights, is not 1-D (NumPy's depth check:object of too small depth for desired array,object too deep for desired array; its ValueError under the house dimension-error type).- InvalidCastException
xis not an integer, bool or char array, or with points the weights are complex or text (NumPy's safe-cast TypeError text).- ValueError
NumPy's three ValueErrors, in its order: a negative
minlength('minlength' must not be negative), a negative element ('list' argument must have no negative elements), weights of another length (The weights and list don't have the same length.).
bitwise_and(NDArray, NDArray, NDArray, NDArray, DType)
Compute the bit-wise AND of two arrays element-wise. Only integer and boolean types are handled (NumPy: float/complex inputs raise the no-loop TypeError).
public static NDArray bitwise_and(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array.
x2NDArraySecond input array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDType
Returns
- NDArray
Result. This is a scalar if both x1 and x2 are scalars.
Remarks
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.).
bitwise_count(NDArray, NDArray, NDArray, DType)
Compute the number of 1-bits in the absolute value of each element (NumPy 2.0's np.bitwise_count).
Only integer and boolean types are handled — float/complex/decimal inputs raise a TypeError, and a
dtype other than uint8 raises the no-loop TypeError (every loop outputs uint8).
Signed negatives count the MAGNITUDE, so bitwise_count(-1) == 1 (not 8), and the signed minimum
counts as 1 (its two's-complement negation overflows to itself, matching NumPy's a < 0 ? -a : a).
public static NDArray bitwise_count(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array. Only integer and boolean types are handled.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeOutput dtype request; only uint8 (or null) is a valid loop.
Returns
- NDArray
A uint8 array of set-bit counts. This is a scalar if x is a scalar.
Remarks
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.).
bitwise_invert(NDArray, NDArray, NDArray, DType)
Bit-wise inversion (bit-wise NOT), element-wise; integer and bool inputs only (NumPy's np.bitwise_invert,
the Array-API name NumPy 2.0 added: np.bitwise_invert is np.invert, the
same ufunc object, so this forwards to invert(NDArray, NDArray, NDArray, DType) and answers bit for bit as it does).
public static NDArray bitwise_invert(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array (a C# scalar converts to a 0-d array marked as the Python scalar it stands for).
outNDArrayA location into which the result is stored (NumPy ufunc
out=);nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=);nullis NumPy'swhere=True.dtypeDTypeThe loop dtype (NumPy ufunc
dtype=); must be an integer / bool loop - a float request raises NumPy's no-loop TypeError.
Returns
- NDArray
The result of invert(NDArray, NDArray, NDArray, DType):
outitself when it was given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.bitwise_invert.html
<p>One signature, the ufunc form of the original's; the original's own extra overloads (if any) are not
copied, so the alias never carries a second overload.</p>
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.).
bitwise_left_shift(NDArray, NDArray, NDArray, NDArray, DType)
Shift the bits of an integer to the left, element-wise (NumPy's np.bitwise_left_shift,
the Array-API name NumPy 2.0 added: np.bitwise_left_shift is np.left_shift, the
same ufunc object, so this forwards to left_shift(NDArray, NDArray, NDArray, NDArray, DType) and
answers bit for bit as it does).
public static NDArray bitwise_left_shift(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayValue operand (integer / bool / char only).
x2NDArrayShift-count operand (integer / bool / char only).
outNDArrayA location into which the result is stored (NumPy ufunc
out=);nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=);nullis NumPy'swhere=True.dtypeDTypeThe loop dtype (NumPy ufunc
dtype=); must be an integer / bool loop - a float request raises NumPy's no-loop TypeError.
Returns
- NDArray
The result of left_shift(NDArray, NDArray, NDArray, NDArray, DType):
outitself when it was given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.bitwise_left_shift.html
<p>One signature, the ufunc form of the original's. A C# literal operand converts to a 0-d array marked as
the Python scalar it stands for, so NEP 50's weak-scalar promotion holds without the original's
<code>object</code> overload (<code>np.bitwise_left_shift(int32_array, 2)</code> stays int32, as NumPy's).</p>
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.).
bitwise_not(NDArray, NDArray, NDArray, DType)
Compute bit-wise inversion, or bit-wise NOT, element-wise. Alias for invert.
public static NDArray bitwise_not(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
- NDArray
Result. This is a scalar if x is a scalar.
Remarks
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.).
bitwise_or(NDArray, NDArray, NDArray, NDArray, DType)
Compute the bit-wise OR of two arrays element-wise. Only integer and boolean types are handled (NumPy: float/complex inputs raise the no-loop TypeError).
public static NDArray bitwise_or(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array.
x2NDArraySecond input array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDType
Returns
- NDArray
Result. This is a scalar if both x1 and x2 are scalars.
Remarks
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.).
bitwise_right_shift(NDArray, NDArray, NDArray, NDArray, DType)
Shift the bits of an integer to the right, element-wise (NumPy's np.bitwise_right_shift,
the Array-API name NumPy 2.0 added: np.bitwise_right_shift is np.right_shift, the
same ufunc object, so this forwards to right_shift(NDArray, NDArray, NDArray, NDArray, DType) and
answers bit for bit as it does).
public static NDArray bitwise_right_shift(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayValue operand (integer / bool / char only).
x2NDArrayShift-count operand (integer / bool / char only).
outNDArrayA location into which the result is stored (NumPy ufunc
out=);nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=);nullis NumPy'swhere=True.dtypeDTypeThe loop dtype (NumPy ufunc
dtype=); must be an integer / bool loop - a float request raises NumPy's no-loop TypeError.
Returns
- NDArray
The result of right_shift(NDArray, NDArray, NDArray, NDArray, DType):
outitself when it was given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.bitwise_right_shift.html
<p>One signature, the ufunc form of the original's. A C# literal operand converts to a 0-d array marked as
the Python scalar it stands for, so NEP 50's weak-scalar promotion holds without the original's
<code>object</code> overload (<code>np.bitwise_right_shift(int32_array, 2)</code> stays int32, as NumPy's).</p>
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.).
bitwise_xor(NDArray, NDArray, NDArray, NDArray, DType)
Compute the bit-wise XOR of two arrays element-wise. Only integer and boolean types are handled (NumPy: float/complex inputs raise the no-loop TypeError).
public static NDArray bitwise_xor(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array.
x2NDArraySecond input array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDType
Returns
- NDArray
Result. This is a scalar if both x1 and x2 are scalars.
Remarks
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.).
blackman(double)
Return the Blackman window — a taper formed by the first three terms of a summation of cosines.
public static NDArray blackman(double M)
Parameters
MdoubleNumber of points in the output window. If zero or less, an empty array is returned.
Returns
- NDArray
The window, maximum normalized to one (the value one appears only when
Mis odd).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.blackman.html
NumPy: 0.42 + 0.5*cos(pi*n/(M-1)) + 0.08*cos(2.0*pi*n/(M-1)) with n = arange(1-M, M, 2); the
statements are Blackman(double), called on the default engine.
Exceptions
- ValueError
Mis NaN, +infinity or too large for arange to size.- OutOfMemoryException
A finite count whose window does not fit in memory.
block(object)
Assemble an nd-array from nested lists of blocks.
Blocks in the innermost lists are concatenated (see
concatenate(NDArray[], int?, NDArray, DType, string))
along the last dimension (-1), then these are concatenated along
the second-last dimension (-2), and so on until the outermost
list is reached.
Blocks can be of any dimension, but will not be broadcasted using
the normal rules. Instead, leading axes of size 1 are inserted,
to make block.ndim the same for all blocks.
public static NDArray block(object arrays)
Parameters
arraysobjectNested "lists" of blocks. The C# mapping of NumPy's nested Python lists:
- NDArray — a leaf block.
- numeric scalar (int, double, bool, …) — a 0-d leaf.
- any 1-D Array (
object[],NDArray[],int[], jaggedint[][], …) or non-generic IList (List<T>) — a nested LIST whose elements are classified recursively (mirrors a Python list). - rank ≥ 2 rectangular arrays (
int[,], …) — a leaf, converted via asanyarray(in object, DType, char?, string, bool?). - tuples (ITuple) — rejected with TypeError, matching NumPy ("np.block does not allow implicit conversion from tuple to ndarray").
If passed a single NDArray or scalar (a nested list of depth 0), a copy is returned (matching NumPy 2.x behavior).
Returns
- NDArray
The array assembled from the given blocks. The dimensionality of the output is equal to the greatest of the dimensionality of all the inputs and the depth to which the input list is nested.
Remarks
Exceptions
- ValueError
If list depths are mismatched — for instance
[[a, b], c]is illegal and should be spelt[[a, b], [c]]— or if lists are empty — for instance[[a, b], []].- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
bmat(NDArray)
Interpret a single array as a matrix — an NDMatrix copy. A 0-D input becomes
(1, 1), a 1-D input of length N becomes (1, N), and a 2-D input is copied unchanged.
public static NDMatrix bmat(NDArray obj)
Parameters
objNDArrayInput array.
Returns
- NDMatrix
A new matrix holding
obj's values.
Remarks
Port of NumPy 2.x numpy.bmat(ndarray) ≙ matrix(obj), which copies
(matrix's default copy=True) — unlike asmatrix(NDArray, DType),
which returns a view. The array is viewed as a matrix first (which is where an input that cannot
be a matrix raises), then copied, so the result never aliases obj.
https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
bmat(NDArray[])
Build a matrix from a flat sequence of blocks placed side by side: [A, B] joins the
blocks along the last axis, then coerces the result to 2-D.
public static NDMatrix bmat(NDArray[] obj)
Parameters
objNDArray[]The blocks, concatenated left-to-right (along the last axis).
Returns
- NDMatrix
The assembled matrix; it owns its data in C order.
Remarks
Port of NumPy 2.x numpy.bmat([A, B, …]) ≙ matrix(concatenate(obj, axis=-1)) —
the flat-list branch, equivalent to a single-row [[A, B, …]]. A flat list of 1-D
blocks concatenates to 1-D and is then coerced to a (1, N) row (NumPy's
matrix() finalize). No matrix products; see bmat(NDArray[][]).
https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
bmat(NDArray[][])
Build a matrix from a nested sequence of blocks: [[A, B], [C, D]] assembles one
NDMatrix by joining the blocks in each inner list left-to-right and stacking the
resulting rows top-to-bottom.
public static NDMatrix bmat(NDArray[][] obj)
Parameters
objNDArray[][]Rows of blocks. Each inner array holds the blocks of one row; they are concatenated along the last axis (horizontally). The rows are then concatenated along axis 0 (vertically).
Returns
- NDMatrix
The assembled matrix; it owns its data in C order.
Remarks
Port of NumPy 2.x numpy.bmat ≙ matrix(concatenate([concatenate(row, axis=-1) for
row in obj], axis=0)). It is pure block assembly (concatenation) — it performs NO
matrix multiplication, so no BLAS/OpenBLAS path is involved; the numerics come entirely
from concatenate(NDArray[], int?, NDArray, DType, string) and the 2-D
coercion from NumSharp.Shape.AsMatrix(). The result is an NDMatrix, as in
NumPy: * is the matrix product on it and it has .T, .H, .I; seen
through an NDArray reference it is a plain 2-D array. The result dtype follows NumPy's two-stage
result_type(params NDArray[]) promotion (per row, then across rows). Errors reproduce
NumPy's ValueError verbatim (see bmat(ITuple) remarks). See
block(object) for the N-D generalization.
https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
bmat(ITuple)
Build a matrix from C# tuples of blocks — (A, B) is a single side-by-side row and
((A, B), (C, D)) is a nested block matrix — the tuple spelling of NumPy's
np.bmat((A, B)) / np.bmat(((A, B), (C, D))).
public static NDMatrix bmat(ITuple obj)
Parameters
objITupleA ITuple (any
ValueTuple/Tuple): if its first entry is a bare block (NDArray) the whole tuple is one row joined along the last axis; otherwise each entry is a row (itself a tuple /NDArray[]/ sequence of blocks), concatenated per row and stacked along axis 0.
Returns
- NDMatrix
The assembled matrix; it owns its data in C order.
Remarks
Port of NumPy 2.x numpy.bmat's isinstance(obj, (tuple, list)) branch. Mixed
forms work too — ([A, B], [C, D]) (a tuple of lists) — since a row may be a tuple, an
NDArray[], or any IEnumerable of blocks; a non-NDArray
entry is passed through asanyarray(in object, DType, char?, string, bool?) exactly as NumPy runs
asarray over the entries. Still pure concatenation (no matrix products).
Error parity. The errors reproduce numpy.concatenate's contract as
ValueError with NumPy's verbatim text (see BmatConcat(NDArray[], int)): an empty
tuple / row → "need at least one array to concatenate"; a leading 0-D block (a scalar, or a
null — NumPy's None becomes a 0-D array) → "zero-dimensional arrays cannot be
concatenated"; a later block whose rank differs from the first → "all the input arrays must
have same number of dimensions, but the array at index 0 has {n} dimension(s) and the array
at index {k} has {m} dimension(s)". A width/height mismatch between well-ranked blocks keeps
concatenate's IncorrectShapeException — same verbatim NumPy text, the
library-wide house exception type for shape/alignment errors.
https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
bmat(string, IDictionary<string, NDArray>, IDictionary<string, NDArray>)
Build a matrix from a matrix string whose tokens name the blocks: rows are separated by
';' and the blocks within a row by commas and/or whitespace, e.g.
"A, B; C, D". Each token is resolved to an NDArray through the supplied
dictionaries (trying ldict first, then gdict); the
blocks of each row are joined along the last axis and the rows are stacked along axis 0.
public static NDMatrix bmat(string obj, IDictionary<string, NDArray> ldict, IDictionary<string, NDArray> gdict = null)
Parameters
objstringMatrix string such as
"A, B; C, D".ldictIDictionary<string, NDArray>Local name → array map, consulted first (NumPy's
ldict).gdictIDictionary<string, NDArray>Global name → array map, consulted when a name is absent from
ldict(NumPy'sgdict). Optional.
Returns
- NDMatrix
The assembled matrix; it owns its data in C order.
Remarks
Port of NumPy 2.x numpy.bmat(str, ldict, gdict) → matrix(_from_string(...)).
Still pure concatenation (no matrix products).
Divergence — the name dictionary is required. NumPy resolves a bare token against the
CALLER'S Python frame (sys._getframe().f_back) when gdict is None; C#
has no equivalent, so at least one of ldict / gdict
must be supplied (this is the same reason r_/c_ omit the
bmat branch). Resolution tries ldict then
gdict; a token absent from both — including a numeric literal such as
"1", which NumPy also treats as a name — raises NameError
("name '{token}' is not defined"), matching NumPy verbatim. Unlike
asmatrix(string, DType)'s literal parser, brackets are NOT stripped (they
become part of a token and fail to resolve), exactly as NumPy's _from_string leaves
them. https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
Exceptions
- NameError
A token is not present in either dictionary.
broadcast(NDArray, NDArray)
Two-operand overload — the most common case. Retained as an explicit overload so
np.broadcast(a, b) stays binary-compatible and skips the params-array allocation.
public static np.Broadcast broadcast(NDArray nd1, NDArray nd2)
Parameters
Returns
Exceptions
- IncorrectShapeException
The operands do not broadcast together (NumPy's text).
broadcast(params NDArray[])
Produce an object that mimics broadcasting.
public static np.Broadcast broadcast(params NDArray[] arrays)
Parameters
arraysNDArray[]The arrays to broadcast against one another. NumPy caps this at 64 operands (NPY_MAXARGS); NumSharp imposes no cap, matching its unlimited-operand
NDIter.
Returns
- np.Broadcast
Broadcast the input parameters against one another, and return an object that encapsulates the result. Amongst others, it has shape and nd properties, and may be used as an iterator.
Remarks
broadcast(NDListArray[])
NumPy's np.broadcast(*arrays) over object arrays of lists - np.char.split's
NDListArray results: their shapes broadcast together, and iterating yields one tuple of the
operands' lists (each a List<T> of its pieces, NumPy's Python list) per broadcast position.
public static np.Broadcast broadcast(NDListArray[] arrays)
Parameters
arraysNDListArray[]The list arrays (NumPy's sequence of operands); the object borrows them.
Returns
Remarks
A sequence parameter, not params: a second params form would make np.broadcast()
ambiguous. NumSharp's lists are their own array type, so a list array and a numeric array do not broadcast in
one object here (NumPy's object array would). API-parity batch 13.
Exceptions
- ArgumentNullException
An operand is null.
- ObjectDisposedException
An operand was disposed.
- IncorrectShapeException
The operands do not broadcast together (NumPy's text).
broadcast_arrays(NDArray, NDArray)
Broadcast two arrays against each other (NumPy 2.4.2's numpy.broadcast_arrays(lhs, rhs)): an array
already of the common shape comes back as itself, the other as a view, writeable only when its array is.
public static (NDArray Lhs, NDArray Rhs) broadcast_arrays(NDArray lhs, NDArray rhs)
Parameters
Returns
- (NDArray Lhs, NDArray Rhs)
The two results: each the input itself when its shape is the broadcast shape, else a view on it. Views are typically not contiguous, and more than one element of a broadcasted array may refer to a single memory location: copy first to write to them independently. A view of a read-only array is read-only.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.broadcast_arrays.html; the same statement as the params overload (BroadcastArraysMember(NDArray, Shape) per operand).
Exceptions
- IncorrectShapeException
The arrays do not broadcast together: NumPy's
shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (3,) and arg 1 with shape (4,).(parity QA-30).- ValueError
The broadcast shape's element count does not fit a 64-bit integer (
broadcast dimensions too large.).
broadcast_arrays(params NDArray[])
Broadcast any number of arrays against each other (NumPy 2.4.2's numpy.broadcast_arrays): an array
already of the common shape comes back as itself, every other one as a view, writeable only when its array is.
public static NDArray[] broadcast_arrays(params NDArray[] ndArrays)
Parameters
ndArraysNDArray[]The arrays to broadcast.
Returns
- NDArray[]
One array per input: the input itself when its shape is the broadcast shape, else a view on it. Views are typically not contiguous, and more than one element of a broadcasted array may refer to a single memory location: copy first to write to them independently. A view of a read-only array is read-only.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.broadcast_arrays.html. See broadcast_arrays(NDArray[]) for the writeable rule (parity QA-34). A result that IS an input must not be disposed as if it were a new view.
Exceptions
- IncorrectShapeException
The arrays do not broadcast together.
broadcast_shapes(params Shape[])
Broadcasts the input shapes into the single shape they would all broadcast to, WITHOUT
allocating any array — the NumPy 2.x numpy.broadcast_shapes. Use it to size an
output up front (e.g. before an out= allocation) when you have only the shapes,
not the arrays. An int argument is read as the one-dimensional shape (n,)
exactly as NumPy treats a bare int, so broadcast_shapes(3, 1) is (3,).
public static Shape broadcast_shapes(params Shape[] shapes)
Parameters
shapesShape[]The shapes to broadcast against each other. Each entry is a Shape; the rich implicit conversions on Shape let NumPy call sites port verbatim — a tuple literal
(1, 2), a bareint(→(n,)), anint[]/long[](e.g.a.shape), or an explicitnew Shape(...)all bind. No argument at all returns the scalar shape()(NumPy's empty-tuple result).
Returns
- Shape
The broadcast shape. A scalar shape
()whenshapesis empty or every entry is scalar. A stretched extent of 0 wins over 1 (so(0,)broadcast with(1,)is(0,)), matching NumPy — a zero-length axis is not size-1.
Remarks
Exceptions
- ValueError
If any dimension is negative —
"negative dimensions are not allowed", verbatim with NumPy (which reaches it through thenp.emptyit would have allocated).- IncorrectShapeException
If the shapes are not broadcast-compatible. The message is NumPy's verbatim, naming the argument that first established the conflicting extent and the argument that clashes with it (e.g.
"... Mismatch is between arg 0 with shape (3,) and arg 1 with shape (4,).").
broadcast_to(UnmanagedStorage, UnmanagedStorage)
Broadcast an array to a new shape.
public static NDArray broadcast_to(UnmanagedStorage from, UnmanagedStorage against)
Parameters
fromUnmanagedStorageThe UnmanagedStorage to broadcast.
againstUnmanagedStorageThe shape to broadcast against.
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
Exceptions
- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
broadcast_to(UnmanagedStorage, NDArray)
Broadcast an array to a new shape.
public static NDArray broadcast_to(UnmanagedStorage from, NDArray against)
Parameters
fromUnmanagedStorageThe UnmanagedStorage to broadcast.
againstNDArrayThe shape to broadcast against.
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
Exceptions
- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
broadcast_to(UnmanagedStorage, Shape)
Broadcast an array to a new shape.
public static NDArray broadcast_to(UnmanagedStorage from, Shape against)
Parameters
fromUnmanagedStorageThe NDArray to broadcast.
againstShapeThe shape to broadcast against.
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
Exceptions
- ValueError
A dimension of
againstis negative: NumPy'sall elements of broadcast shape must be non-negative, raised before the broadcast check.- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
broadcast_to(NDArray, UnmanagedStorage)
Broadcast an array to a new shape.
public static NDArray broadcast_to(NDArray from, UnmanagedStorage against)
Parameters
fromNDArrayThe NDArray to broadcast.
againstUnmanagedStorageThe shape to broadcast against.
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
Exceptions
- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
broadcast_to(NDArray, NDArray)
Broadcast an array to a new shape.
public static NDArray broadcast_to(NDArray from, NDArray against)
Parameters
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
Exceptions
- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
broadcast_to(NDArray, Shape)
Broadcast an array to a new shape.
public static NDArray broadcast_to(NDArray from, Shape against)
Parameters
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
Exceptions
- ValueError
A dimension of
againstis negative: NumPy'sall elements of broadcast shape must be non-negative, raised before the broadcast check.- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
broadcast_to(Shape, UnmanagedStorage)
Broadcast an shape against an other new shape.
public static Shape broadcast_to(Shape from, UnmanagedStorage against)
Parameters
fromShapeThe shape that is to be broadcasted
againstUnmanagedStorageThe shape that'll be used to broadcast
fromshape
Returns
- Shape
A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.
Remarks
Exceptions
- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
broadcast_to(Shape, NDArray)
Broadcast an shape against an other new shape.
public static Shape broadcast_to(Shape from, NDArray against)
Parameters
fromShapeThe shape that is to be broadcasted
againstNDArrayThe shape that'll be used to broadcast
fromshape
Returns
- Shape
A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.
Remarks
Exceptions
- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
broadcast_to(Shape, Shape)
Broadcast an shape against an other new shape.
public static Shape broadcast_to(Shape from, Shape against)
Parameters
fromShapeThe shape that is to be broadcasted
againstShapeThe shape that'll be used to broadcast
fromshape
Returns
- Shape
A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.
Remarks
Exceptions
- ValueError
A dimension of
againstis negative: NumPy'sall elements of broadcast shape must be non-negative, raised before the broadcast check.- IncorrectShapeException
fromdoes not broadcast toagainstone way: it has more axes, or an axis of a length other than 1 that differs from the target's.
can_cast(DType, DType, NPY_CASTING)
Returns True if cast between data types can occur according to the casting rule (the NPY_CASTING spelling).
public static bool can_cast(DType from, DType to, NPY_CASTING casting)
Parameters
fromDTypeData type to cast from.
toDTypeData type to cast to.
castingNPY_CASTINGThe casting level.
Returns
- bool
True if cast can occur according to the casting rule.
Exceptions
- TypeError
toorfromis null (NumPy's "did not understand one of the types; 'None' not accepted").
can_cast(DType, DType, string)
Returns True if cast between data types can occur according to the casting rule — NumPy's
np.can_cast(from_, to, casting='safe') over two descriptors (PyArray_CanCastTypeTo, NEP 43):
the CastingImpl registered for the two DType CLASSES answers, so byte order and datetime units
take part (can_cast('>i4', 'i4', 'equiv') is True and 'no' is False;
can_cast('M8[D]', 'M8[s]', 'safe') is True and the reverse is False).
public static bool can_cast(DType from, DType to, string casting = "safe")
Parameters
fromDTypeData type to cast from (any spelling that converts to DType).
toDTypeData type to cast to.
castingstringControls what kind of data casting may occur (case-sensitive, as in NumPy):
- "no" means the data types should not be cast at all.
- "equiv" means only byte-order changes are allowed.
- "safe" means only casts which can preserve values are allowed.
- "same_kind" means only safe casts or casts within a kind (int to int, float to float) are allowed.
- "unsafe" means any data conversions may be done.
Returns
- bool
True if cast can occur according to the casting rule.
Remarks
Exceptions
- TypeError
toorfromis null (NumPy'sNone: "did not understand one of the types; 'None' not accepted"), orcastingis null ("casting must be str, not NoneType"). NumPy convertstoandcastingwhile it parses the arguments andfrom_after, so the checks run in that order.- ValueError
casting must be one of 'no', 'equiv', 'safe', 'same_kind', 'unsafe' (got '…')— verbatim NumPy.
can_cast(NDArray, DType, string)
Returns True if cast from the array's dtype can occur according to the casting rule (NumPy's array form of
can_cast; arrays are never inspected by value under NEP 50).
public static bool can_cast(NDArray from, DType to, string casting = "safe")
Parameters
fromNDArrayThe array whose dtype is cast, by its own descriptor (for a string array: class and width); null is NumPy's
None.toDTypeData type to cast to.
castingstringThe casting rule (see can_cast(DType, DType, string)).
Returns
- bool
True if the array's dtype can be cast to
toundercasting.
Exceptions
- TypeError
A null argument (NumPy's texts, in NumPy's order:
to,casting, thenfrom_), orfromis the 0-d array a bare C# number became: NumPy 2's NEP 50 refusal (NumSharp.np.PythonNumberRefusal()), after thetoandcastingchecks.- ValueError
castingis not one of NumPy's five casting names.
can_cast(NDArray, NPTypeCode, string)
Returns True if cast from array dtype can occur according to the casting rule.
public static bool can_cast(NDArray from, NPTypeCode to, string casting = "safe")
Parameters
fromNDArrayArray to cast from: arrays are judged by their dtype, never by value (NEP 50).
toNPTypeCodeData type to cast to.
castingstringControls what kind of data casting may occur.
Returns
- bool
True if the array can be cast to the target type.
Remarks
Since API-parity batch 9 this is the overload a bare C# number binds (np.can_cast(1,
NPTypeCode.SByte), through NDArray's implicit conversion), so it carries the refusal the removed typed value
overloads never made.
Exceptions
- ArgumentNullException
fromis null.- TypeError
fromis the 0-d array a bare C# number became (abool, an integer primitive,float,doubleor Complex literal, which NumSharp's implicit conversions mark as NumPy's Python scalar): NumPy 2's NEP 50 refusal (NumSharp.np.PythonNumberRefusal()).np.array(1),NDArray.Scalar(1)and a Half keep the dtype rule, as NumPy's 0-d arrays and NumPy scalars do.- ValueError
castingis not one of NumPy's five casting names.- NotSupportedException
tois String: a storage lane names neither the string class nor its width (pass a DType such asnp.dtype("U5")).
can_cast(NPTypeCode, NPTypeCode, string)
Returns True if cast between data types can occur according to the casting rule.
public static bool can_cast(NPTypeCode from, NPTypeCode to, string casting = "safe")
Parameters
fromNPTypeCodeData type to cast from.
toNPTypeCodeData type to cast to.
castingstringControls what kind of data casting may occur:
- "no" means the data types should not be cast at all.
- "equiv" means only byte-order changes are allowed.
- "safe" means only casts which can preserve values are allowed.
- "same_kind" means only safe casts or casts within a kind (int to int, float to float) are allowed.
- "unsafe" means any data conversions may be done.
Returns
- bool
True if cast can occur according to the casting rule.
Examples
np.can_cast(NPTypeCode.Int32, NPTypeCode.Int64) // True
np.can_cast(NPTypeCode.Int64, NPTypeCode.Int32) // False
np.can_cast(NPTypeCode.Int32, NPTypeCode.Single, "same_kind") // True (int -> float is allowed)
np.can_cast(NPTypeCode.Int32, NPTypeCode.Int16, "unsafe") // True
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.can_cast.html
The NPTypeCode spelling of can_cast(DType, DType, string): the same NEP 43 engine,
whose answers for the storage-backed types are the rules this overload always applied
(safe ⇔ promote(from, to) == to; same_kind ⇔ safe or the source kind orders at or below the
destination kind).
can_cast(object, NPTypeCode, string)
NumPy's np.can_cast(from_, to, casting='safe') for a source whose static type is object:
array_can_cast_safely's dispatch on from_, statement for statement — an array by its own
descriptor (PyArray_CanCastArrayTo), a NumPy scalar by its dtype, a Python number REFUSED (NEP 50), and
anything else converted as a dtype specifier.
public static bool can_cast(object value, NPTypeCode to, string casting = "safe")
Parameters
valueobjectThe source: an NDArray; a dtype spelling (DType, NPTypeCode, Type, NDScalarType, a dtype string); a NumPy scalar (a boxed Half or
char, the C# values NumSharp treats as NumPy scalars); or a C# number, which NumPy 2 refuses.toNPTypeCodeData type to cast to; Empty is NumPy's
None.castingstringThe casting rule (see can_cast(DType, DType, string)).
Returns
- bool
True if the source's dtype casts to
toundercasting.
Remarks
API-parity batch 9. NumSharp kept eleven typed value overloads (can_cast(int value, ...) and its twins)
with a value table, "does 300 fit int8", which NumPy 2 replaced by the refusal; the table also had holes
(can_cast(1, NPTypeCode.SByte) was False). They went, so a bare C# number now binds
can_cast(NDArray, NPTypeCode, string) through NDArray's implicit conversion, which refuses the
literal-marked 0-d array the same way; this form refuses the boxed number. The literal 0 also converts
to NPTypeCode, so np.can_cast(0, NPTypeCode.Byte) is CS0121 at compile time. A
decimal has no NumPy analog: it is NumSharp's decimal dtype, judged by the dtype rule.
https://numpy.org/doc/stable/reference/generated/numpy.can_cast.html
Exceptions
- TypeError
A boxed C# number (
bool, an integer primitive,float,double, Complex): NumPy 2's refusal,can_cast() does not support Python ints, floats, and complex because the result used to depend on the value.(two lines, see NumSharp.np.PythonNumberRefusal()). A null source, a nullto, or an object that names no dtype (a C# array, a list):did not understand one of the types; 'None' not accepted.- ValueError
An unknown
castingname, raised before the source is looked at (NumPy parses it with the arguments).- NotSupportedException
tois String for an array source (see can_cast(NDArray, NPTypeCode, string)).
can_cast(string, DType, string)
can_cast(DType, DType, string) for a dtype STRING source (np.can_cast("i4", "i8")). Exists so that a
string first argument binds the dtype grammar rather than NumSharp's string→NDArray (character array) conversion.
public static bool can_cast(string from, DType to, string casting = "safe")
Parameters
fromstringThe dtype string to cast from; null is NumPy's
None.toDTypeData type to cast to.
castingstringThe casting rule (see can_cast(DType, DType, string)).
Returns
- bool
True if cast can occur according to the casting rule.
Exceptions
- TypeError
A null argument (NumPy's texts, in NumPy's order:
to,casting, thenfrom_), or afromstring NumPy cannot parse: NumPy replaces the parser's error withdid not understand one of the types; 'None' not acceptedforfrom_(a badtostring keeps the parser's own error, raised while the argument converts).- ValueError
An unknown casting name.
- NotSupportedException
fromis a valid NumPy dtype NumSharp does not implement (complex64, structured, ...).
can_cast(Type, Type, string)
Returns True if cast between data types can occur according to the casting rule.
public static bool can_cast(Type from, Type to, string casting = "safe")
Parameters
fromTypeCLR type to cast from.
toTypeCLR type to cast to.
castingstringControls what kind of data casting may occur.
Returns
- bool
True if cast can occur according to the casting rule.
cbrt(NDArray, NDArray, NDArray, DType)
Return the cube-root of an array, element-wise.
public static NDArray cbrt(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayThe values whose cube-roots are required.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
An array of the same shape as x, containing the cube root of each element. If x contains negative values, the result contains the (negative) real cube root. This is a scalar if x is a scalar.
Remarks
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.).
ceil(NDArray, NDArray, NDArray, DType)
Return the ceiling of the input, element-wise.
The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \lceil x \rceil.
public static NDArray ceil(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput data.
outNDArrayA location into which the result is stored (NumPy ufunc out=);
nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeThe loop dtype (NumPy's
dtype=):xmust cast to it undersame_kind, so a float input with an integer dtype is refused.nullkeeps the input's dtype (an integer input stays integer, as in NumPy 2.x).
Returns
- NDArray
The ceiling of each element in x, in the input's dtype unless
dtypenames another. This is a scalar if x is a scalar.
Remarks
Exceptions
- TypeError
A
dtypethe input cannot reach undersame_kind(Cannot cast ufunc 'ceil' input from dtype('float64') to dtype('int64') with casting rule 'same_kind'; NumPy raisesUFuncTypeError).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
choose(NDArray, NDArray, NDArray, string)
choose(NDArray, object[], NDArray, string) where choices is a
single array whose OUTERMOST dimension is taken as the sequence (NumPy's "not recommended"
abuse — choices.shape[0] choice sub-arrays). A 0-d choices is a
TypeError ("iteration over a 0-d array"), exactly as NumPy raises.
public static NDArray choose(NDArray a, NDArray choices, NDArray @out = null, string mode = "raise")
Parameters
aNDArrayThe index array (see choose(NDArray, object[], NDArray, string)).
choicesNDArrayAn array whose outermost dimension enumerates the choices.
outNDArrayOptional destination whose shape must equal the broadcast result shape.
modestring"raise"(default),"wrap"or"clip".
Returns
- NDArray
A fresh C-contiguous array, or
outwhen given.
Remarks
Scoped by [NDScoped], with the same reclaimed set as the object[] overload,
plus the views along axis 0 this overload builds (each held a reference on the caller's buffer until
the finalizer ran).
Exceptions
- ArgumentNullException
aorchoicesis null.- IncorrectShapeException
The choices and
ado not broadcast together: NumPy's multi-iterator text (shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (0, 3) and arg 2 with shape (0,).), the choices numbered first and the index array last.- TypeError
choicesis 0-d,acannot be safe-cast to int64, orouthas the wrong shape.- ValueError
choiceshas length 0 along its first axis, an index is out of range undermode="raise", ormodeis not a known clip mode.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
choose(NDArray, NDArray[], NDArray, string)
choose(NDArray, object[], NDArray, string) for a strongly-typed array of choices (the common case — every choice is an NDArray). The result dtype is result_type(params object[]) of the choices.
public static NDArray choose(NDArray a, NDArray[] choices, NDArray @out = null, string mode = "raise")
Parameters
aNDArrayThe index array (see choose(NDArray, object[], NDArray, string)).
choicesNDArray[]The choice arrays.
outNDArrayOptional destination whose shape must equal the broadcast result shape.
modestring"raise"(default),"wrap"or"clip".
Returns
- NDArray
A fresh C-contiguous array, or
outwhen given.
Remarks
Scoped by [NDScoped], with the same reclaimed set as the object[] overload.
Exceptions
- ArgumentNullException
a,choicesor a choice is null.- IncorrectShapeException
The choices and
ado not broadcast together: NumPy's multi-iterator text (shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (0, 3) and arg 2 with shape (0,).), the choices numbered first and the index array last.- ValueError
choicesis empty, an index is out of range undermode="raise", ormodeis not a known clip mode.- TypeError
acannot be safe-cast to int64, orouthas the wrong shape.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
choose(NDArray, object[], NDArray, string)
Construct an array from an index array and a sequence of arrays to choose from. For every
position I of the (broadcast) result, the output is
choices[a[I]][I] — i.e. the value of the a[I]-th choice array at that same
position. a and every choice are first broadcast to a common shape.
public static NDArray choose(NDArray a, object[] choices, NDArray @out = null, string mode = "raise")
Parameters
aNDArrayThe index array. Converted to
int64under the"safe"casting rule (bool and the signed/unsigned integers up touint32are accepted;uint64, float, complex and decimal are rejected with a TypeError).choicesobject[]The choice arrays. Each entry is either an NDArray (strong dtype) or a boxed C# scalar; as in NumPy (NEP50) an
int/float/double/Complex literal is a weak scalar that adopts the other choices' dtype, whilebool,char, Half,decimaland every NDArray are strong. All choices are broadcast against each other and againsta.outNDArrayOptional destination. Its shape must EQUAL the broadcast result shape (not merely broadcast to it); values are cast into it with unsafe casting and the method returns
outitself. Whennull(default) a fresh array is allocated with the choices' common dtype.modestringHow indices outside
[0, n-1]are treated:"raise"(default — throw),"wrap"(modulo with sign correction) or"clip"(values < 0 → 0, values > n-1 → n-1). Case-sensitive, matching NumPy's clip-mode parser.
Returns
- NDArray
A fresh C-contiguous array (or
out) whose dtype is result_type(params object[]) of the choices (NEP50) and whose shape is the broadcast of the choices againsta.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.choose.html
Scoped by [NDScoped]: the int64 copy of a non-int64 index array, the 0-d arrays of
scalar choices, the converted copies of collection choices, the dtype casts of the choices, their
broadcast views and, when out is given, the computed result that is copied into
it are all released on return, exceptions included. The result is yielded when out
is null. Before the scope, only the index copy was released by hand: the casts, the scalar arrays and
the out= temporary were left to the finalizer, and a broadcast view of a cast choice kept that
cast's buffer out of the pool. The caller's arrays were built before the scope opened, so the scope
never disposes them.
Exceptions
- ValueError
choicesis empty ("0-length sequence."), an index is out of range undermode="raise"("invalid entry in choice array"), ormodeis not a known clip mode (NumPy's two clip-mode texts).- TypeError
acannot be safe-cast toint64, orouthas the wrong shape ("choose: invalid shape for output array.").- ArgumentNullException
a,choicesor a choice entry is null.- IncorrectShapeException
The choices and
ado not broadcast together: NumPy's multi-iterator text (shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (0, 3) and arg 2 with shape (0,).), the choices numbered first and the index array last.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
clip(NDArray, NDArray, NDArray, NDArray, DType, NDArray, NDArray, NDArray)
Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.
Matches NumPy 2.x signature: clip(a, a_min=<no value>, a_max=<no value>, out=None, *, min=<no value>, max=<no value>, **kwargs), with the ufunc keywords dtype and where. Either or both bounds may be null (NumPy's None). The min and max keyword aliases (added in NumPy 2.0) are accepted under NumPy's rules (see the remarks).
public static NDArray clip(NDArray a, NDArray a_min = null, NDArray a_max = null, NDArray @out = null, DType dtype = null, NDArray min = null, NDArray max = null, NDArray where = null)
Parameters
aNDArrayArray containing elements to clip. It broadcasts with the bounds,
outandwhere.a_minNDArrayMinimum value. If null, clipping is not performed on lower interval edge. A C# integer literal is NumPy's Python int: on an integer array a value at or below the dtype's minimum is ignored (it cannot clip anything), and a value that does not fit the dtype on the other side raises. An array bound broadcasts against
a.a_maxNDArrayMaximum value. If null, clipping is not performed on upper interval edge. A C# integer literal at or above an integer array's dtype maximum is ignored; one below the dtype's minimum raises.
outNDArrayThe results will be placed in this array, which is returned as-is. It may be the input array for in-place clipping, and it may overlap an input in any other way: the result is then computed as if from a copy of that input (NumPy's COPY_IF_OVERLAP).
outmust have the broadcast shape of the operands (it is never stretched), and its dtype must be reachable from the computed dtype by a same_kind cast (NumPy's ufunc rule; e.g. a uint8 clip may write into an int8 or a float64 out).dtypeDTypeThe dtype the computation runs in (NumPy's ufunc
dtype=). The inputs are cast to it, and each must reach it by a same_kind cast.minNDArrayNumPy 2.x keyword alias for
a_min; see the remarks for how it combines with the positional bounds.maxNDArrayNumPy 2.x keyword alias for
a_max; see the remarks for how it combines with the positional bounds.whereNDArrayNumPy's ufunc
where=mask (a bool array, broadcast with the other operands). Only the True positions are computed and written. The other positions ofoutkeep their contents; withoutoutthey are uninitialized, as in NumPy.
Returns
- NDArray
An array with the elements of a, but where values < min are replaced with min, and those > max with max (
outwhen given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.clip.html
Bound arguments. NumPy tells an omitted argument (<no value>) from an explicit None;
C# cannot, so a null bound means None until a keyword alias is used:
- No
min/maxkeyword:a_minanda_maxare the bounds, a null one is None. NumPy raises "missing 1 required positional argument" fornp.clip(a, 1); here that call clips from below only, asnp.clip(a, 1, None)does. - A keyword given: a null positional counts as omitted, as it does in NumPy's own call
np.clip(a, min=2). Both positionals null → the keywords are the bounds; exactly one null → NumPy's TypeError naming it; both given → NumPy's ValueError. A positional passed explicitly as null next to a keyword therefore reports the TypeError where NumPy'snp.clip(a, 2, None, min=3)reports the ValueError.
Routing. A port of NumPy's numpy/_core/_methods.py::_clip, the function behind both np.clip and
ndarray.clip. On an integer array it first drops a Python-int bound at or past the dtype's limit:
np.clip(uint8_array, 0, 256) returns the array unchanged, and np.clip(uint8_array, -1, 100)
only clips from above. It then routes the call: no bound left → positive (a copy), one bound →
minimum / maximum, two → the clip ufunc. The routed name is what the cast errors quote.
A kept integer bound is packed into the computed dtype under NEP 50, so it raises instead of wrapping.
The drop rule uses the input array's own range, even when dtype changes the computation:
np.clip(int8_array, 1000, 2000, dtype: np.int16) is legal and returns all 1000.
The ufunc. The routed ufunc broadcasts a, the bounds, out and
where together; a fresh result takes the memory order of its operands (C order breaks ties),
as NumPy's iterator allocates it. For two scalar float32/float64 bounds NumPy runs its const fast path
(x < lo ? lo : x, then x > hi ? hi : x: a signed-zero tie keeps the element, a NaN bound fills the
result with that NaN's bits); array bounds run MIN(MAX(x, lo), hi) (a tie takes the bound). Which one runs
for a broadcast or buffered call is NumPy's own per-call decision, reproduced exactly.
NumSharp cannot tell a C# literal from a 0-d NDArray at this boundary, so every 0-d integer
bound counts as a Python int. NumPy promotes with a 0-d array or a NumPy scalar instead (np.int64(1000)
makes an int8 clip int64). The values agree; only that result dtype differs.
When |value| >= 2^31, NumPy's overflow text depends on the platform's C long. NumSharp
uses the Linux/macOS (LP64) text: values that fit a 64-bit long say "Python integer ... out of bounds
for ...", larger ones say "Python int too large to convert to C long".
Exceptions
- TypeError
A
min/maxkeyword is given while exactly one ofa_min/a_maxis null: NumPy's "clip() missing 1 required positional argument: 'a_max'" (or 'a_min'). Or neither bound is given (or both were ignored) and the computation would run in bool: NumPy then callsnp.positive, which has no bool loop.- ValueError
A
min/maxkeyword is given together with both positional bounds ("Passingminormaxkeyword argument whena_minanda_maxare provided is forbidden."). Oroutis read-only (checked before every ufunc argument). Or the operands do not broadcast together, oroutwould have to be stretched (NumPy's two iterator texts).- TypeError
A
dtypethe inputs cannot reach, or anoutthe result cannot be cast into, under the same_kind rule (NumPy's UFuncTypeError texts, naming the routed ufunc).- ArgumentException
A
wherethat is not bool ("Cannot cast array data from dtype('int64') to dtype('bool') according to the rule 'safe'").- OverflowError
An integer bound that is kept does not fit the integer dtype the computation runs in, for example
np.clip(int8_array, 1000, 2000): "Python integer 1000 out of bounds for int8" (NumPy's OverflowError). It is raised before any element is read, so an empty array raises too.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
column_stack(params NDArray[])
Stack 1-D arrays as columns into a 2-D array. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack(params NDArray[]). 1-D arrays are turned into 2-D columns first.
public static NDArray column_stack(params NDArray[] tup)
Parameters
tupNDArray[]Arrays to stack. All of them must have the same first dimension.
Returns
- NDArray
The 2-D array formed by stacking the given arrays. A
numpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
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.).- ArgumentNullException
tupis null, or one of its entries is (the parameter is then namedtup[i]).- ValueError
tupis empty ("need at least one array to concatenate").- IncorrectShapeException
Arrays whose ranks or first dimensions differ once turned into columns.
- InvalidCastException
An array that does not cast to the result dtype.
common_type(params NDArray[])
Return a scalar type which is common to the input arrays.
public static DType common_type(params NDArray[] arrays)
Parameters
arraysNDArray[]Input arrays; none is allowed, as in NumPy.
Returns
- DType
The common scalar type: always inexact (float64 at least for integers), complex when any input is complex, and NumPy's starting precision — float16 — when no array is given (
np.common_type()isnumpy.float16, thearray_type[0][0]its loop starts from).
Examples
np.common_type(np.array(new int[] {1, 2})) // float64
np.common_type(a_float32, a_float64) // float64
np.common_type() // float16
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.common_type.html
The return type will always be a floating-point type (minimum float64 for integers). This differs from result_type which may return an integer type.
Exceptions
- TypeError
An input is not numeric (a bool array: NumPy's "can't get common type for non-numeric array").
common_type_code(params NDArray[])
Return a scalar type code which is common to the input arrays.
public static NPTypeCode common_type_code(params NDArray[] arrays)
Parameters
arraysNDArray[]Input arrays; none gives float16, as common_type(params NDArray[]) does.
Returns
- NPTypeCode
The common scalar type as NPTypeCode.
Remarks
The return type will always be a floating-point type (minimum Double for integers).
Exceptions
- ArgumentNullException
arraysis null.- TypeError
An input is a bool array (not numeric for
common_type).
common_type_code(params NPTypeCode[])
Return a scalar type code which is common to the input type codes.
public static NPTypeCode common_type_code(params NPTypeCode[] types)
Parameters
typesNPTypeCode[]Input type codes; none gives Half.
Returns
- NPTypeCode
The common scalar type as NPTypeCode.
Remarks
NumPy common_type rules:
- Any Complex input -> Complex (complex128).
- Any Decimal input (NumSharp extension) -> Decimal.
- Any integer/bool/char input -> Double (any int presence forces float64).
- Otherwise (all float16/float32/float64): return max-precision float — float16 when there is no input at
all, because NumPy's loop starts from precision 0 (
half) and never raises it.
Exceptions
- ArgumentNullException
typesis null.- TypeError
A type is Boolean (not numeric for
common_type).
compress(NDArray, NDArray, int?, NDArray)
Return selected slices of a along the given
axis at positions where the 1-D
condition is truthy.
public static NDArray compress(NDArray condition, NDArray a, int? axis = null, NDArray @out = null)
Parameters
conditionNDArray1-D array of booleans (or any dtype interpreted as truthy). Must be 1-D — a 2-D or 0-D condition raises ValueError, NumPy's
ValueError("condition must be a 1-d array"). Iflen(condition) < a.shape[axis], only the firstlen(condition)positions alongaxisare considered; if longer, any True beyonda.shape[axis]raises IndexOutOfRangeException.aNDArraySource array.
axisint?Axis along which to slice.
null(default) flattensafirst.outNDArrayOptional destination. When supplied, shape must match the natural output and
out.dtypemust be safely castable toa.dtype; values are written via copyto(NDArray, NDArray, string, NDArray) with unsafe casting and the method returnsoutitself (matches NumPy's out= dispatch via PyArray_TakeFrom).
Returns
- NDArray
A copy of
awithout the slices alongaxisfor whichconditionis false. Dtype matchesa(orout's dtype when supplied). Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.compress.html
Two execution paths:
-
Fast path: bool condition, contig source, no out= or
out= matches src.dtype,
condition.size <= a.shape[axis]. Runs the fused mask-driven gather kernel (popcount → alloc → SIMD bit-scan + cpblk-per-outer-slab), skipping the flatnonzero indices NDArray. -
Generic path: mirrors NumPy's
PyArray_Compresschain — flatnonzero(cond) → take(a, indices, axis, out, "raise"). Handles non-bool conditions, out= with safe dtype cast, and OOB-True via take's RAISE mode.
When condition is 1-D extract(NDArray, NDArray) with
axis = null is equivalent.
Exceptions
- ArgumentNullException
conditionorais null.- ValueError
conditionis not 1-D.- AxisError
axisis out of range fora's rank (rank 1 for a 0-da, which NumPy ravels first).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
concat(NDArray[], int?, NDArray, DType, string)
Join a sequence of arrays along an existing axis. Alias of concatenate(NDArray[], int?, NDArray, DType, string) introduced in NumPy 2.0 for Array API compatibility.
public static NDArray concat(NDArray[] arrays, int? axis = 0, NDArray @out = null, DType dtype = null, string casting = "same_kind")
Parameters
arraysNDArray[]The arrays must have the same shape, except in the dimension corresponding to
axis(the first, by default).axisint?The axis along which the arrays will be joined. If
null, arrays are flattened before use. Default is 0.outNDArrayIf provided, the destination to place the result. Cannot be used together with
dtype.dtypeDTypeIf provided, the result array will have this dtype. Cannot be used together with
out.castingstringControls what kind of data casting may occur. One of
"no","equiv","safe","same_kind"(default), or"unsafe".
Returns
- NDArray
The concatenated array.
Remarks
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.).
concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate(NDArray[], int?, NDArray, DType, string)
Join a sequence of arrays along an existing axis.
public static NDArray concatenate(NDArray[] arrays, int? axis = 0, NDArray @out = null, DType dtype = null, string casting = "same_kind")
Parameters
arraysNDArray[]The arrays must have the same shape, except in the dimension corresponding to
axis(the first, by default).axisint?The axis along which the arrays will be joined. If
null, arrays are flattened before use — a 0-d array included, which joins as one element (an axis refuses a 0-d FIRST array: "zero-dimensional arrays cannot be concatenated"; a later one fails NumPy's rank check). Default is 0. Negative axes are normalized against the input ndim.outNDArrayIf provided, the destination to place the result. The shape must be correct, matching what would have been returned with no
outargument. Cannot be used together withdtype.dtypeDTypeIf provided, the result array will have this dtype. Cannot be used together with
out.castingstringControls what kind of data casting may occur. One of
"no","equiv","safe","same_kind"(default), or"unsafe".
Returns
- NDArray
The concatenated array (
outitself when given).
Remarks
Exceptions
- ArgumentNullException
arraysor one of its elements is null.- ArgumentException
An unknown
castingname; bothoutanddtype.- ValueError
No arrays (
need at least one array to concatenate); a 0-d FIRST array with an axis (zero-dimensional arrays cannot be concatenated; NumPy's ValueError —axis=Noneravels it into one element instead).- AxisError
axisis out of bounds for the inputs' rank.- IncorrectShapeException
The inputs' ranks or non-axis dimensions differ - a later 0-d array included (
all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 0 dimension(s), as NumPy reports it) - orouthas the wrong rank or shape (NumPy's ValueError texts).- InvalidCastException
An input does not cast to the result dtype under
casting(NumPy's TypeError text).- ValueError
Numbers joined into a numeric
dtypewith text that does not parse as that number (the string route, inNDArray.Multiarray.cs, formats numbers into a text result and parses text into a numeric one).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
conj(NDArray, NDArray, NDArray, DType)
Alias of conjugate(NDArray, NDArray, NDArray, DType) — return the
complex conjugate, element-wise (NumPy: np.conj is np.conjugate).
public static NDArray conj(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArrayA location into which the result is stored (must be the same shape; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop and its output dtype.
Returns
Remarks
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.).
conjugate(NDArray, NDArray, NDArray, DType)
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the sign of its
imaginary part. For real-valued input the conjugate is the value itself.
Mirrors NumPy's ufunc signature conjugate(x, /, out=None, *, where=True, dtype=None).
public static NDArray conjugate(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArrayA location into which the result is stored (must be the same shape; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=). Masked-off slots keep the prior contents of
out.dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop and its output dtype.
Returns
- NDArray
The complex conjugate of
x. For real dtypes this is a copy of the input values (dtype preserved) — EXCEPTbool, which NumPy has no loop for and therefore resolves to theint8loop (values 0/1); for Complex the imaginary sign is flipped.
Remarks
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.).
convolve(NDArray, NDArray, string)
Returns the discrete, linear convolution of two one-dimensional sequences.
The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal[1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions.
If v is longer than a, the arrays are swapped before computation.
public static NDArray convolve(NDArray a, NDArray v, string mode = "full")
Parameters
aNDArrayThe first one-dimensional input sequence (a 0-d array is one element, NumPy's
ndmin=1).vNDArrayThe second one-dimensional input sequence (likewise); it is the one reversed, after the swap that makes the longer sequence the data.
modestring'full'(the default: every overlap,len(a) + len(v) - 1points),'same'(max(len(a), len(v))points, centred) or'valid'(only the full overlaps). The name is case-sensitive, as in NumPy.
Returns
- NDArray
A fresh 1-D array of the operands' common dtype (
result_type(a, v)): the discrete, linear convolution ofaandv.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.convolve.html
NumPy's Python body (numpy/_core/numeric.py) runs in the engine member
Convolve(NDArray, NDArray, string) (the engine of a); its last
statement, multiarray.correlate(a, v[::-1], mode), is the engine member
Correlate(NDArray, NDArray, string). Unlike correlate(NDArray, NDArray, string), a complex kernel is NOT
conjugated, and the swap needs no reversal of the result (convolution is commutative). The order of the errors
is NumPy's: the two emptiness texts (on the operands as given) come before the mode, and the mode before the
depth check. Both functions share one kernel; see correlate(NDArray, NDArray, string) for its bit parity.
Exceptions
- ValueError
a cannot be empty/v cannot be empty(on the operands as given, before the length swap), then an unknownmode(Use one of 'valid', 'same', or 'full' for convolve/correlate modewhen its first letter names a mode, elsemode must be one of 'valid', 'same', or 'full' (got 'x')with the argument in Python'srepr),object too deep for desired arrayfor an operand of two or more dimensions (anumpy.matrixoperand included, as in NumPy), or — for a fixed-width string operand, after every check above —function not available for this data type.- UnicodeEncodeError
A
modeholding a lone surrogate (CPython's UTF-8 encoding error, raised before the mode is read).- TypeError
A null
mode(NumPy'sNone):convolve/correlate mode not understood. AStringDTypeoperand (after the emptiness checks and the swap): NumPy's legacy-only descriptor refusal, or Python's error from the first product of the OBJECT fallback.- NotSupportedException
A
StringDTypeoperand whose OBJECT product NumPy computes (an object array, which NumSharp does not have).
copy(NDArray, char, bool)
Return an array copy of the given object.
public static NDArray copy(NDArray a, char order = 'K', bool subok = false)
Parameters
aNDArrayInput data.
ordercharControls the memory layout of the copy. 'C' - row-major, 'F' - column-major, 'A' - 'F' if source is F-contiguous else 'C', 'K' - match source layout as closely as possible.
subokboolTrue to keep the class of a subclass object (NumPy's
array(a, order=order, subok=True, copy=True)): the copy of anumpy.char.chararrayis a chararray that owns its data, the copy of anumpy.matrixa matrix. False (the default, as in NumPy) returns a plain array whateverais — use it when the copy is passed to code written for plain arrays.
Returns
- NDArray
Array interpretation of a: a new array holding a copy of its data.
Remarks
Exceptions
- NullReferenceException
ais null.- ValueError
orderis not one of NumPy's order codes (order must be one of 'C', 'F', 'A', or 'K' (got 'Q')).
copysign(NDArray, NDArray, NDArray, NDArray, DType)
Change the sign of x1 to that of x2, element-wise.
Returns the magnitude of x1 carrying the sign of x2 (the sign of x2 includes its sign
bit, so copysign(3, -0.0) == -3).
Mirrors NumPy's ufunc signature: copysign(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray copysign(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayValues to change the sign of.
x2NDArrayThe sign of x2 is copied to x1. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only).
Returns
- NDArray
The values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars.
Remarks
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.).
copyto(NDArray, NDArray, string, NDArray)
Copies values from one array to another, broadcasting as necessary: NumPy's np.copyto(dst, src,
casting='same_kind', where=True), a statement-for-statement port of array_copyto →
PyArray_AssignArray (numpy/_core/src/multiarray/array_assign_array.c).
public static void copyto(NDArray dst, NDArray src, string casting = "same_kind", NDArray where = null)
Parameters
dstNDArrayThe array into which values are copied (written in place).
srcNDArrayThe array from which values are copied. It broadcasts to
dst's shape; leading axes of extent 1 beyonddst's rank are stripped first (NumPy's backward compatibility rule), so a(1, 3)source fills a(3,)destination. A 0-d array is a SCALAR source (NumPy'sPyArray_AssignRawScalar): cast once, then written to every selected element. An NDArray is always NumPy's ndarray (STRONG); a C# number binds copyto<T>(NDArray, T, string, NDArray) instead, which is NumPy's Python scalar (weak). A null ((NDArray)null) is Python'sNone: NumPy's 0-d OBJECT array, castable only undercasting='unsafe', where it stores NaN /nan+nanj/False/'None'/ aStringDTypeNA object, or raisesint(None)'s TypeError for an integer destination.castingstringWhich casts from
src's dtype todst's are allowed:"no","equiv","safe","same_kind"(the default) or"unsafe".whereNDArrayA bool mask broadcast to
dst's shape: elements are written only where it is true.null(the default) is NumPy'swhere=True. A 0-d mask is NumPy's scalar optimization: true copies everything, false copies nothing (after the source shape has been checked).
Remarks
NumPy's checks, in NumPy's order (each probed on 2.4.2): the casting name, the where mask's
dtype, then — for an array source — a redundant self-copy returns at once (the same data, dtype, shape and
strides: np.copyto(a, a) is legal even when a is read-only), the read-only destination, the
cast rule, the source's broadcast, the 0-d mask, the mask's broadcast; for a 0-d source: the read-only
destination, the cast rule, the mask's broadcast.
Overlap. A source that may share memory with the destination is copied first, as NumPy does,
unless the destination is 1-D with both runs in the same direction; then the copy walks in NumPy's raw order
(a negative destination stride flipped; backward when the source starts below the destination inside it), so
overlapping views with different strides give NumPy's bits (np.copyto(a[3:19:2], a[6:14]) reads
elements it has already written, in NumPy and here).
Kernels. The masked copy is a bit copy of the destination's element width over NumPy's prepared iteration (TryGetMaskedAssignKernel(int)): a SIMD blend for contiguous runs, a hoisted value for a broadcast source, a branch-free select otherwise. A source of another dtype is cast into the destination's dtype first (one element per distinct source element, laid out in the destination's memory order). The unmasked copy is Copy(UnmanagedStorage, UnmanagedStorage).
Operand roots. NDAnchoredAttribute: the kernels read raw addresses and the copy runs
storage to storage, so a caller's temporary src, where or even
dst (np.copyto(np.zeros(n), x)) would otherwise be collectable mid-copy and its
buffer pooled under the kernel. The weaver roots all three until the call returns; no scope is opened (this
is a hot internal primitive, and it builds no array it reads after its last use).
Exceptions
- TypeError
castingisnull: "casting must be str, not NoneType".- ValueError
castingis not one of the five names ("casting must be one of 'no', 'equiv', 'safe', 'same_kind', 'unsafe' (got '…')");dstis read-only ("assignment destination is read-only");srcdoes not broadcast todst("could not broadcast input array from shape (4,) into shape (3,)"); orwheredoes not ("could not broadcast where mask from shape (2,) into shape (3,)") — NumPy's ValueError texts.- ArgumentException
whereis not a bool array: "Cannot cast array data from dtype('int64') to dtype('bool') according to the rule 'safe'" ("scalar" for a 0-d mask) — NumPy's TypeError text, under the house type every ufunc'swhere=check raises.- InvalidCastException
The cast from
src's dtype todst's is not allowed undercasting: "Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'same_kind'" ("Cannot cast scalar from …" for a 0-d source) — NumPy's TypeError text, under the house type of every cast check (astype, concatenate, NDIter); aNonesource under any rule but'unsafe'("Cannot cast scalar from dtype('O') to …").- TypeError
A
Nonesource (srcnull) undercasting='unsafe'into an integer ordecimaldestination with an element to convert: Python'sint(None).- ArgumentNullException
dstisnull.
copyto(NDArray, BigInteger, string, NDArray)
np.copyto(dst, src) with an arbitrary-size integer source — NumPy's Python int of any magnitude
(weak, range-checked against the destination). See copyto<T>(NDArray, T, string, NDArray).
public static void copyto(NDArray dst, BigInteger src, string casting = "same_kind", NDArray where = null)
Parameters
dstNDArrayThe array into which the value is copied.
srcBigIntegerThe integer.
castingstringwhereNDArray
Remarks
NDAnchoredAttribute: the destination and the mask stay reachable while the fill kernel runs, as on copyto(NDArray, NDArray, string, NDArray).
Exceptions
- OverflowError
The integer does not fit an integer destination (NumPy's OverflowError texts), or is past the double range for a float destination ("int too large to convert to float").
- TypeError
- ValueError
- ArgumentException
- InvalidCastException
- ArgumentNullException
dstisnull.
copyto(NDArray, string, string, NDArray)
np.copyto(dst, src) with a Python str source: NumPy's PyArray_FromAny(src) makes it a 0-d
Unicode array of its own length ('abcdef' is <U6), which is then assigned like any 0-d source —
truncated into a shorter U destination, ASCII-encoded into an S one (under a casting rule that
allows U → S: 'unsafe').
public static void copyto(NDArray dst, string src, string casting = "same_kind", NDArray where = null)
Parameters
dstNDArrayThe array into which the text is copied.
srcstringThe text (not null).
castingstringwhereNDArray
Remarks
A C# string would otherwise reach copyto(NDArray, NDArray, string, NDArray) through
NumSharp's implicit string → NDArray conversion, which still reads "[1, 2]"-shaped text as a numeric
matrix (a legacy NumSharp shorthand); this overload keeps every text a text, as NumPy does.
NDAnchoredAttribute: the destination and the mask stay reachable while the copy runs, as on
copyto(NDArray, NDArray, string, NDArray) (the text's own array is the using local).
Exceptions
- ArgumentNullException
dstorsrcisnull.- InvalidCastException
The cast from
<U{len}to the destination's dtype is not allowed:Cannot cast scalar from dtype('<U6') to dtype('S3') according to the rule 'same_kind'.- UnicodeEncodeError
The text is not ASCII and the destination is
S.- OverflowError
The destination is an integer dtype and the text is an integer outside it (NumPy's LP64 OverflowError texts).
- SystemError
The text is one unit above U+10FFFF (only reachable through a raw view).
- ValueError
See copyto(NDArray, NDArray, string, NDArray); also a numeric destination the text does not parse into (
invalid literal for int() with base 10: np.str_('x')— NumPy parses the 0-d array the text became, so it quotes the NumPy scalar).- TypeError
- ArgumentException
copyto<T>(NDArray, T, string, NDArray)
np.copyto(dst, src) with a C# scalar source — NumPy's Python scalar. A C# integer, float,
double or Complex is WEAK (NEP 50): it takes the destination's dtype within its kind, so
np.copyto(uint8_array, 0) and np.copyto(float32_array, 0.1, casting: "safe") are legal, and an
integer that does not fit the destination raises instead of wrapping. A bool, Half,
char or decimal is STRONG (a Python bool, a NumPy scalar): a 0-d array of its own dtype.
public static void copyto<T>(NDArray dst, T src, string casting = "same_kind", NDArray where = null) where T : unmanaged
Parameters
Type Parameters
TThe C# scalar type. Pass an NDArray (0-d or not) for NumPy's ndarray semantics:
NDArray.Scalar(1000L)into int8 wraps to -24 likenp.array(1000), while the literal1000raises like the Python int.
Remarks
NumPy's array_copyto: npy_mark_tmp_array_if_pyscalar marks the scalar weak,
npy_find_descr_for_scalar picks the dtype it is stored in — the common DType of the scalar's abstract
class (_PyLongDType, _PyFloatDType, _PyComplexDType) and the destination's class: the
destination's own dtype for a number of a kind it can hold, int64 for an int into bool, float64 for a float
into an integer or bool — and npy_update_operand_for_scalar stores it there with the element setter
(PyArray_Pack: range-checked, never wrapped). The 0-d value is then assigned like any 0-d source.
NumSharp has one complex width, so a complex into a float32 destination is resolved (and reported) as complex128 where NumPy says complex64.
Operand roots. NDAnchoredAttribute, as on copyto(NDArray, NDArray, string, NDArray): the destination and the mask stay reachable while the fill kernel writes and reads them, even when the caller passed them as temporaries.
Exceptions
- OverflowError
A weak integer does not fit an integer destination: "Python integer 1000 out of bounds for int8" (NumPy's OverflowError, raised before the mask is checked); a
ulongpast MaxValue into an integer other than uint32/uint64: "Python int too large to convert to C long" (the LP64 text NumSharp pins).- TypeError
castingis"equiv"and the destination's dtype is not the scalar's own default (int64, float64, complex128): "cannot cast Python int to int32 under the casting rule 'equiv'" — NumPy's text; orcastingisnull.- NotSupportedException
Tis an unmanaged type with no NumPy counterpart (for example DateTime).- ValueError
- ArgumentException
- InvalidCastException
The scalar's resolved dtype cannot be cast to the destination's under
casting: a float into an integer destination ("Cannot cast scalar from dtype('float64') to dtype('int32') according to the rule 'same_kind'"), an int into a bool destination (dtype('int64')), a complex into a real one.- ArgumentNullException
dstisnull.
corrcoef(NDArray, NDArray, bool, DType)
Return Pearson product-moment correlation coefficients.
The relationship between the correlation coefficient matrix R and the
covariance matrix C (see cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType)) is
R_ij = C_ij / sqrt(C_ii * C_jj). The values of R are between
-1 and 1, inclusive.
public static NDArray corrcoef(NDArray x, NDArray y = null, bool rowvar = true, DType dtype = null)
Parameters
xNDArrayA 1-D or 2-D array containing multiple variables and observations. Each row of
xrepresents a variable, each column a single observation of all those variables (seerowvar).yNDArrayAn additional set of variables and observations, same shape as
x.rowvarboolIf true (default) each row is a variable with observations in the columns. Otherwise the relationship is transposed: each column is a variable, rows are observations.
dtypeDTypeData-type of the result. By default the result has at least float64 precision.
Returns
- NDArray
The correlation coefficient matrix of the variables.
Remarks
Port of NumPy 2.4.2's numpy/lib/_function_base_impl.corrcoef — a thin wrapper
over cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType). Like NumPy 2.x this exposes ONLY x/y/rowvar/
dtype; the long-deprecated bias/ddof parameters were removed and are
not offered. All dtype/promotion/edge behaviour is inherited from cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType), so
the result is bit-identical to NumPy for float64/complex128 (within the managed GEMM's
rounding) and within that GEMM's ULP tolerance for float32/float16 — the same parity
profile as cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType) itself. Due to floating-point rounding the diagonal may not
be exactly 1 and off-diagonal magnitudes may nudge past 1; the real (and, for complex
input, imaginary) parts are therefore clipped to [-1, 1], exactly as NumPy does.
The statements are Corrcoef(NDArray, NDArray, bool, DType), on x's engine.
https://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html
Exceptions
- ArgumentNullException
xis null.- ValueError
More than 2 dimensions, and the other refusals of cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType) that its
m/y/rowvar/dtypecan reach (Corrcoef(NDArray, NDArray, bool, DType) lists them).- IncorrectShapeException
Numeric variables with different observation counts.
- TypeError
Text that cov's mean refuses.
- DTypePromotionError
StringDTypevariables withoutdtype.- ArgumentException
An integer or bool
dtype.
correlate(NDArray, NDArray, string)
Cross-correlation of two 1-dimensional sequences.
c_k = sum_n a_{n+k} * conj(v_n) — the signal-processing convention.
public static NDArray correlate(NDArray a, NDArray v, string mode = "valid")
Parameters
aNDArrayFirst one-dimensional input sequence.
vNDArraySecond one-dimensional input sequence (complex-conjugated internally).
modestring'valid' (default), 'same', or 'full'. Note the default is 'valid', unlike convolve(NDArray, NDArray, string) which defaults to 'full'.
Returns
- NDArray
Discrete cross-correlation of
aandv.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.correlate.html
Port of NumPy 2.4.2's PyArray_Correlate2 + _pyarray_correlate +
small_correlate. correlate is non-commutative: when len(a) < len(v) the
operands are swapped and the output time-reversed, and a complex v is
conjugated — so correlate(v, a) is the time-reversed conjugate of
correlate(a, v).
The output dtype is result_type(a, v). The sliding multiply-accumulate is
outer-vectorized over output positions with SIMD for the 10 Vector<T>-capable
dtypes (byte/sbyte/int/uint families + float32/float64; char via ushort) and scalar for
Half/Complex/Decimal/Boolean, except that a LONG float32 / float64 / complex128 / float16
product runs a blocked SIMD kernel on a host with AVX and FMA
(Backends/Default/Math/Sliding/SlidingDot.Long.cs); one engine serves
convolve(NDArray, NDArray, string) too.
Float bit-parity. Each output accumulates sum_t a[i+t]*k[t] in t-order with
separate multiply-then-add (never FMA), matching NumPy's small_correlate exactly —
so the result is byte-identical to NumPy for the small-kernel regime. Where NumPy reduces
a position with its dotfunc instead, NumSharp reproduces each dotfunc's scalar regime
byte for byte (ddot below 16 terms, sdot below 32, zdotu below 8,
float16's HALF_dot at every length); a float32 / float64 / complex128 position at or
past the dot's vector block carries a bounded-ULP divergence, because NumPy sums it in
OpenBLAS's order — which NumSharp.Interop.OpenBLAS reproduces byte for byte when it
is referenced. Integer, bool and decimal outputs are exact at every size (modular / exact
arithmetic does not depend on the order).
The body is NumPy's C function multiarray.correlate2, the engine member
Correlate2(NDArray, NDArray, string). A numpy.matrix operand is two-dimensional, so it is
refused as too deep, as in NumPy.
Exceptions
- ValueError
First an unknown
mode(Use one of 'valid', 'same', or 'full' for convolve/correlate modewhen its first letter names a mode, elsemode must be one of 'valid', 'same', or 'full' (got 'x')with the argument in Python'srepr); thenobject of too small depth for desired array(a 0-d operand) orobject too deep for desired array(two or more dimensions),first array argument cannot be empty/second array argument cannot be empty, or — for a fixed-width string operand, after every check above —function not available for this data type.- UnicodeEncodeError
A
modeholding a lone surrogate (CPython's UTF-8 encoding error, raised before the mode is read).- TypeError
A null
mode(NumPy'sNone):convolve/correlate mode not understood, before any operand check. AStringDTypeoperand: NumPy's legacy-only descriptor refusal, or Python's error from the first product of the OBJECT fallback.- NotSupportedException
A
StringDTypeoperand whose OBJECT product NumPy computes (an object array, which NumSharp does not have).
cos(NDArray, NDArray, NDArray, DType)
Cosine element-wise.
Mirrors NumPy's ufunc signature: cos(x, /, out=None, *, where=True, dtype=None).
public static NDArray cos(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array in radians.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
The cosine of each element of x. This is a scalar if x is a scalar.
Remarks
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.).
cosh(NDArray, NDArray, NDArray, DType)
Hyperbolic cosine, element-wise.
Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j* x).
public static NDArray cosh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
Output array of same shape as x. This is a scalar if x is a scalar.
Remarks
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.).
count_nonzero(NDArray)
Counts the number of non-zero values in the array.
public static long count_nonzero(NDArray a)
Parameters
aNDArrayThe array for which to count non-zeros.
Returns
- long
Number of non-zero values in the array (a text element counts when non-empty); 0 for an empty array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.count_nonzero.html — the count is the engine's
(TensorEngine.CountNonZero). The C# long of NumPy's np.count_nonzero(a) (its
np.intp scalar), kept beside the axis signature below as C# programs read it; with any argument after
a C# binds the axis signature, whose answer is an array.
Exceptions
- NullReferenceException
ais null.
count_nonzero(NDArray, int, bool)
count_nonzero(NDArray, NDAxis?, bool) with the axis as one int: the overload a C#
integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so
every answer, error, layout and subclass result is that overload's.
public static NDArray count_nonzero(NDArray a, int axis, bool keepdims = false)
Parameters
aNDArrayThe array for which to count non-zeros (any dtype; a text element counts when non-empty).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).keepdimsboolIf True, the counted axes are left in the result as dimensions with size one (keyword-only in NumPy; C# takes it positionally too).
Returns
- NDArray
The int64 counts (NumPy's
intp), laid out as NumPy's sum allocates them; a read-only 0-d array (NumPy's scalar) when every axis is counted withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.count_nonzero.html. NumPy's statements:
if axis is None and not keepdims: return multiarray.count_nonzero(a), else
a.astype(bool, copy=False).sum(axis=axis, dtype=np.intp, keepdims=keepdims) (text through
a != '') - the whole call is the engine's (CountNonZero(NDArray, NDAxis?, bool)).
The counts are integers, so they are exact in any reduction order.
One signature since API-parity batch 4 (2026-11-12): it replaces count_nonzero(a, int axis,
keepdims), which had no tuple and no axis=None with keepdims.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of bounds (the first one in order, as given; every axis is range-checked before the repeat check).
- ValueError
A tuple names an axis twice (
duplicate value in 'axis').
count_nonzero(NDArray, int[], bool)
count_nonzero(NDArray, NDAxis?, bool) with the axes as an int[]: the overload an
int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new
int[0] is ()).
public static NDArray count_nonzero(NDArray a, int[] axis, bool keepdims = false)
Parameters
aNDArrayThe array for which to count non-zeros (any dtype; a text element counts when non-empty).
axisint[]The axes as NumPy's tuple, or
nullfor None.keepdimsboolIf True, the counted axes are left in the result as dimensions with size one (keyword-only in NumPy; C# takes it positionally too).
Returns
- NDArray
The int64 counts (NumPy's
intp), laid out as NumPy's sum allocates them; a read-only 0-d array (NumPy's scalar) when every axis is counted withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.count_nonzero.html. NumPy's statements:
if axis is None and not keepdims: return multiarray.count_nonzero(a), else
a.astype(bool, copy=False).sum(axis=axis, dtype=np.intp, keepdims=keepdims) (text through
a != '') - the whole call is the engine's (CountNonZero(NDArray, NDAxis?, bool)).
The counts are integers, so they are exact in any reduction order.
One signature since API-parity batch 4 (2026-11-12): it replaces count_nonzero(a, int axis,
keepdims), which had no tuple and no axis=None with keepdims.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of bounds (the first one in order, as given; every axis is range-checked before the repeat check).
- ValueError
A tuple names an axis twice (
duplicate value in 'axis').
count_nonzero(NDArray, NDAxis?, bool)
NumPy's np.count_nonzero(a, axis=None, *, keepdims=False): the number of non-zero values along the given
axes (every axis by default).
public static NDArray count_nonzero(NDArray a, NDAxis? axis = null, bool keepdims = false)
Parameters
aNDArrayThe array for which to count non-zeros (any dtype; a text element counts when non-empty).
axisNDAxis?NumPy's
axis:null(None, the default) counts every element; one axis (0,-1) or a tuple ((0, 2),new[] { 0, 2 }) counts along those axes, and the empty tuple counts each element on its own (0 or 1). Negative axes count from the end. A 0-datakes the integer axis 0 or -1 (the sum's rule) and the empty tuple.keepdimsboolIf True, the counted axes are left in the result as dimensions with size one (keyword-only in NumPy; C# takes it positionally too).
Returns
- NDArray
The int64 counts (NumPy's
intp), laid out as NumPy's sum allocates them; a read-only 0-d array (NumPy's scalar) when every axis is counted withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.count_nonzero.html. NumPy's statements:
if axis is None and not keepdims: return multiarray.count_nonzero(a), else
a.astype(bool, copy=False).sum(axis=axis, dtype=np.intp, keepdims=keepdims) (text through
a != '') - the whole call is the engine's (CountNonZero(NDArray, NDAxis?, bool)).
The counts are integers, so they are exact in any reduction order.
One signature since API-parity batch 4 (2026-11-12): it replaces count_nonzero(a, int axis,
keepdims), which had no tuple and no axis=None with keepdims.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of bounds (the first one in order, as given; every axis is range-checked before the repeat check).
- ValueError
A tuple names an axis twice (
duplicate value in 'axis').
cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType)
Estimate a covariance matrix, given data and weights.
Covariance indicates the level to which two variables vary together. Given
N-dimensional samples X = [x_1, x_2, ..., x_N]^T, the covariance matrix
element C_ij is the covariance of x_i and x_j; C_ii is
the variance of x_i.
public static NDArray cov(NDArray m, NDArray y = null, bool rowvar = true, bool bias = false, int? ddof = null, NDArray fweights = null, NDArray aweights = null, DType dtype = null)
Parameters
mNDArrayA 1-D or 2-D array containing multiple variables and observations. Each row represents a variable, each column a single observation of all those variables (see
rowvar).yNDArrayAn additional set of variables and observations, same form as
m.rowvarboolIf true (default) each row is a variable with observations in the columns. Otherwise the relationship is transposed: each column is a variable, rows are observations.
biasboolDefault normalization (false) is by
(N - 1)(unbiased). If true, normalization is byN. Overridden byddof.ddofint?If not null, overrides the default implied by
bias.ddof=1returns the unbiased estimate even when weights are given;ddof=0returns the simple average.fweightsNDArray1-D array of integer frequency weights (number of times each observation is repeated).
aweightsNDArray1-D array of observation vector weights (relative importance of each observation).
dtypeDTypeData-type of the result. By default the result has at least float64 precision.
Returns
- NDArray
The covariance matrix of the variables.
Remarks
Exceptions
- ArgumentNullException
mis null.- ValueError
moryhas more than 2 dimensions; text variables (or a textdtyperequest) whosemandyhave different observation counts (concatenate's text); a negative weight; text that does not parse into a numericdtype; aStringDTyperequest over no observations (add.reduce's "no identity").- IncorrectShapeException
Numeric variables of
mandywith different observation counts (concatenate's text; NumPy's ValueError).- TypeError
A non-integral frequency weight; text the mean refuses (add.reduce's text, the weighted mean's class-only refusal of a sized string descriptor, the division of
StringDTypetext by the count).- RuntimeError
A weight array that is multidimensional or does not have one weight per observation.
- DTypePromotionError
StringDTypevariables withoutdtype(result_type(m, y, float64)), or aStringDTyperequest with weights.- TypeError
An integer or bool
dtype: NumPy's in-placeX -= avg[:, None]cannot cast the float64 mean's difference back (its UFuncTypeError text).- ZeroDivisionError
Weights that sum to zero (the weighted mean's "Weights sum to zero, can't be normalized"; NumPy's ZeroDivisionError).
- OverflowError
An integer text outside an integer
dtype.- OverflowException
Decimal arithmetic out of decimal's range (.NET's own, decimal has no NumPy dtype).
- UnicodeEncodeError
A U → S conversion of non-ASCII text.
- UnicodeDecodeError
An S → U conversion of non-ASCII bytes.
cross(NDArray, NDArray, int, int, int, int?)
Return the cross product of two (arrays of) vectors.
The cross product of a and b in R^3 is a vector
perpendicular to both. Vectors are taken along axisa/axisb
(the last axis by default) and must have 3 components; the 3-vector result is placed along
axisc. NumPy 2.5 removed the 2-vector forms deprecated in 2.0 (a missing third
component read as zero, a scalar z-component for two 2-vectors): for those, compute
x[..., 0] * y[..., 1] - x[..., 1] * y[..., 0] directly, NumPy's own suggestion.
public static NDArray cross(NDArray a, NDArray b, int axisa = -1, int axisb = -1, int axisc = -1, int? axis = null)
Parameters
aNDArrayComponents of the first vector(s).
bNDArrayComponents of the second vector(s).
axisaintAxis of
athat defines the vector(s). By default, the last axis.axisbintAxis of
bthat defines the vector(s). By default, the last axis.axiscintAxis of the result containing the cross product vector(s). By default, the last axis.
axisint?If given, the single axis of
a,band the result that defines the vector(s). Overridesaxisa/axisb/axisc.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.cross.html
A line-for-line port of NumPy's numpy/_core/numeric.py cross: a pure
composition over multiply(NDArray, NDArray, NDArray, NDArray, DType)/negative(NDArray, NDArray, NDArray, DType)/subtract(NDArray, NDArray, NDArray, NDArray, DType)/
moveaxis(NDArray, NDAxis, NDAxis) (no new kernel), so it supports full broadcasting of the leading
axes and its result dtype is promote_types(a.dtype, b.dtype). cross(NDArray, NDArray, int),
the Array-API form, is this function with a single axis.
Exceptions
- ValueError
When either input has zero dimensions, or a vector's length is not 3 (
Both input arrays must be (arrays of) 3-dimensional vectors, but they are 2 and 3 dimensional instead.).- IncorrectShapeException
The leading axes do not broadcast: NumPy's
np.broadcasttext (shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (2,) and arg 1 with shape (3,).), raised before the dtype promotion.- AxisError
When an axis is out of bounds for its operand (
axiscagainst the result's rank, checked right after the broadcast).- TypeError
A text operand: NumPy multiplies the components in the promoted dtype, which has no string loop (checked after the shape checks).
- ArgumentNullException
ais null.
cumprod(NDArray, int?, DType, NDArray)
Return the cumulative product of the elements along a given axis.
public static NDArray cumprod(NDArray a, int? axis = null, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayInput array (NumPy's keyword
a).axisint?Axis along which the cumulative product is computed. The default (None) is to compute the cumprod over the flattened array.
dtypeDTypeType of the returned array and of the accumulator in which the elements are multiplied (NumPy's keyword
dtype). If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.outNDArrayAlternate output array in which to place the result. It must have the same shape and buffer length as the expected output, but its dtype may differ (the result is cast into it with NumPy's unsafe casting) and a reference to
outis returned.
Returns
- NDArray
A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.cumprod.html. The facade only calls ReduceCumMul(NDArray, int?, DType, NDArray), NumPy's whole call (its declaration answers for a subclass
operand). NumPy's signature cumprod(a, axis=None, dtype=None, out=None), keyword for keyword: the
input and the dtype were arr and typeCode until 2026-11-11.
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 read-onlyout(output array is read-only); text that a numericdtypemust parse that does not parse.- AxisError
axisis out of range for the input (a 0-d input counts as 1-D).- TypeError
Text, or a string
dtype: NumPy's refusal (its verbatim text; no multiply loop accumulates text).- IncorrectShapeException
outdoes not have the result's shape: NumPy's text for the path its accumulate takes (parity QA-31): NpyIter'soperands could not be broadcast together with remapped shapes [original->remapped]: (4,3)->(4,3) (3,4)->(3,4)and its siblings along an axis of an N-D input (or with another out dtype),provided out is the wrong size for the accumulation.for every other out of other dimensions — the direct 1-D path (the flattened form included), an out the iterator accepts, an empty input or out (NumPy 2.5's check, ahead of the empty exits).
cumsum(NDArray, int?, DType, NDArray)
Return the cumulative sum of the elements along a given axis.
public static NDArray cumsum(NDArray a, int? axis = null, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayInput array (NumPy's keyword
a).axisint?Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
dtypeDTypeType of the returned array and of the accumulator in which the elements are summed (NumPy's keyword
dtype). If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.outNDArrayAlternate output array in which to place the result. It must have the same shape and buffer length as the expected output, but its dtype may differ (the result is cast into it with NumPy's unsafe casting) and a reference to
outis returned.
Returns
- NDArray
A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html. The facade only calls ReduceCumAdd(NDArray, int?, DType, NDArray), NumPy's whole call (its declaration answers for a subclass
operand). NumPy's signature cumsum(a, axis=None, dtype=None, out=None), keyword for keyword: the
input and the dtype were arr and typeCode until 2026-11-11.
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 read-onlyout(output array is read-only); text a numeric loop must parse that does not parse.- AxisError
axisis out of range for the input (a 0-d input counts as 1-D).- TypeError
Fixed-width text, or a string
dtype, where NumPy's loop resolution refuses (its verbatim text); aStringDTypeinput concatenates.- IncorrectShapeException
outdoes not have the result's shape: NumPy's text for the path its accumulate takes (parity QA-31): NpyIter'soperands could not be broadcast together with remapped shapes [original->remapped]: (4,3)->(4,3) (3,4)->(3,4)and its siblings along an axis of an N-D input (or with another out dtype),provided out is the wrong size for the accumulation.for every other out of other dimensions — the direct 1-D path (the flattened form included), an out the iterator accepts, an empty input or out (NumPy 2.5's check, ahead of the empty exits).
cumulative_prod(NDArray, int?, DType, NDArray, bool)
Return the cumulative product of the elements along a given axis (NumPy 2.1's Array-API alternative to cumprod(NDArray, int?, DType, NDArray)): never flattens an N-D input, and can prepend the product's identity, one.
public static NDArray cumulative_prod(NDArray x, int? axis = null, DType dtype = null, NDArray @out = null, bool include_initial = false)
Parameters
xNDArrayInput array (NumPy's positional-only
x); a 0-d input is read as 1-D (NumPy'satleast_1d).axisint?Axis along which the cumulative product is computed (negative counts from the end).
null(NumPy'sNone, the default) is axis 0 for a 1-D input and an error for an input of two or more dimensions: unlike cumprod(NDArray, int?, DType, NDArray), this function never flattens.dtypeDTypeType of the returned array and of the accumulator;
nullfollows cumprod(NDArray, int?, DType, NDArray)'s rule (an integer narrower than int64 multiplies as int64, uint8 as uint64, bool as int64).outNDArrayAlternate output array; with
include_initialit must be one longer alongaxisthan the input. It is returned.include_initialboolPrepend the identity (one) along
axis, so the result is one longer there:[1, x0, x0 * x1, ...].
Returns
- NDArray
The cumulative products, a new array unless
outwas given (thenoutitself).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.cumulative_prod.html
NumPy's signature cumulative_prod(x, /, *, axis=None, dtype=None, out=None, include_initial=False);
the body is NumPy's _cumulative_func, shared with cumulative_sum(NDArray, int?, DType, NDArray, bool)
(CumulativeFunc(NDArray, bool, int?, DType, NDArray, bool), in np.cumulative_sum.cs).
Exceptions
- ArgumentNullException
xis null.- ValueError
axisisnulland the input has two or more dimensions ("For arrays which have more than one dimensionaxisargument is required."), orout's shape does not fit (NumPy's iterator text).- AxisError
axisis out of bounds for the (at least 1-D) input.- IndexError
axisis out of bounds whileoutandinclude_initialare both given ("list assignment index out of range").
cumulative_sum(NDArray, int?, DType, NDArray, bool)
Return the cumulative sum of the elements along a given axis (NumPy 2.1's Array-API alternative to cumsum(NDArray, int?, DType, NDArray)): never flattens an N-D input, and can prepend the sum's identity, zero.
public static NDArray cumulative_sum(NDArray x, int? axis = null, DType dtype = null, NDArray @out = null, bool include_initial = false)
Parameters
xNDArrayInput array (NumPy's positional-only
x); a 0-d input is read as 1-D (NumPy'satleast_1d).axisint?Axis along which the cumulative sum is computed (negative counts from the end).
null(NumPy'sNone, the default) is axis 0 for a 1-D input and an error for an input of two or more dimensions: unlike cumsum(NDArray, int?, DType, NDArray), this function never flattens.dtypeDTypeType of the returned array and of the accumulator;
nullfollows cumsum(NDArray, int?, DType, NDArray)'s rule (an integer narrower than int64 sums as int64, uint8 as uint64, bool as int64).outNDArrayAlternate output array; with
include_initialit must be one longer alongaxisthan the input. It is returned.include_initialboolPrepend the identity (zero) along
axis, so the result is one longer there:[0, x0, x0 + x1, ...].
Returns
- NDArray
The cumulative sums, a new array unless
outwas given (thenoutitself).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.cumulative_sum.html
NumPy's signature cumulative_sum(x, /, *, axis=None, dtype=None, out=None, include_initial=False);
C# has no keyword-only parameters, so the keywords may also be passed positionally, in NumPy's order. The body
is NumPy's _cumulative_func statement for statement (CumulativeFunc(NDArray, bool, int?, DType, NDArray, bool)).
Exceptions
- ArgumentNullException
xis null.- ValueError
axisisnulland the input has two or more dimensions ("For arrays which have more than one dimensionaxisargument is required."), orout's shape does not fit (NumPy's iterator text).- AxisError
axisis out of bounds for the (at least 1-D) input.- IndexError
axisis out of bounds whileoutandinclude_initialare both given: NumPy indexes its slice list with the axis before it accumulates ("list assignment index out of range").
datetime_data(DType)
Get information about the step size of a date or time type — NumPy's np.datetime_data(dtype):
the unit string and the multiplier of a datetime64 / timedelta64 descriptor
(np.datetime_data(np.dtype("M8[10ns]")) == ("ns", 10); a bare M8 is ("generic", 1)).
public static (string unit, int count) datetime_data(DType dtype)
Parameters
dtypeDTypeA datetime64 or timedelta64 descriptor (any spelling that converts to DType, e.g.
"M8[s]").
Returns
Remarks
Exceptions
- TypeError
cannot get datetime metadata from non-datetime type— verbatim NumPy.
deg2rad(NDArray, NDArray, NDArray, DType)
Convert angles from degrees to radians.
public static NDArray deg2rad(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngles in degrees.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The corresponding angle in radians. This is a scalar if x is a scalar.
Remarks
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.).
degrees(NDArray, NDArray, NDArray, DType)
Convert angles from radians to degrees. Alias for rad2deg.
public static NDArray degrees(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngle in radians.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The corresponding angle in degrees. This is a scalar if x is a scalar.
Remarks
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.).- ArgumentNullException
xis null.
delete(NDArray, NDArray, int?)
NumPy's delete(arr, obj, axis=None) with an index or a mask: the positions obj names
along axis are removed. Selects the integer-array path or the boolean-mask path based on
obj.GetTypeCode; a 0-d or 1-element integer array collapses to the scalar-index path (NumPy's
obj.size == 1 and obj.dtype.kind in "ui": obj = obj.item()).
public static NDArray delete(NDArray arr, NDArray obj, int? axis = null)
Parameters
arrNDArrayInput array.
objNDArrayA boolean mask (removed where true) or an integer index array (a 0-d one is one position, negative from the end); a C#
int[]/long[](positions) orbool[](a mask) converts implicitly, and a C# integer binds delete(NDArray, long, int?), which calls this form.axisint?The axis to delete along;
nulldeletes from the flattened array.
Returns
- NDArray
A fresh array without the selected sub-arrays (F-ordered when
arris). Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
An integer obj of any rank is accepted, as NumPy's fancy keep[obj,] accepts it (its
elements are the indices; one element takes the single-index path).
API-parity batch 13: one of np.delete's forms - the int, int[], long[] and bool[] overloads went (their arguments convert to this one or to the long form, which answer alike).
Scoped by [NDScoped]: the ravel work array, the keep mask, the helpers' chunk views and
the C-order result that an F-ordered relabel supersedes are released on return.
Exceptions
- ArgumentNullException
arrorobjis null.- ValueError
A boolean
objis not 1-D or its length differs from the axis length (NumPy'sboolean array argument obj to delete must be one dimensional and match the axis length of 6; a C#trueis a 0-d mask).- IndexError
obj's dtype is neither boolean nor integer — text, a float, complex, decimal — whatever its size (NumPy'skeep[obj,] = False:arrays used as indices must be of integer (or boolean) type).- IndexOutOfRangeException
An index is outside
[-N, N).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
delete(NDArray, Slice, int?)
NumPy's delete(arr, obj, axis=None) with a slice: the positions obj selects along
axis are removed, obj read through Python's slice.indices(N)
against the axis length.
public static NDArray delete(NDArray arr, Slice obj, int? axis = null)
Parameters
arrNDArrayInput array.
objSliceThe positions to remove, as a slice (
new Slice(1, 4)is NumPy'sslice(1, 4)).axisint?The axis to delete along;
null(default) flattensarrfirst and returns a 1-D result.
Returns
- NDArray
A fresh array without the sliced positions (F-ordered when
arris). Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.delete.html
One of np.delete's forms (API-parity batch 13): a slice has no NDArray form, so it keeps its own; one integer is delete(NDArray, long, int?), every other obj NumPy takes the delete(NDArray, NDArray, int?) form.
Exceptions
- ArgumentNullException
arrorobjis null.- AxisError
axisis out of bounds.- ArgumentException
A slice step of zero.
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
delete(NDArray, long, int?)
NumPy's delete(arr, obj, axis=None) with one integer: the position obj along
axis is removed - NumPy's single-value path for a Python int.
public static NDArray delete(NDArray arr, long obj, int? axis = null)
Parameters
arrNDArrayInput array.
objlongThe position to remove; negative counts from the end. Every C# integer type binds here.
axisint?The axis to delete along;
null(default) flattensarrfirst and returns a 1-D result.
Returns
- NDArray
A fresh array without the position (F-ordered when
arris). Anumpy.char.chararrayoperand gives a chararray VIEW of a text result; a result of another dtype stays plain.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.delete.html
The one integer form C# needs beside NumPy's two (API-parity batch 13): a C# int converts to
both Slice and NDArray by user-defined conversions, so without it
np.delete(a, 1) would not compile (CS0121). It is the delete(NDArray, NDArray, int?)
call with the Python int obj stands for (NumPy's obj as given, a 0-d integer).
Exceptions
- ArgumentNullException
arris null.- AxisError
axisis out of bounds.- IndexOutOfRangeException
objis outside[-N, N)(NumPy'sindex 7 is out of bounds for axis 0 with size 6).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
diag(NDArray, int)
Extract a diagonal or construct a diagonal array.
public static NDArray diag(NDArray v, int k = 0)
Parameters
vNDArrayIf
vis 2-D, return a copy of itsk-th diagonal. Ifvis 1-D, return a 2-D array withvon thek-th diagonal.kintDiagonal in question. Use
k > 0for diagonals above the main diagonal, andk < 0for diagonals below the main diagonal.
Returns
- NDArray
The extracted diagonal or constructed diagonal array. A
numpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diag.html
The two branches differ in view-ness, exactly as in NumPy:
the 1-D branch constructs a fresh, writeable, C-contiguous
(n, n) array (n = v.size + |k|); the 2-D branch delegates to
diagonal(NDArray, int, int, int) and therefore returns a read-only view that shares
storage with v — despite the NumPy docstring's talk of "a
copy" (probed against 2.4.2: np.shares_memory is True and
flags.writeable is False).
Exceptions
- ArgumentException
vis not 1- or 2-dimensional —Input must be 1- or 2-d.(NumPy'sValueError).
diag_indices(int, int)
Return the indices to access the main diagonal of an array.
public static NDArray<long>[] diag_indices(int n, int ndim = 2)
Parameters
nintThe size, along each dimension, of the arrays for which the returned indices can be used.
ndimintThe number of dimensions. Default 2.
Returns
- NDArray<long>[]
ndimindex arrays, eacharange(n), suitable for indexing the main diagonal of an array of shape(n,) * ndim.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diag_indices.html
NumPy's body is idx = np.arange(n); return (idx,) * ndim — the tuple holds
the same array object repeated, so writing through one entry is visible
through all of them (probed against 2.4.2). NumSharp reproduces that aliasing by
returning the identical NDArray<TDType> instance in every slot rather
than ndim independent copies.
A non-positive ndim yields an empty array, mirroring Python's
(idx,) * 0; a negative n yields empty index arrays.
The array OWNS its data (flags.owndata True), as NumPy's fresh np.arange does; it was an alias of
its own buffer (MakeGeneric), which reported OWNDATA False (the open-bugs rundown's bug 8 sweep).
NumPy's statements are the array object's (NDArray.diag_indices); it has no operand, so no class
rule applies.
diag_indices_from(NDArray)
Return the indices to access the main diagonal of an n-dimensional array.
public static NDArray<long>[] diag_indices_from(NDArray arr)
Parameters
arrNDArrayArray, at least 2-D, whose dimensions must all be of equal length.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diag_indices_from.html
<p>Only the shape is read, so no class rule applies; NumPy's statements are the array object's
(<code>NDArray.diag_indices_from</code>).</p>
Exceptions
- ArgumentNullException
arris null.- ArgumentException
input array must be at least 2-dwhenndim < 2, orAll dimensions of input must be of equal lengthwhen the shape is not hyper-cubic (both NumPyValueErrors, verbatim).- OverflowException
The dimension exceeds MaxValue.
diagflat(NDArray, int)
Create a two-dimensional array with the flattened input as a diagonal.
public static NDArray diagflat(NDArray v, int k = 0)
Parameters
vNDArrayInput data, which is flattened (in C order) and set as the
k-th diagonal of the output.kintDiagonal to set; 0, the default, corresponds to the "main" diagonal, a positive (negative)
kgiving the number of the diagonal above (below) the main.
Returns
- NDArray
The 2-D output array of shape
(n, n)wheren = v.size + |k|. Always a freshly allocated, C-contiguous, writeable array. Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diagflat.html
Unlike diag(NDArray, int), diagflat accepts any dimensionality —
the input is raveled first, so a 0-d scalar produces a (1, 1) array and a
3-D input is flattened in C order. Ravel order is logical C order, so an
F-contiguous or strided input is read in row-major index order, not memory order
(probed against NumPy 2.4.2).
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.).
diagonal(NDArray, int, int, int)
Return specified diagonals of a. For a 2-D
array, returns the diagonal as a 1-D array. For an N-D array,
the last two axes (default axis1=0,
axis2=1) define the 2-D sub-arrays from which
diagonals are taken; the diagonal is appended as the last axis
of the returned array.
public static NDArray diagonal(NDArray a, int offset = 0, int axis1 = 0, int axis2 = 1)
Parameters
aNDArraySource array. Must have at least 2 dimensions.
offsetintOffset of the diagonal from the main diagonal. Positive values refer to diagonals above the main, negative below. Default 0.
axis1intFirst axis of the 2-D sub-array. Default 0.
axis2intSecond axis of the 2-D sub-array. Default 1.
Returns
- NDArray
A read-only view sharing storage with
a. Shape:a.shapewithaxis1andaxis2removed and the diagonal appended as the last axis. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diagonal.html
Mirrors NumPy's PyArray_Diagonal (item_selection.c). The
view trick: combining the two strides into one
stride[axis1] + stride[axis2] walks the diagonal in one
step. Read-only by NumPy contract (the writeable-by-default
change pencilled in for NumPy 1.10 hasn't shipped in 2.x).
Exceptions
- ArgumentNullException
ais null.- ValueError
ahas fewer than two dimensions ("diag requires an array of at least two dimensions"), or the two axes are the same axis ("axis1 and axis2 cannot be the same").- AxisError
An axis is out of range: "axis1: axis …" / "axis2: axis …" (axis1 checked first).
diff(NDArray, int, int, object, object)
Calculate the n-th discrete difference along the given axis.
The first difference is out[i] = a[i+1] - a[i]; higher
differences are computed recursively.
public static NDArray diff(NDArray a, int n = 1, int axis = -1, object prepend = null, object append = null)
Parameters
aNDArrayInput array (must be at least one dimensional).
nintThe number of times values are differenced. If zero, the input is returned as-is. Must be non-negative.
axisintThe axis along which the difference is taken; default is the last axis. Negative axes count from the end.
prependobjectValue(s) to prepend to
aalongaxisprior to differencing. Scalars expand to length 1 along the axis.nullmeans "not supplied" (NumPy'snp._NoValue).appendobjectValue(s) to append to
aalongaxisprior to differencing. Scalars expand to length 1 along the axis.nullmeans "not supplied".
Returns
- NDArray
The n-th differences. The shape matches the (optionally prepend/append-extended) input except along
axiswhere the size shrinks byn. The dtype is preserved (boolean input yields boolean output via not_equal).
Remarks
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.).- TypeError
A string array (or a string prepend/append) with
nabove 0: NumPy'ssubtracthas no string loop, so its firsta[1:] - a[:-1]refuses whatever the size.- ValueError
ais 0-D ("diff requires input that is at least one dimensional").- AxisError
axisis out of range fora's rank.- ArgumentNullException
ais null.
digitize(NDArray, NDArray, bool)
Return the indices of the bins to which each value in input array x belongs.
| right | bins order | returned index i satisfies |
|---|---|---|
| false | increasing | bins[i-1] <= x < bins[i] |
| true | increasing | bins[i-1] < x <= bins[i] |
| false | decreasing | bins[i-1] > x >= bins[i] |
| true | decreasing | bins[i-1] >= x > bins[i] |
Values in x beyond the bounds of bins return 0 or
len(bins) as appropriate. Implemented in terms of searchsorted(NDArray, NDArray, string, NDArray).
public static NDArray digitize(NDArray x, NDArray bins, bool right = false)
Parameters
xNDArrayInput array to be binned. May have any shape; the result has the same shape.
binsNDArray1-D monotonic (increasing or decreasing) array of bin edges.
rightboolWhether the intervals include the right or the left bin edge. Default is left-closed (false).
Returns
- NDArray
Array of int64 indices, of the same shape as
x.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.digitize.html
Check order (NumPy's). A complex x first; then _monotonicity(bins), whose
PyArray_FROMANY(bins, NPY_DOUBLE, 1, 1) checks the bins' rank before their 'safe' cast to float64; then the
monotonicity; then searchsorted. So a text x is only reached once the (numeric) bins passed — and when x has
no elements, or the bins are empty, NumPy's answer needs no comparison: an empty int64 array, or all zeros.
Text x. searchsorted(bins, x) converts the numeric bins to x's string kind (their text, as NumPy
formats them) and compares text: digitize(['3', '10'], [2, 5]) is [1, 0], because '10'
sorts before '2'. The bins' text need not be in order (the monotonicity was checked on the numbers); the
search's exact comparisons, ported from NumPy, give NumPy's indices anyway.
Exceptions
- ArgumentNullException
xorbinsis null.- IncorrectTypeException
xis complex (x may not be complex, checked first).- ValueError
binsis not 1-D (object too deep for desired array/object of too small depth for desired array), or, after the cast below, not monotonic (bins must be monotonically increasing or decreasing).- InvalidCastException
binsdoes not cast 'safely' to float64 (text, StringDType included, or complex; NumPy's TypeError text).- TypeError
A
StringDTypex: NumPy's searchsorted compares the numeric bins and the text as Python objects and refuses the first mixed pair ('<' not supported between instances of 'float' and 'str'), or two keys Python cannot order.
divide(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray divide(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
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.).
divmod(NDArray, NDArray, (NDArray Quotient, NDArray Remainder), NDArray, DType)
Return element-wise quotient and remainder simultaneously:
divmod(x1, x2) is equivalent to (floor_divide(x1, x2), remainder(x1, x2)) but
computed in a single fused pass. Item1 (Quotient) is the floored quotient, Item2
(Remainder) the floored remainder (same sign as the divisor). Integer inputs stay
integer (NEP50; bool -> int8); float ÷0 yields (±inf/nan, nan). A complex operand raises NumPy's
TypeError: NumPy has no complex divmod loop.
Mirrors NumPy's two-output ufunc divmod(x1, x2[, out1, out2], / [, out=(None, None)],
*, where=True, dtype=None). In C# the two outputs are a value tuple; pass an
out tuple to write into existing arrays.
public static (NDArray Quotient, NDArray Remainder) divmod(NDArray x1, NDArray x2, (NDArray Quotient, NDArray Remainder) @out = default, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayDividend array.
x2NDArrayDivisor array.
out(NDArray Lhs, NDArray Rhs)Optional pair of output arrays (NumPy ufunc out=); each is written and returned as-is (dtype must be same_kind-castable from the loop dtype).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the loop computes in this dtype.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.divmod.html
<p>One signature, NumPy's ufunc form (2026-11-11): the former overload that took the second operand as an
<code>object</code> read a boxed number as a STRONG array (parity QA-QB30); a C# literal converts to a 0-d array
marked as the Python scalar it stands for, so NEP 50's weak-scalar rule holds without it, and a value held in
an <code>object</code> variable goes through <xref href="NumSharp.np.asanyarray(System.Object%40%2cNumSharp.DType%2cSystem.Nullable%7bSystem.Char%7d%2cSystem.String%2cSystem.Nullable%7bSystem.Boolean%7d)" data-throw-if-not-resolved="false"></xref>.</p>
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.).- TypeError
A complex operand with no
dtype: divmod has no complex loop, so NumPy'sufunc 'divmod' not supported for the input types, ...(parity QA-27); under a realdtype, an input or an out the loop cannot reach by a same_kind cast (NumPy's UFuncTypeError texts); a bool or complexdtype(no loop).
dot(NDArray, NDArray, NDArray)
Dot product of two arrays. See remarks.
public static NDArray dot(NDArray a, NDArray b, NDArray @out = null)
Parameters
aNDArrayLhs, First argument.
bNDArrayRhs, Second argument.
outNDArrayOutput argument. Unlike a ufunc's
out,np.dot's is STRICT (itsnew_array_for_sumincommon.c): it must have the EXACT result dtype, the exact number of dimensions, be C-contiguous and writeable — no casting or broadcasting. A dtype / ndim / non-C-array mismatch is"output array is not acceptable (must have the right datatype, number of dimensions, and be a C-Array)"; a same-ndim shape mismatch is"output array has wrong dimensions". Returned as-is when given.
Returns
- NDArray
Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.dot.html
Specifically,
- If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
- If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
- If either a or b is 0-D(scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a* b is preferred.
- If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
- If a is an N-D array and b is an M-D array(where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
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.); an out array the strict check refuses (the two texts above).- IncorrectShapeException
Misaligned operands (NumPy's
shapes (…) and (…) not alignedValueError text).
dsplit(NDArray, int)
Split array into multiple sub-arrays along the 3rd axis (depth).
public static NDArray[] dsplit(NDArray ary, int indices_or_sections)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintIf an integer, N, the array will be divided into N equal arrays along axis 2. If such a split is not possible, an error is raised.
Returns
- NDArray[]
A list of sub-arrays as views into ary. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
Equivalent to split with axis=2. Array must have ndim >= 3. https://numpy.org/doc/stable/reference/generated/numpy.dsplit.html
Exceptions
- ArgumentException
aryhas fewer than three dimensions ("dsplit only works on arrays of 3 or more dimensions"; NumPy raises the text as a ValueError) - anumpy.matrixalways does.- ValueError
The sections are not positive ("number sections must be larger than 0."), or do not divide the axis ("array split does not result in an equal division").
- NullReferenceException
aryis null (its rank is read first).
dsplit(NDArray, int[])
Split array into multiple sub-arrays along the 3rd axis (depth).
public static NDArray[] dsplit(NDArray ary, int[] indices)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indicesint[]A 1-D array of sorted integers indicating where along axis 2 the array is split. For example, [2, 3] would result in ary[:,:,:2], ary[:,:,2:3], ary[:,:,3:].
Returns
- NDArray[]
A list of sub-arrays as views into ary. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
Equivalent to split with axis=2. Array must have ndim >= 3. https://numpy.org/doc/stable/reference/generated/numpy.dsplit.html
Exceptions
- ArgumentException
aryhas fewer than three dimensions ("dsplit only works on arrays of 3 or more dimensions"; NumPy raises the text as a ValueError) - anumpy.matrixalways does.- ArgumentNullException
indicesis null (checked after the rank).- NullReferenceException
aryis null (its rank is read first).
dstack(params NDArray[])
Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape(M, N) have been reshaped to(M, N,1) and 1-D arrays of shape(N,) have been reshaped to(1, N,1). Rebuilds arrays divided by dsplit. This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.
public static NDArray dstack(params NDArray[] tup)
Parameters
tupNDArray[]The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape.
Returns
- NDArray
The array formed by stacking the given arrays, will be at least 3-D. A
numpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
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.).- ArgumentNullException
tupis null.- ValueError
tupis empty ("need at least one array to concatenate").- NullReferenceException
An entry of
tupis null.- IncorrectShapeException
Arrays whose ranks, or dimensions other than the third, differ once made three-dimensional.
- InvalidCastException
An array that does not cast to the result dtype.
dtype(DType, bool, bool, IReadOnlyDictionary<string, object>)
A descriptor converts to itself — np.dtype(np.dtype('f8')) is the same object, unless a keyword asks for a copy.
public static DType dtype(DType dtype, bool align = false, bool copy = false, IReadOnlyDictionary<string, object> metadata = null)
Parameters
dtypeDTypeThe descriptor, or null — NumPy's
None, the default float64 descriptor (NumSharp.np.DefaultTypeDescr). A null Nullable<T> NPTypeCode reaches this overload through its implicit conversion and reads the same way.alignboolNumPy's
align=; no effect on a non-structured dtype.copyboolNumPy's
copy=: a fresh copy whendtypeis a class singleton (any other descriptor comes back as itself, as in NumPy).metadataIReadOnlyDictionary<string, object>NumPy's
metadata=: merged into the descriptor's own metadata without overwriting its keys, in a fresh descriptor; null means "not given".
Returns
- DType
dtypeitself (the float64 singleton for null), or a fresh copy when a keyword asks for one.
dtype(NDScalarType, bool, bool, IReadOnlyDictionary<string, object>)
The descriptor of a NumPy scalar CLASS — np.dtype(np.float64) where np.float64 is the class: a
concrete class gives its builtin descriptor (the same object np.dtype("f8") returns; the generic
dtype('<M8') singleton for datetime64), and an ABSTRACT class raises NumPy's
TypeError, since it has no dtype.
public static DType dtype(NDScalarType sctype, bool align = false, bool copy = false, IReadOnlyDictionary<string, object> metadata = null)
Parameters
sctypeNDScalarTypeThe scalar class (
(NDScalarType)np.float64, an element ofnp.floating.subclasses(), integer, ...), or null — NumPy'sNone, the default float64 descriptor (NumSharp.np.DefaultTypeDescr).alignboolNumPy's
align=; no effect on a non-structured dtype.copyboolNumPy's
copy=: a fresh copy of the class singleton instead of the singleton.metadataIReadOnlyDictionary<string, object>NumPy's
metadata=: a dictionary to attach (always gives a fresh descriptor); null means "not given".
Returns
- DType
The class's canonical descriptor (float64 for null), or a fresh copy when
copyormetadataasks for one.
Exceptions
- TypeError
sctypeis abstract — NumPy's texts, verbatim:Converting 'np.integer' or 'np.signedinteger' to a dtype is not allowed,Converting(also fornp.inexactornp.floatingto a dtype not allowednp.number),Converting,np.unsignedintegerto a dtype is not allowedConverting,np.complexto a dtype is not allowed.Converting,np.characterto a dtype is not allowedConverting(also fornp.genericto a dtype is not allowed.np.flexible).
dtype(NPTypeCode, bool, bool, IReadOnlyDictionary<string, object>)
The descriptor of an NPTypeCode — NumSharp's storage enum spelling.
public static DType dtype(NPTypeCode typecode, bool align = false, bool copy = false, IReadOnlyDictionary<string, object> metadata = null)
Parameters
typecodeNPTypeCodeThe storage code.
alignboolNumPy's
align=; no effect on a non-structured dtype.copyboolNumPy's
copy=: a fresh copy of the class singleton instead of the singleton.metadataIReadOnlyDictionary<string, object>NumPy's
metadata=: a dictionary to attach (always gives a fresh descriptor); null means "not given".
Returns
- DType
The class's canonical instance, or a fresh copy when
copyormetadataasks for one.
Exceptions
- ArgumentException
typecodeis Empty.- NotSupportedException
typecodehas no registered class.
dtype(string, bool, bool, IReadOnlyDictionary<string, object>)
Create a data type object from a NumPy dtype string — the port of descriptor.c's
_convert_from_str (NumPy 2.4.2), the coercion point behind np.dtype('…') and every
dtype= keyword.
public static DType dtype(string dtype, bool align = false, bool copy = false, IReadOnlyDictionary<string, object> metadata = null)
Parameters
dtypestringAny NumPy-style dtype string: a single type code (
"d","?","q"), a kind plus byte size ("i4","f8","c16","b1"), a name ("float64","intc","longlong","complex128"), a datetime typestr ("M8[ns]","m8","datetime64[10ns]","timedelta64[s/2]"), optionally prefixed with a byte order ("<i4",">f8","=u2","|b1"), or one of NumSharp's PascalCase aliases ("Int32","Single"). Null is NumPy'sNone: the default float64 descriptor (NumSharp.np.DefaultTypeDescr).alignboolNumPy's
align=: pad a STRUCTURED dtype like a C struct. Every NumSharp dtype is non-structured, where NumPy ignores it too (np.dtype('f8', align=True) is np.dtype('f8')), so it is accepted and has no effect.copyboolNumPy's
copy=: return a fresh copy instead of the shared builtin singleton. Only a singleton is copied (NumPy testsfields is None, which only the static builtin descriptors satisfy): a descriptor that is already a fresh object (a non-native byte order, a datetime unit) comes back as itself.metadataIReadOnlyDictionary<string, object>NumPy's
metadata=: a dictionary to attach (see metadata). The result is always a fresh descriptor; when the parsed descriptor already carries metadata the two are merged without overwriting the keys it already has (NumPy'sPyDict_Merge(..., override=0)). Null means "not given".
Returns
- DType
The matching descriptor: the class's canonical instance for a native builtin (so
np.dtype("i8")is the same object every call), a fresh instance for a non-native byte order (">i4"keepsbyteorder == '>',isnative == false) and for every datetime64/timedelta64 descriptor — or a fresh copy whencopyormetadataasks for one. An explicit host byte order is read as native ("<f8"is thefloat64singleton on a little-endian host), as NumPy's parser reads it. A null string gives the float64 singleton (NumPy'snp.dtype(None)).
Remarks
Grammar, in NumPy's order: a comma string (a top-level comma, a leading digit or a leading ()) is split
by NumPy's _commastring into fields of [order] [repeats] [order] dtype, each converted in order:
(type, ()) is the type itself ("()f8" is float64), a repeat count sizes an unsized string class
("5U" is <U5, "2>U" is >U2), any other count is a sub-array and several
fields a structured dtype (both unsupported); the byte-order character is consumed ('|' reads as native,
an explicit host order folds into '=', and a lone byte-order character is invalid); a datetime typestr
(M8/m8/datetime64/timedelta64 + metadata) is parsed by
Parse(string); a one-character code is a type code (a control character below
'\x18' is a TYPE NUMBER: '\x0c' is float64); a code whose tail is an integer is
kind + size (PyArray_TypestrConvert — so "b1" is bool while "b" is int8,
"i3", "f16" and "?1" are invalid); anything else is a NAME looked up in the type
dictionary by the WHOLE string, so a byte-order prefix before a name ("<float64",
"|bool") is "not understood" while it is accepted before a code ("<f8", ">d").
Case matters everywhere ("I4" is not "i4"), whitespace is never stripped. The keywords then
apply in arraydescr_new's order: copy, then metadata.
Null is NumPy's None in every np.dtype overload: the float64 singleton, before the keywords
(copy: true gives a fresh float64, metadata a fresh float64 carrying it). A bare null
literal matches the string and Type overloads alike (CS0121), so write it typed:
np.dtype((string)null), np.dtype((DType)null).
https://numpy.org/doc/stable/reference/arrays.dtypes.html
Exceptions
- NotSupportedException
A valid NumPy dtype NumSharp does not implement — void, object, complex64, the sub-array and structured dtypes a comma string builds (
"3f8","(2,3)i4","i4,f8"): "is not supported by NumSharp". NumPy accepts these, so the refusal is NumSharp's limit, not one of NumPy's errors, and it is raised only where NumPy returns a dtype.- TypeError
A string NumPy cannot parse either, with NumPy's own texts:
data type 'X' not understood(the string quoted by Python'srepr),Alias 'bool8' was removed in NumPy 2.0. Use a name without a digit at the end.; or a malformed datetime unit (Invalid datetime metadata string "[5]" at position 2, verbatim).- ValueError
A datetime divisor that is not a multiple of a lower unit (verbatim); or a comma string NumPy refuses, with NumPy's texts:
format number 2 of "f8,x y" is not recognized,inconsistent byte-order specification < and >,invalid itemsize in generic type tuple("()U","536870912U"),invalid shape in fixed-type tuple.and its: dimension does not fit into a C int./: dtype size in bytes must fit into a C int.variants,Expected at least one field name.- SyntaxError
A comma string whose repeat count is not a Python literal (
"01f8","1 2f8","f8,,i4"):ast.literal_eval's CPython 3.12 texts, such asinvalid syntax (<unknown>, line 1).
dtype(Type, bool, bool, IReadOnlyDictionary<string, object>)
The descriptor of a C# Type — np.dtype(typeof(int)) (NumPy's np.dtype(np.int32)).
public static DType dtype(Type type, bool align = false, bool copy = false, IReadOnlyDictionary<string, object> metadata = null)
Parameters
typeTypeThe C# element type, or null — NumPy's
None, the default float64 descriptor (NumSharp.np.DefaultTypeDescr).alignboolNumPy's
align=; no effect on a non-structured dtype (see dtype(string, bool, bool, IReadOnlyDictionary<string, object>)).copyboolNumPy's
copy=: a fresh copy of the class singleton instead of the singleton.metadataIReadOnlyDictionary<string, object>NumPy's
metadata=: a dictionary to attach (always gives a fresh descriptor); null means "not given".
Returns
- DType
The class's canonical instance (float64 for a null type), or a fresh copy when
copyormetadataasks for one.
Exceptions
- NotSupportedException
typeis not one of NumSharp's element types.
ediff1d(NDArray, object, object)
The differences between consecutive elements of an array. The input is flattened first; the result is always 1-D.
public static NDArray ediff1d(NDArray ary, object to_end = null, object to_begin = null)
Parameters
aryNDArrayInput array (flattened before differencing).
to_endobjectNumber(s) to append to the end of the returned differences.
nullmeans none. Cast toary's dtype under thesame_kindcasting rule.to_beginobjectNumber(s) to prepend to the beginning of the returned differences.
nullmeans none. Cast toary's dtype under thesame_kindcasting rule.
Returns
- NDArray
1-D array of consecutive differences (input dtype), optionally bracketed by
to_beginandto_end.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ediff1d.html
Scoped by [NDScoped]: the ravel, the prepared to_begin /
to_end copies, the slice views of the fallback path and the middle differences
that a concatenation supersedes are released on return, exceptions included, and the result is
yielded. The body no longer repeats that bookkeeping with a hand-written try/finally.
Exceptions
- ArgumentNullException
aryis null.- TypeError
to_beginorto_endcannot be cast toary's dtype undersame_kind: NumPy'sdtype of(parity QA-08).to_beginmust be compatible with inputaryunder thesame_kindrule.- TypeError
aryis boolean (NumPy's boolean-subtract TypeError).- TypeError
aryholds fixed-width strings: NumPy's subtract has no string loop (ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U2'), dtype('<U2')) -> None), raised after theto_begin/to_endchecks, as NumPy raises it.
einsum(params object[])
Evaluates the Einstein summation convention in NumPy's SUBLIST spelling —
np.einsum(a, [0,1], b, [1,2], [0,2]) — where each operand is followed by its
axis labels as integers, and a trailing list gives the output.
public static NDArray einsum(params object[] operands)
Parameters
operandsobject[]Alternating NDArray and subscript list, optionally closed by a lone output list. A subscript list is an
int[], or anobject[]mixing integers with Ellipsis where NumPy writesEllipsis.
Returns
Remarks
Labels are indices into NumPy's einsum_symbols, UPPER case first: 0-25 are
A-Z and 26-51 are a-z, so [0,1] means "AB" (see the
encoding note on FromSublists(object[], out NDArray[])). Anything outside that range raises
ValueError("subscript is not within the valid range [0, 52)"), and a non-integer
entry raises TypeError("each subscript must be either an integer or an ellipsis")
— both NumPy's, verbatim.
https://numpy.org/doc/stable/reference/generated/numpy.einsum.html
The body is Einsum(string, NDArray[], NDArray, DType, char, string, object) (TensorEngine.EinsumFunc.cs), which
DefaultEngine implements as a composition over the matrix products — a port of NumPy's
bmm_einsum (its optimize= path) that reduces each pairwise contraction to
matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char), so it runs through OpenBLAS whenever a backend is referenced
(byte-identical to NumPy for float32/float64/complex128) and through the managed GEMM
otherwise. Integer and boolean contractions are byte-exact; a pure float summation done
outside a product (e.g. ij->i, or across three or more operands) can differ in
the last ULP because its accumulation order follows sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) and a left-to-right
fold. Every rejection below is unchanged — a malformed expression, a wrong operand
count, a bad ellipsis, an impossible diagonal or a shape conflict is reported the same
way and with the same text as NumPy's default parser.
A single-operand expression that sums nothing away answers with a view of the
operand, exactly as NumPy does: np.einsum("ii->i", a) is a WRITEABLE view of
a's diagonal (writing it writes a), "ij->ji" is the transpose
view, and on this path order= and dtype= are ignored — NumPy's view
attempt wins over both keywords.
One deliberate divergence. NumPy carries TWO independent einsum parsers — the C
one behind the default optimize=False, and a Python one behind the
optimize path — and they word their rejections differently for the same input.
NumSharp reproduces the C one, since that is what a default call hits, and uses it
whatever optimize says. The single exception is a label whose extents disagree
between operands: NumPy's C path leaks its ITERATOR's "remapped shapes" text there,
which describes axis bookkeeping rather than the contraction, so NumSharp raises
NumPy's other wording for the identical error —
Size of label 'j' for operand 1 (3) does not match previous terms (4).
A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or
ends with np.concatenate), which drops the class.
einsum(string, params NDArray[])
Evaluates the Einstein summation convention on the operands.
public static NDArray einsum(string subscripts, params NDArray[] operands)
Parameters
subscriptsstringComma-separated subscript labels, optionally followed by
->and the output labels — e.g."ij,jk->ik". Spaces are ignored and...broadcasts. Without->the output is INFERRED: every label used exactly once, in ASCII order (so an upper-case label sorts before a lower-case one), preceded by the broadcast dimensions.operandsNDArray[]The arrays the subscripts label, in order.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.einsum.html
The body is Einsum(string, NDArray[], NDArray, DType, char, string, object) (TensorEngine.EinsumFunc.cs), which
DefaultEngine implements as a composition over the matrix products — a port of NumPy's
bmm_einsum (its optimize= path) that reduces each pairwise contraction to
matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char), so it runs through OpenBLAS whenever a backend is referenced
(byte-identical to NumPy for float32/float64/complex128) and through the managed GEMM
otherwise. Integer and boolean contractions are byte-exact; a pure float summation done
outside a product (e.g. ij->i, or across three or more operands) can differ in
the last ULP because its accumulation order follows sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) and a left-to-right
fold. Every rejection below is unchanged — a malformed expression, a wrong operand
count, a bad ellipsis, an impossible diagonal or a shape conflict is reported the same
way and with the same text as NumPy's default parser.
A single-operand expression that sums nothing away answers with a view of the
operand, exactly as NumPy does: np.einsum("ii->i", a) is a WRITEABLE view of
a's diagonal (writing it writes a), "ij->ji" is the transpose
view, and on this path order= and dtype= are ignored — NumPy's view
attempt wins over both keywords.
One deliberate divergence. NumPy carries TWO independent einsum parsers — the C
one behind the default optimize=False, and a Python one behind the
optimize path — and they word their rejections differently for the same input.
NumSharp reproduces the C one, since that is what a default call hits, and uses it
whatever optimize says. The single exception is a label whose extents disagree
between operands: NumPy's C path leaks its ITERATOR's "remapped shapes" text there,
which describes axis bookkeeping rather than the contraction, so NumSharp raises
NumPy's other wording for the identical error —
Size of label 'j' for operand 1 (3) does not match previous terms (4).
Exceptions
- ValueError
Subscripts NumPy refuses, with its parser's texts; an
out=whose extents differ from the result's (see Einsum(string, NDArray[], NDArray, DType, char, string, object)).- TypeError
An operand that cannot reach the loop dtype, or text outside the view path.
einsum(string, NDArray[], NDArray, DType, char, string, object)
Evaluates the Einstein summation convention, with NumPy's full keyword surface.
public static NDArray einsum(string subscripts, NDArray[] operands, NDArray @out = null, DType dtype = null, char order = 'K', string casting = "safe", object optimize = null)
Parameters
subscriptsstringThe subscripts string, as for einsum(string, params NDArray[]) (
"ij,jk->ik").operandsNDArray[]The arrays the subscripts label, in order.
outNDArrayWhere the calculation would be deposited. Its RANK is validated now.
dtypeDTypeForces the accumulation dtype.
ordercharMemory layout of the result —
'C','F','A'or'K', in either case (NumPy's order converter).castingstringCasting rule —
"no","equiv","safe","same_kind"or"unsafe", spelled exactly.optimizeobjectfalse(the default),true,"greedy"or"optimal". NumPy also takes a precomputed contraction path; that is not modelled, because nothing plans one yet.
Returns
Remarks
Pass the keywords BY NAME — np.einsum("ij->i", ops, @out: dst). They are
keyword-only in NumPy, and naming them is also what keeps them unambiguous here:
NumSharp converts scalars to NDArray implicitly, so a fully positional
einsum(subscripts, ops, null, null, 'K', "safe", true) matches this overload
AND the params one, and the compiler rejects the call as ambiguous.
https://numpy.org/doc/stable/reference/generated/numpy.einsum.html
The body is Einsum(string, NDArray[], NDArray, DType, char, string, object) (TensorEngine.EinsumFunc.cs), which
DefaultEngine implements as a composition over the matrix products — a port of NumPy's
bmm_einsum (its optimize= path) that reduces each pairwise contraction to
matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char), so it runs through OpenBLAS whenever a backend is referenced
(byte-identical to NumPy for float32/float64/complex128) and through the managed GEMM
otherwise. Integer and boolean contractions are byte-exact; a pure float summation done
outside a product (e.g. ij->i, or across three or more operands) can differ in
the last ULP because its accumulation order follows sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) and a left-to-right
fold. Every rejection below is unchanged — a malformed expression, a wrong operand
count, a bad ellipsis, an impossible diagonal or a shape conflict is reported the same
way and with the same text as NumPy's default parser.
A single-operand expression that sums nothing away answers with a view of the
operand, exactly as NumPy does: np.einsum("ii->i", a) is a WRITEABLE view of
a's diagonal (writing it writes a), "ij->ji" is the transpose
view, and on this path order= and dtype= are ignored — NumPy's view
attempt wins over both keywords.
One deliberate divergence. NumPy carries TWO independent einsum parsers — the C
one behind the default optimize=False, and a Python one behind the
optimize path — and they word their rejections differently for the same input.
NumSharp reproduces the C one, since that is what a default call hits, and uses it
whatever optimize says. The single exception is a label whose extents disagree
between operands: NumPy's C path leaks its ITERATOR's "remapped shapes" text there,
which describes axis bookkeeping rather than the contraction, so NumSharp raises
NumPy's other wording for the identical error —
Size of label 'j' for operand 1 (3) does not match previous terms (4).
A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or
ends with np.concatenate), which drops the class.
Exceptions
- ArgumentNullException
subscriptsis null.- TypeError
castingis null (casting must be str, not NoneType); anoptimizeNumPy does not understand; an operand that cannot reach the loop dtype, or a result that cannot reachout's dtype, undercasting; text outside the view path.- ValueError
No operand; an
orderletter or acastingname NumPy refuses, with its texts; malformed subscripts; anoutof another shape (before any cast check, as NumPy's iterator broadcasts the out first), or a read-only one. The full list is Einsum(string, NDArray[], NDArray, DType, char, string, object)'s.- RuntimeError
An explicit path (
optimize: new object[] { "einsum_path", ... }or an EinsumPath) that leaves operands uncontracted:np.einsum_path's text, checked beforeorder,castingandout, as NumPy's einsum plans first.- IndexError
An explicit path, or an ellipsis, naming an operand that is not there (
np.einsum_path'spop index out of range/list index out of range).
einsum_path(params object[])
Evaluates the contraction order variadically — np.einsum_path("ij,jk", a, b) — and
in NumPy's SUBLIST spelling — np.einsum_path(a, [0,1], b, [1,2], [0,2]).
Optimization is "greedy"; use the NDArray[] overload to choose a different
optimize.
public static (EinsumPath path, string repr) einsum_path(params object[] operands)
Parameters
operandsobject[]The arrays the subscripts label — only their SHAPES are read.
Returns
- (EinsumPath path, string repr)
The EinsumPath (NumPy's
['einsum_path', …]list) and a printable representation of the path.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.einsum_path.html
A route-for-route port of NumPy 2.4.2's numpy.einsum_path (its greedy/optimal
planner in einsumfunc.py). The EinsumPath and every numeric metric
in the string are byte-identical to NumPy; the only difference is the placeholder letters
an ... expands to in the printed string, which NumPy itself does not pin (they are
drawn from a hash-randomized set and vary per process). NumSharp draws them
deterministically, so the path and the numbers always match.
Spell the operands either as an NDArray[] (this overload) or variadically through
einsum_path(params object[]) — np.einsum_path("ij,jk", a, b). The default
is optimize: "greedy", NumPy's default for einsum_path (note
einsum(string, params NDArray[])'s own default is false).
The statements are EinsumPath(string, NDArray[], object), on the first operand's engine (the default one with none).
Exceptions
- ArgumentNullException
subscriptsis null.- ValueError
A null operand, or subscripts NumPy's parser refuses (NumPy's texts); the variadic overload with nothing to parse.
- KeyError
An unknown path name.
- RuntimeError
An explicit path that does not contract every operand.
- TypeError
An
optimizeNumPy does not understand; the variadic overload's operand that is not an NDArray.- IndexError
An ellipsis with no operand to read its rank from (
list index out of range: NumPy's parser reads the operand before it counts them), or an explicit path naming an operand that is not there (pop index out of range).
einsum_path(string, NDArray[])
Evaluates the lowest-cost contraction order for an einsum(string, params NDArray[]) expression, considering the creation of intermediate arrays.
public static (EinsumPath path, string repr) einsum_path(string subscripts, NDArray[] operands)
Parameters
subscriptsstringThe einsum subscripts, e.g.
"ij,jk,kl->il".operandsNDArray[]The arrays the subscripts label — only their SHAPES are read.
Returns
- (EinsumPath path, string repr)
The EinsumPath (NumPy's
['einsum_path', …]list) and a printable representation of the path.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.einsum_path.html
A route-for-route port of NumPy 2.4.2's numpy.einsum_path (its greedy/optimal
planner in einsumfunc.py). The EinsumPath and every numeric metric
in the string are byte-identical to NumPy; the only difference is the placeholder letters
an ... expands to in the printed string, which NumPy itself does not pin (they are
drawn from a hash-randomized set and vary per process). NumSharp draws them
deterministically, so the path and the numbers always match.
Spell the operands either as an NDArray[] (this overload) or variadically through
einsum_path(params object[]) — np.einsum_path("ij,jk", a, b). The default
is optimize: "greedy", NumPy's default for einsum_path (note
einsum(string, params NDArray[])'s own default is false).
The statements are EinsumPath(string, NDArray[], object), on the first operand's engine (the default one with none).
Exceptions
- ArgumentNullException
subscriptsis null.- ValueError
A null operand, or subscripts NumPy's parser refuses (NumPy's texts); the variadic overload with nothing to parse.
- KeyError
An unknown path name.
- RuntimeError
An explicit path that does not contract every operand.
- TypeError
An
optimizeNumPy does not understand; the variadic overload's operand that is not an NDArray.- IndexError
An ellipsis with no operand to read its rank from (
list index out of range: NumPy's parser reads the operand before it counts them), or an explicit path naming an operand that is not there (pop index out of range).
einsum_path(string, NDArray[], object)
Evaluates the contraction order, choosing the path type via optimize.
public static (EinsumPath path, string repr) einsum_path(string subscripts, NDArray[] operands, object optimize)
Parameters
subscriptsstringThe einsum subscripts, e.g.
"ij,jk,kl->il".operandsNDArray[]The arrays the subscripts label — only their SHAPES are read.
optimizeobjectfalse/null(no optimization),true(≙"greedy"),"greedy","optimal", a precomputed EinsumPath (an explicit path), or a("greedy"|"optimal", maxIntermediateSize)tuple that caps the largest intermediate. Anything else is rejected exactly as NumPy rejects it.
Returns
- (EinsumPath path, string repr)
The EinsumPath (NumPy's
['einsum_path', …]list) and a printable representation of the path.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.einsum_path.html
A route-for-route port of NumPy 2.4.2's numpy.einsum_path (its greedy/optimal
planner in einsumfunc.py). The EinsumPath and every numeric metric
in the string are byte-identical to NumPy; the only difference is the placeholder letters
an ... expands to in the printed string, which NumPy itself does not pin (they are
drawn from a hash-randomized set and vary per process). NumSharp draws them
deterministically, so the path and the numbers always match.
Spell the operands either as an NDArray[] (this overload) or variadically through
einsum_path(params object[]) — np.einsum_path("ij,jk", a, b). The default
is optimize: "greedy", NumPy's default for einsum_path (note
einsum(string, params NDArray[])'s own default is false).
The statements are EinsumPath(string, NDArray[], object), on the first operand's engine (the default one with none).
Exceptions
- ArgumentNullException
subscriptsis null.- ValueError
A null operand, or subscripts NumPy's parser refuses (NumPy's texts); the variadic overload with nothing to parse.
- KeyError
An unknown path name.
- RuntimeError
An explicit path that does not contract every operand.
- TypeError
An
optimizeNumPy does not understand; the variadic overload's operand that is not an NDArray.- IndexError
An ellipsis with no operand to read its rank from (
list index out of range: NumPy's parser reads the operand before it counts them), or an explicit path naming an operand that is not there (pop index out of range).
empty(Shape, DType, char, string)
Return a new array of given shape and type, without initializing entries — NumPy's one signature,
np.empty(shape, dtype=None, order='C', *, device=None).
public static NDArray empty(Shape shape, DType dtype = null, char order = 'C', string device = null)
Parameters
shapeShapeThe dimensions: an int (
2), a tuple ((2, 3)), anint[]/long[]or a Shape (all convert implicitly). Only the dimensions are read: the layout comes fromorder, as NumPy's shape is a tuple of ints — a Shape taken from a transposed view gives a C-ordered array unlessordersays'F'.dtypeDTypeThe desired dtype — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. Null (NumPy's None) is float64.orderchar'C'(row-major, the default) or'F'(column-major), in either case. NumPy's'A'and'K'mean nothing without a source array and are refused.devicestringNull or
"cpu"(the Array-API device; NumPy has no other).
Returns
- NDArray
A new, owned, writeable array whose elements are uninitialized (arbitrary): write every element before reading it.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.empty.html — NumPy's array_empty
(multiarraymodule.c).
One signature since API-parity batch 8 (2026-11-12): the int / int[] / long[] /
Shape-only overloads, the (Shape, DType dtype, string device) form whose dtype was required and the
(Shape, char order, DType) form with the order before the dtype all went, as did the generic
empty<T> forms (write the dtype: np.empty(shape, np.float64)). A positional char after the
shape no longer compiles: NumPy reads np.empty(s, 'F')'s 'F' as the DTYPE (complex64), so write
order: 'F'.
Exceptions
- ValueError
In NumPy's order:
orderis not one of C, F, A, K (order must be one of 'C', 'F', 'A', or 'K' (got 'X'));deviceis not"cpu"(Device not understood. Only "cpu" is allowed, but received: gpu);orderis A or K (only 'C' or 'F' order is permitted); a negative dimension (negative dimensions are not allowed) or a byte count past the allocation limit.- NotSupportedException
dtypenames a class NumSharp has no storage for.
empty_like(NDArray, DType, char, Shape?, string)
Return a new array with the same shape and type as a given array, of uninitialized (arbitrary) data: NumPy's
empty_like(prototype, /, dtype=None, order='K', subok=True, shape=None, *, device=None).
public static NDArray empty_like(NDArray prototype, DType dtype = null, char order = 'K', Shape? shape = null, string device = null)
Parameters
prototypeNDArrayThe shape and data-type of
prototypedefine these same attributes of the returned array.dtypeDTypeOverrides the dtype of the result — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly.ordercharMemory layout:
'C','F','A'(F whenprototypeis F-contiguous and not C-contiguous, else C) or'K'(the default:prototype's axis order, kept also for ashapeof the same rank), in either case.shapeShape?Overrides the shape of the result (an int, an int[] or a tuple converts to Shape), or null for
prototype's. With'K'and a different rank the result is C-ordered, as NumPy's.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity; NumPy's is keyword-only).
Returns
- NDArray
Array of uninitialized (arbitrary) data with the same shape and type as prototype. A
numpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.empty_like.html
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces the former <code>(prototype, dtype, Shape shape = default, device)</code> / <code>(prototype, dtype, shape, order, device)</code>
pair,
so <code>order</code> no longer needs a <code>dtype</code> before it and <code>shape</code> takes None; a positional
<code>device</code> is written <code>device: "cpu"</code>. <code>subok</code> stays out (the parity plan's
exclusion).</p>
Exceptions
- ValueError
orderis not one of C, F, A, K in either case (order must be one of 'C', 'F', 'A', or 'K' (got 'Z')), reported before the device, as NumPy's empty_like converts its arguments in order;deviceis neither null nor"cpu"(NumPy'sDevice not understood. Only "cpu" is allowed, but received: ...); a negative dimension inshape(negative dimensions are not allowed); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).
equal(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 == x2) element-wise.
Mirrors NumPy's ufunc signature: equal(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the == operator for the typed wrapper).
public static NDArray equal(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).
equal(NDArray, object)
Return (x1 == x2) element-wise with scalar.
public static NDArray<bool> equal(NDArray x1, object x2)
Parameters
Returns
equal(object, NDArray)
Return (x1 == x2) element-wise with scalar on left.
public static NDArray<bool> equal(object x1, NDArray x2)
Parameters
Returns
evaluate(NDExpr, NDArray[], NDArray, NDArray, DType, string, char)
Evaluate an expression tree over NDArrays in ONE fused pass — no intermediate arrays, one read of each operand, one write of the result (NumSharp extension; the NumPy-ecosystem equivalent is numexpr.evaluate).
public static NDArray evaluate(NDExpr expr, NDArray[] operands = null, NDArray @out = null, NDArray where = null, DType dtype = null, string casting = null, char order = 'K')
Parameters
exprNDExprExpression with embedded array leaves, or with positional Input(int) leaves that
operandsfills. NDArrays convert implicitly, so one cast lights up the whole operator set:NDArray r = np.evaluate((NDExpr)a * b + 2); // a*b+2 fused NDArray d = np.evaluate((NDExpr.Arr(a) - b) / (NDExpr.Arr(a) + b)); NDArray s = np.evaluate(NDExpr.Sum((NDExpr)a * b)); // one-pass sum(a*b) NDArray p = np.evaluate(NDExpr.Input(0) * NDExpr.Input(1), new[] { a, b }); // positional operands NDArray o = np.evaluate((NDExpr)a * b, @out: x); // into xA repeated NDArray reference becomes ONE iterator operand. Text operands (
S,UandStringDTypearrays, and a C#string, which is NumPy'sstr) take part through the six comparisons, each computed as NumPy's own string comparison before the fused pass reads its bool result:NDArray m = np.evaluate(NDExpr.Equal(city, "paris") & ((NDExpr)age > 30)); // text and numbers, one calloperandsNDArray[]The operands of a tree built over positional Input(int) leaves, by position, or null (the default) for a tree whose leaves embed their arrays. Text operands follow the same rule as embedded text leaves (see
expr).outNDArrayOptional pre-allocated result (ufunc out= rules: joins the broadcast but is never stretched; cast from the resolved dtype under
casting; may alias an input — overlap-safe). Mutually exclusive withdtype. Pass it by name: the second position isoperands.whereNDArrayOptional boolean write mask (ufunc where= convention, plan P4.5): the fused kernel writes the result only where the mask is True, so masked-off slots of
outkeep their prior contents (and withoutoutthe unmasked slots of the fresh result are left uninitialised, exactly as NumPy's ufuncs leave them). It broadcasts with the inputs andoutbut never stretches a providedout, and must be a boolean array. NOT supported on a reduction tree (a masked reduction is a different operation).dtypeDTypeOptional result dtype — an implicit root cast (plan P4.5): the tree still COMPUTES at its natural per-node NEP50 dtypes and the RESULT is cast to this, so
np.evaluate(expr, dtype: X)equalsnp.evaluate(expr).astype(X)in one fused pass. NOT an accumulator/loop dtype — for a reduction tree it is rejected (a reduction fixes its own accumulator dtype); cast the reduction result instead. Mutually exclusive without(which already fixes the result dtype).castingstringThe cast rule enforced when a caller
outhas a different dtype than the resolved result ('no'/'equiv'/'safe'/'same_kind'/'unsafe'); default (null) is NumPy's ufuncsame_kind. With nooutit only validates the string.ordercharThe memory layout of a FRESH result (plan P4.5): 'K' (default) keeps today's heuristic (column-major only when every input is strictly F-contiguous, else row-major), 'C' forces row-major, 'F' forces column-major, 'A' resolves like 'K'. A caller
outkeeps its own layout, and a reduction (a fixed-layout result) rejects a non-'K' order.
Returns
- NDArray
The evaluated array at the tree's NumPy result_type (or
dtypeif given) — dtypes otherwise match the equivalent unfused NumPy expression node-for-node (NEP50, including weak python-scalar literals). Root reductions (Sum(NDExpr) / Prod / Min / Max / Mean) return a 0-d scalar array.
Remarks
One overload, its optional parameters defaulted (the np-layer dtype plan's D11, D19: a function NumPy does not
have keeps one overload). The whole call is the engine member
Evaluate(NDExpr, NDArray[], NDArray, NDArray, DType, string, char), which takes the
keywords as given and checks them in this order: a read-only out, then the keyword bundle,
then the tree itself when its program is built (a text node it does not compute among them).
Exceptions
- TypeError
outis not reachable from the result dtype undercasting(NumPy's UFuncTypeError text).- ArgumentException
Both
dtypeandoutwere given;whereis not a boolean array (NumPy's verbatim "Cannot cast … to dtype('bool') according to the rule 'safe'"); oroperandsis empty.- ValueError
A read-only
out;castingis not a legal rule, ororderis not one of 'C'/'F'/'A'/'K'.- StringComputationNotSupportedException
A node takes a text operand where NumPy's answer is not a number or a bool — a text result (concatenation, a
Wherewith text branches, a bare text leaf), a reduction of text other thanAny/All/CountNonzero, an arithmetic or math node (the message names it); raised when the expression's program is built, before any text is read. The comparisons, the truth readers,IsNaN,Castto a number and the numpy.strings factories compute on text.- TypeError
A text node NumPy refuses (a comparison of
SwithUor of text with a number, a numpy.strings function over the wrong class,IsNaNofS/U), with NumPy'sUFuncTypeErrortext.- OverflowError
A
Castof text to an integer whose parsed value is out of the target's range (NumPy'sOverflowError).- ArgumentNullException
expris null, or an entry ofoperandsis.- NotSupportedException
dtype, a non-'K'order, or awheremask was given for a reduction tree; or the operands' engine has no fused evaluation.
exp(NDArray, NDArray, NDArray, DType)
Calculate the exponential of all elements in the input array.
Mirrors NumPy's ufunc signature: exp(x, /, out=None, *, where=True, dtype=None).
public static NDArray exp(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput value.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
e**xelement-wise (an integer or bool input computes in its float tier), oroutitself when given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.exp.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.exp(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.exp(x))</code>), as for every other ufunc.</p>
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.).
exp2(NDArray, NDArray, NDArray, DType)
Mirrors NumPy's ufunc signature: exp2(x, /, out=None, *, where=True, dtype=None).
public static NDArray exp2(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop; the input must be same_kind-castable to it.
Returns
- NDArray
2**xelement-wise (an integer or bool input computes in its float tier), oroutitself when given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.exp2.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.exp2(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.exp2(x))</code>), as for every other ufunc.</p>
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.).
expand_dims(NDArray, NDAxis)
NumPy's np.expand_dims(a, axis): a view of a with a new axis of length one at every
position axis names in the RESULT.
public static NDArray expand_dims(NDArray a, NDAxis axis)
Parameters
aNDArrayThe array.
axisNDAxisNumPy's
axis(required, no None): one position (0,-1) or a tuple of positions ((0, 3)ornew[] { 0, 3 }), each in the result's ranka.ndim + Count; negative positions count from the end of the result. An empty tuple inserts nothing. AList<int>needs.ToArray().
Returns
- NDArray
A NEW view of
awith the new axes (an empty tuple included, NumPy'sa.reshape(shape)): it shares memory witha. Anumpy.matrixoperand gives a plain array (NumPy converts it withasarrayfirst); anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html. NumPy's statements are the array
object's (NDArray.expand_dims): out_ndim = len(axis) + a.ndim,
axis = normalize_axis_tuple(axis, out_ndim), then the reshape.
One signature since API-parity batch 4 (2026-11-12): it replaces the int, int[] and
IEnumerable<int> overloads (the last one let a null sequence return a itself,
where NumPy has no None for this argument).
Exceptions
- ArgumentNullException
ais null, oraxiswas converted from a nullint[](a non-nullable NDAxis has no None).- AxisError
A position is out of range for the result's rank:
axis 4 is out of bounds for array of dimension 4, the position as given (every position is range-checked before the repeat check).- ValueError
Two positions are the same after normalization (
repeated axis).
expand_dims(NDArray, int)
expand_dims(NDArray, NDAxis) with the axis as one int: the overload a C# integer
binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every
answer, error, layout and subclass result is that overload's.
public static NDArray expand_dims(NDArray a, int axis)
Parameters
Returns
- NDArray
A NEW view of
awith the new axes (an empty tuple included, NumPy'sa.reshape(shape)): it shares memory witha. Anumpy.matrixoperand gives a plain array (NumPy converts it withasarrayfirst); anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html. NumPy's statements are the array
object's (NDArray.expand_dims): out_ndim = len(axis) + a.ndim,
axis = normalize_axis_tuple(axis, out_ndim), then the reshape.
One signature since API-parity batch 4 (2026-11-12): it replaces the int, int[] and
IEnumerable<int> overloads (the last one let a null sequence return a itself,
where NumPy has no None for this argument).
Exceptions
- ArgumentNullException
ais null, oraxiswas converted from a nullint[](a non-nullable NDAxis has no None).- AxisError
A position is out of range for the result's rank:
axis 4 is out of bounds for array of dimension 4, the position as given (every position is range-checked before the repeat check).- ValueError
Two positions are the same after normalization (
repeated axis).
expand_dims(NDArray, int[])
expand_dims(NDArray, NDAxis) with the axes as an int[]: the overload an
int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form as NumPy's tuple (new int[0] is ()). NumPy's expand_dims has
no None, so a null array throws, exactly as the NDAxis form's conversion does.
public static NDArray expand_dims(NDArray a, int[] axis)
Parameters
Returns
- NDArray
A NEW view of
awith the new axes (an empty tuple included, NumPy'sa.reshape(shape)): it shares memory witha. Anumpy.matrixoperand gives a plain array (NumPy converts it withasarrayfirst); anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html. NumPy's statements are the array
object's (NDArray.expand_dims): out_ndim = len(axis) + a.ndim,
axis = normalize_axis_tuple(axis, out_ndim), then the reshape.
One signature since API-parity batch 4 (2026-11-12): it replaces the int, int[] and
IEnumerable<int> overloads (the last one let a null sequence return a itself,
where NumPy has no None for this argument).
Exceptions
- ArgumentNullException
axisis null (expand_dims has no None).- ArgumentNullException
ais null, oraxiswas converted from a nullint[](a non-nullable NDAxis has no None).- AxisError
A position is out of range for the result's rank:
axis 4 is out of bounds for array of dimension 4, the position as given (every position is range-checked before the repeat check).- ValueError
Two positions are the same after normalization (
repeated axis).
expm1(NDArray, NDArray, NDArray, DType)
Mirrors NumPy's ufunc signature: expm1(x, /, out=None, *, where=True, dtype=None).
public static NDArray expm1(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop; the input must be same_kind-castable to it.
Returns
- NDArray
exp(x) - 1element-wise, accurate near zero, oroutitself when given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.expm1.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.expm1(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.expm1(x))</code>), as for every other ufunc.</p>
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.).
extract(NDArray, NDArray)
Return the elements of arr that satisfy some
condition. Equivalent to
np.take(np.ravel(arr), np.flatnonzero(np.ravel(condition))) —
i.e. arr.ravel()[condition.ravel()] when condition is boolean.
public static NDArray extract(NDArray condition, NDArray arr)
Parameters
conditionNDArrayArray whose nonzero / True entries indicate the elements of
arrto extract. May be any dtype (treated as truthy via NumPy's "nonzero" semantics). May be any shape — it is ravel'd before alignment witharr.arrNDArrayInput array. May be any shape; it is ravel'd.
Returns
- NDArray
Rank-1 NDArray of values from
arrwhere the corresponding ravel'dconditionentry is truthy. Dtype matchesarr. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.extract.html
Two execution paths:
-
Fast path: bool condition, contig arr + condition,
condition.size <= arr.size. Runs a fused IL kernel (popcount → alloc → SIMD bit-scan + cpblk) avoiding the indices NDArray allocation that the generic path needs. -
Generic path: mirrors NumPy's literal chain
take(ravel(arr), flatnonzero(ravel(condition))). Handles non-bool conditions (any dtype interpreted as nonzero), broadcast / strided / negative-stride sources, and the OOB-True case (raises via take's RAISE mode).
Note that place(NDArray, NDArray, NDArray) is the inverse operation.
eye(int, int?, int, DType, char, string)
Return a 2-D array with ones on the diagonal and zeros elsewhere.
public static NDArray eye(int N, int? M = null, int k = 0, DType dtype = null, char order = 'C', string device = null)
Parameters
NintNumber of rows in the output.
Mint?Number of columns in the output. If None, defaults to N.
kintIndex of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
dtypeDTypeData-type of the returned array.
ordercharMemory layout: 'C' (row-major, default) or 'F' (column-major).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.eye.html. NumPy's eye is
m = zeros((N, M), dtype=dtype, order=order, device=device) and so raises in np.zeros' order, which this
follows: the order's letter (an argument conversion), the device, the order's C-or-F rule, then the
dimensions (the allocation).
Exceptions
- ValueError
orderis not one of C, F, A, K in either case (order must be one of 'C', 'F', 'A', or 'K' (got 'Z')), or it is A or K (only 'C' or 'F' order is permitted);NorMis negative (negative dimensions are not allowed); or the dtype's setitem refuses the Python int 1 (aStringDType(coerce=False)).- ValueError
deviceis neither null nor"cpu"(NumPy'sDevice not understood. Only "cpu" is allowed, but received: ...).
fabs(NDArray, NDArray, NDArray, DType)
Compute the absolute values element-wise, in the FLOATING-POINT domain.
Mirrors NumPy's ufunc signature: fabs(x, /, out=None, *, where=True, dtype=None).
public static NDArray fabs(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array. Any dtype EXCEPT complex — fabs(NDArray, NDArray, NDArray, DType) has no complex loop (use absolute(NDArray, NDArray, NDArray, DType) for the complex magnitude).
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the resolved float loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): float kinds only. A bool/integer/char or complex request raises the no-loop error; a complex input with a float dtype= raises the input-cast error.
Returns
- NDArray
A float array (or
out) holding the absolute value of each element. Unlike absolute(NDArray, NDArray, NDArray, DType) this ALWAYS returns a float: integer/bool input is promoted (NEP50 tier — bool/int8/uint8→float16, int16/uint16→float32, int32/uint32/int64/uint64→float64), while float16/float32/float64 are preserved.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.fabs.html
Port of NumPy 2.4.2's fabs ufunc. It is the float-only counterpart of
absolute(NDArray, NDArray, NDArray, DType): the operation is identical on the float loops (clear the
IEEE sign bit — so -0.0 → +0.0, ±inf → +inf, and a negative NaN's sign bit is
cleared while its payload is preserved), but fabs promotes integer/bool to float and refuses
complex input (NumPy: "ufunc 'fabs' not supported for the input types").
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.).
fill_diagonal(NDArray, object, bool)
Fill the main diagonal of the given array of any dimensionality — in place.
public static void fill_diagonal(NDArray a, object val, bool wrap = false)
Parameters
aNDArrayArray whose diagonal is to be filled; it is modified in place.
valobjectValue(s) to write into the diagonal. A scalar is repeated; a sequence is raveled and then tiled cyclically (and truncated) to the diagonal's length. It is converted to
a's dtype first, as NumPy's flat assignment converts it: a C# number or a str by the dtype's setitem (a Python int range-checked, never wrapped; a str parsed by Python'sint()/float()/complex(); intoS/Uitsstr()), anobject[]or collection (a Python list) item by item the same way, an NDArray or typed C# array by an unsafe cast.nullis Python'sNone: NaN (NumPy's positiveNPY_NAN) for a float array,nan+nanjfor complex,Falsefor bool,'None'(truncated) forS/U, aStringDType's NA object or'None'.wrapboolFor tall matrices the diagonal "wraps" after N columns and continues on the row below. Off by default.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html
Values tile, they do not broadcast. NumPy's body ends in
a.flat[:end:step] = val, and flat-iterator assignment repeats a short
right-hand side rather than raising: probed on a 6×6, [1,2,3,4] fills the
diagonal as [1,2,3,4,1,2], while an over-long value list is truncated and
an empty one is a silent no-op. resize(NDArray, Shape) already
implements exactly that cyclic-tile-or-truncate rule, so it supplies the values.
No element loop. NumPy addresses the diagonal as a strided slice of the
flat iterator; NumSharp resolves the same positions into real strides and
writes through ordinary aliased views. Without wrapping the targets are
(i, i, …, i), i.e. one constant stride of Σ strides — a single view.
With wrapping on a tall matrix the flat position of target i = q·cols + r
is q·(cols+1)·s0 + r·(s0+s1), so the run splits into ceil(count/cols)
equally-strided blocks — a handful of views, still no per-element addressing.
Because the targets are computed from strides rather than from memory order, this
works unchanged on transposed, sliced and otherwise non-contiguous arrays, which
it writes through exactly as NumPy does.
Exceptions
- ArgumentException
array must be at least 2-d,All dimensions of input must be of equal length(ndim > 2 with a non-hyper-cubic shape), orunderlying array is read-only— all verbatim NumPyValueErrortexts.- ArgumentNullException
ais null.- TypeError
valis null (None), or a list holds one, andais an integer (ordecimal) array — Python'sint(None); or a complex value into a real array. Like every conversion error, raised even for an empty diagonal.- ValueError
A
StringDType(coerce=False)array given a value that is not text (Noneincluded); a str that is not a number of a numeric array's kind (invalid literal for int() with base 10: 'x'); a float NaN into an integer array.- OverflowError
A Python int (alone or in a list) out of an integer array's range (
Python integer 300 out of bounds for int8).
find_common_type(DType[])
find_common_type(NPTypeCode[], NPTypeCode[]) with no scalar types, in the DType form
the np.float32/np.int64 spellings are (new[] { np.float32, np.int64 } is a DType[]).
public static DType find_common_type(DType[] array_types)
Parameters
array_typesDType[]The dtypes of the arrays. Null counts as none.
Returns
- DType
The first type of NumPy's candidate list every entry casts to safely, or null (NumPy's None) for none.
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- NotSupportedException
An entry has no NumSharp storage yet (a datetime64 descriptor).
find_common_type(DType[], DType[])
find_common_type(NPTypeCode[], NPTypeCode[]) in the DType form the
np.float32/np.int64 spellings are (new[] { np.float32, np.int64 } is a DType[]).
public static DType find_common_type(DType[] array_types, DType[] scalar_types)
Parameters
array_typesDType[]The dtypes of the arrays. Null counts as none.
scalar_typesDType[]The dtypes of the scalars. Null counts as none.
Returns
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- NotSupportedException
An entry has no NumSharp storage yet (a datetime64 descriptor).
find_common_type(NPTypeCode[], NPTypeCode[])
Determine common type following standard coercion rules: NumPy 1.26.4's np.find_common_type, the last
NumPy that has it (deprecated in 1.25, removed in 2.0). Kept on purpose, so code written against NumPy 1.x
compiles and runs unchanged; new code writes promote_types(DType, DType) or
result_type(params object[]), passing the Python values 0, 0.0 or 0j for the scalar
types.
public static DType find_common_type(NPTypeCode[] array_types, NPTypeCode[] scalar_types)
Parameters
array_typesNPTypeCode[]The dtypes of the arrays. Null counts as none.
scalar_typesNPTypeCode[]The dtypes of the scalars. Null counts as none.
Returns
- DType
The common data type, which is the maximum of
array_typesignoringscalar_types, unless the maximum ofscalar_typesis of a different, higher kind (dtype.kind): then the first type both maxima cast to safely. Null (NumPy's None) when nothing is given, or when no NumPy dtype NumSharp has holds the inputs (str with a number: NumPy's answer, object, is not a NumSharp dtype).
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- ArgumentException
An entry is Empty (no dtype), which is also what a Type that is not a NumSharp element type converts to.
- NotSupportedException
A dtype string names a dtype NumSharp cannot store (the string overload).
- TypeError
A dtype string NumPy cannot parse either (the string overload; NumPy's
data type 'x' not understood).
find_common_type(NPTypeCode[], Type[])
Determine common type following standard coercion rules: NumPy 1.26.4's np.find_common_type, the last
NumPy that has it (deprecated in 1.25, removed in 2.0). Kept on purpose, so code written against NumPy 1.x
compiles and runs unchanged; new code writes promote_types(DType, DType) or
result_type(params object[]), passing the Python values 0, 0.0 or 0j for the scalar
types.
public static DType find_common_type(NPTypeCode[] array_types, Type[] scalar_types)
Parameters
array_typesNPTypeCode[]The dtypes of the arrays. Null counts as none.
scalar_typesType[]The dtypes of the scalars. Null counts as none.
Returns
- DType
The common data type, which is the maximum of
array_typesignoringscalar_types, unless the maximum ofscalar_typesis of a different, higher kind (dtype.kind): then the first type both maxima cast to safely. Null (NumPy's None) when nothing is given, or when no NumPy dtype NumSharp has holds the inputs (str with a number: NumPy's answer, object, is not a NumSharp dtype).
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- ArgumentException
An entry is Empty (no dtype), which is also what a Type that is not a NumSharp element type converts to.
- NotSupportedException
A dtype string names a dtype NumSharp cannot store (the string overload).
- TypeError
A dtype string NumPy cannot parse either (the string overload; NumPy's
data type 'x' not understood).
find_common_type(params string[])
find_common_type(NPTypeCode[], NPTypeCode[]) of dtype strings that all describe arrays (no scalar
types) — a NumSharp shorthand: NumPy's function always takes the two lists (np.find_common_type("i4", "f8")
is float64).
public static DType find_common_type(params string[] involvedTypes)
Parameters
involvedTypesstring[]The dtype strings (
"int32","f8","<u2").
Returns
- DType
The first type of NumPy's candidate list every entry casts to safely, the entry itself for one, null for none.
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- NotSupportedException
A string names a dtype NumSharp cannot store.
- TypeError
A string NumPy cannot parse either (NumPy's
data type 'x' not understood).
find_common_type(string[], string[])
Determine common type following standard coercion rules: NumPy 1.26.4's np.find_common_type, the last
NumPy that has it (deprecated in 1.25, removed in 2.0). Kept on purpose, so code written against NumPy 1.x
compiles and runs unchanged; new code writes promote_types(DType, DType) or
result_type(params object[]), passing the Python values 0, 0.0 or 0j for the scalar
types.
public static DType find_common_type(string[] array_types, string[] scalar_types)
Parameters
array_typesstring[]The dtypes of the arrays. Null counts as none.
scalar_typesstring[]The dtypes of the scalars. Null counts as none.
Returns
- DType
The common data type, which is the maximum of
array_typesignoringscalar_types, unless the maximum ofscalar_typesis of a different, higher kind (dtype.kind): then the first type both maxima cast to safely. Null (NumPy's None) when nothing is given, or when no NumPy dtype NumSharp has holds the inputs (str with a number: NumPy's answer, object, is not a NumSharp dtype).
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- ArgumentException
An entry is Empty (no dtype), which is also what a Type that is not a NumSharp element type converts to.
- NotSupportedException
A dtype string names a dtype NumSharp cannot store (the string overload).
- TypeError
A dtype string NumPy cannot parse either (the string overload; NumPy's
data type 'x' not understood).
find_common_type(Type[])
Determine common type following standard coercion rules: NumPy 1.26.4's np.find_common_type, the last
NumPy that has it (deprecated in 1.25, removed in 2.0). Kept on purpose, so code written against NumPy 1.x
compiles and runs unchanged; new code writes promote_types(DType, DType) or
result_type(params object[]), passing the Python values 0, 0.0 or 0j for the scalar
types.
public static DType find_common_type(Type[] array_types)
Parameters
array_typesType[]The dtypes of the arrays. Null counts as none.
Returns
- DType
The common data type, which is the maximum of
array_typesignoringscalar_types, unless the maximum ofscalar_typesis of a different, higher kind (dtype.kind): then the first type both maxima cast to safely. Null (NumPy's None) when nothing is given, or when no NumPy dtype NumSharp has holds the inputs (str with a number: NumPy's answer, object, is not a NumSharp dtype).
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- ArgumentException
An entry is Empty (no dtype), which is also what a Type that is not a NumSharp element type converts to.
- NotSupportedException
A dtype string names a dtype NumSharp cannot store (the string overload).
- TypeError
A dtype string NumPy cannot parse either (the string overload; NumPy's
data type 'x' not understood).
find_common_type(Type[], NPTypeCode[])
Determine common type following standard coercion rules: NumPy 1.26.4's np.find_common_type, the last
NumPy that has it (deprecated in 1.25, removed in 2.0). Kept on purpose, so code written against NumPy 1.x
compiles and runs unchanged; new code writes promote_types(DType, DType) or
result_type(params object[]), passing the Python values 0, 0.0 or 0j for the scalar
types.
public static DType find_common_type(Type[] array_types, NPTypeCode[] scalar_types)
Parameters
array_typesType[]The dtypes of the arrays. Null counts as none.
scalar_typesNPTypeCode[]The dtypes of the scalars. Null counts as none.
Returns
- DType
The common data type, which is the maximum of
array_typesignoringscalar_types, unless the maximum ofscalar_typesis of a different, higher kind (dtype.kind): then the first type both maxima cast to safely. Null (NumPy's None) when nothing is given, or when no NumPy dtype NumSharp has holds the inputs (str with a number: NumPy's answer, object, is not a NumSharp dtype).
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- ArgumentException
An entry is Empty (no dtype), which is also what a Type that is not a NumSharp element type converts to.
- NotSupportedException
A dtype string names a dtype NumSharp cannot store (the string overload).
- TypeError
A dtype string NumPy cannot parse either (the string overload; NumPy's
data type 'x' not understood).
find_common_type(Type[], Type[])
Determine common type following standard coercion rules: NumPy 1.26.4's np.find_common_type, the last
NumPy that has it (deprecated in 1.25, removed in 2.0). Kept on purpose, so code written against NumPy 1.x
compiles and runs unchanged; new code writes promote_types(DType, DType) or
result_type(params object[]), passing the Python values 0, 0.0 or 0j for the scalar
types.
public static DType find_common_type(Type[] array_types, Type[] scalar_types)
Parameters
array_typesType[]The dtypes of the arrays. Null counts as none.
scalar_typesType[]The dtypes of the scalars. Null counts as none.
Returns
- DType
The common data type, which is the maximum of
array_typesignoringscalar_types, unless the maximum ofscalar_typesis of a different, higher kind (dtype.kind): then the first type both maxima cast to safely. Null (NumPy's None) when nothing is given, or when no NumPy dtype NumSharp has holds the inputs (str with a number: NumPy's answer, object, is not a NumSharp dtype).
Remarks
NumPy 2 raises AttributeError: `np.find_common_type` was removed in the NumPy 2.0 release. Use
`numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use
`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.
The maximum is a search, not a promotion. Each maximum is the first type of NumPy's candidate list
?bBhHiIlLqQefdgFDGO that every input casts to safely, so [int8, uint8, float16] gives float16 where
a pairwise promote_types chain gives float32. A higher-kind scalar can move the result:
find_common_type([uint8], [int16]) is int16 (NEP 50's weak-scalar rule, which NumSharp's arithmetic uses,
keeps uint8).
The rule is NumPy 1.x's, not NEP 50's: a scalar type counts only when its KIND is higher than every array
type's, and then by its type, never by a value. np.result_type is the NumPy 2 rule, where a C#
literal is a weak Python scalar (np.result_type(int8_array, 300) is int8) and a dtype is always
strong (np.result_type(np.int8, np.int64) is int64, where find_common_type([int8], [int64]) is int8).
NumSharp's own dtypes (Decimal, Char) have no place in NumPy's candidate list: any list holding one is promoted with NumSharp's promotion table instead, the rule its arithmetic uses (decimal wins over the floats, char promotes as uint16).
NumPy 1.26's page: https://numpy.org/doc/1.26/reference/generated/numpy.find_common_type.html; the replacement: https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
Exceptions
- ArgumentException
An entry is Empty (no dtype), which is also what a Type that is not a NumSharp element type converts to.
- NotSupportedException
A dtype string names a dtype NumSharp cannot store (the string overload).
- TypeError
A dtype string NumPy cannot parse either (the string overload; NumPy's
data type 'x' not understood).
finfo(DType)
Machine limits for floating point types.
public static finfo finfo(DType dtype)
Parameters
dtypeDTypeThe floating point dtype — one descriptor parameter, like NumPy's: a C# Type (
typeof(double)), an NPTypeCode or a DType (np.float64,arr.dtype) convert implicitly; a string binds finfo(string), which reads it as NumPy does.
Returns
- finfo
An finfo object describing the floating point type limits.
Examples
var info = np.finfo(np.float64);
Console.WriteLine(info.bits); // 64
Console.WriteLine(info.eps); // ~2.22e-16
Console.WriteLine(info.precision); // 15
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.finfo.html
An ARRAY is not a dtype: NumPy's np.finfo(arr) raises data type dtype('O') not compatible with
finfo; NumSharp has no array overload since API-parity batch 7, so pass arr.dtype.
Exceptions
- TypeError
dtypeis null (NumPy 2.5'sdtype must not be None).- ValueError
Not a floating point or complex dtype: NumPy 2.5's
data type dtype('int32') not compatible with finfo.
finfo(NDScalarType)
Machine limits of a floating-point scalar CLASS — NumPy's np.finfo(cls): a concrete class gives its
dtype's limits (np.finfo((NDScalarType)np.float32) is np.finfo(np.float32)), a complex class its
real part's (np.finfo(np.complex64) is float32's, although NumSharp has no complex64 dtype), and a
Python built-in class the limits of the NumPy class NumPy reads it as (np.finfo(NDScalarType.PyFloat)
is float64's).
public static finfo finfo(NDScalarType dtype)
Parameters
dtypeNDScalarTypeThe scalar class.
Returns
- finfo
The limits.
Exceptions
- TypeError
dtypeis null (NumPy 2.5'sdtype must not be None).- ValueError
The class is not inexact — NumPy 2.5's text, which names the class's dtype:
data type dtype('int64') not compatible with finfo(also forint, whose NumPy class is int64). An abstract class isdata type dtype('O') not compatible with finfo: NumPy'sfinforetries a value that converts to no dtype with the dtype of its TYPE, and the type of a class is Python'stype, an object dtype — so evennp.finfo(np.floating)namesdtype('O').
finfo(string)
Machine limits of the floating-point dtype a STRING names — NumPy's np.finfo("float64"), read as NumPy
reads it: numeric.dtype(dtype), and when that raises TypeError (the string names no dtype) the dtype of
the value's TYPE, str — so np.finfo("foo") and np.finfo("") are NumPy 2.5's data type
dtype('<U') not compatible with finfo.
public static finfo finfo(string dtype)
Parameters
dtypestringA dtype string (
"float32","f2","double"); null is NumPy's None, which NumPy 2.5 refuses (NumPy 2.4 still read it as float64, with a DeprecationWarning since 1.25).
Returns
- finfo
An finfo object describing the floating point type limits.
Examples
var info = np.finfo("float64");
Console.WriteLine(info.bits); // 64
Remarks
An ARRAY is not a dtype: NumPy's np.finfo(arr) reads its type (an object dtype) and raises
data type dtype('O') not compatible with finfo; NumSharp has no array overload since API-parity
batch 7, so pass arr.dtype. Before that batch this parameter was named dtypeName, and a null or
empty string raised NumSharp's own ArgumentException.
Exceptions
- TypeError
dtypeis null (NumPy 2.5'sdtype must not be None).- ValueError
The string names a non-inexact dtype (
"int32":data type dtype('int32') not compatible with finfo) or no dtype at all (dtype('<U')) — NumPy 2.5's texts.- NotSupportedException
The string names a NumPy dtype NumSharp does not model (
"O","V"): dtype(string)'s refusal.
fix(NDArray, NDArray)
Round to nearest integer towards zero, element-wise. The rounded values keep the input's data-type (int/bool are returned unchanged; floats are truncated toward zero).
public static NDArray fix(NDArray x, NDArray @out = null)
Parameters
xNDArrayArray to be rounded.
outNDArrayA location into which the result is stored (NumPy's positional
out). If provided it must have a shape the input broadcasts to and a dtype the truncated result can be cast to undersame_kind(a float→intoutraises, matching NumPy); the same instance is returned. Ifnull, a freshly allocated array is returned.
Returns
- NDArray
The element-wise truncation of
x(orout).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.fix.html
Port of NumPy's numpy.fix (numpy/lib/_ufunclike_impl.py), which in 2.4.2 is a
pure delegation to numpy.trunc(x, out=out) — so fix(NDArray, NDArray) is trunc(NDArray, NDArray, NDArray, DType)
by another name and inherits its behaviour exactly: dtype preservation, NaN/±inf pass-through,
the sign of -0.0, and the error texts (a complex input and an incompatible out
dtype both surface the underlying trunc ufunc — which is what NumPy's fix leaks
too, since it also delegates). Unlike a true ufunc it exposes NO where/dtype
parameters (NumPy's fix signature is only fix(x, out=None)).
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 read-onlyout.- TypeError
Text or complex input, which trunc has no loop for.
- TypeError
An
outthe result does not reach under same_kind.- ArgumentException
An
outthe result does not broadcast into.- NullReferenceException
xis null.
flat(NDArray)
Build a np.FlatIterator over a — the write-through,
C-order flat iterator that is the analog of NumPy's flatiter
(a.flat's type). NumSharp's flat property already returns
a raveled NDArray and is deeply embedded, so it cannot be reclaimed to
return this type; the flat iterator lives on the flatiter accessor
(and this factory) instead.
public static np.FlatIterator flat(NDArray a)
Parameters
aNDArray
Returns
Remarks
flat<T>(NDArray, bool)
Typed, allocation-free FLAT iteration — the unboxed, by-reference counterpart of
flat(NDArray) / flatiter. Yields ref T
straight into the array's memory in logical C-order (last axis fastest,
honouring the array's strides — the same order the boxed np.FlatIterator
walks), so reading costs a dereference and writing goes through to the array for
EVERY memory layout — transposed, sliced, strided, negative-stride, broadcast.
var a = np.arange(6).reshape(2, 3).T; // transposed (non-contiguous) view
// read, by reference, in C-order (0 3 1 4 2 5 — same as a.flatiter)
double total = 0;
foreach (ref double x in np.flat<double>(a))
total += x;
// write through, in C-order
foreach (ref double x in np.flat<double>(a, writeable: true))
x *= 2;
public static np.FlatRefIter<T> flat<T>(NDArray a, bool writeable = false) where T : unmanaged
Parameters
aNDArrayThe array to iterate over.
writeableboolOpen the operand
readwriteso assignments through therefreach the array. A read-only broadcast view (stride-0) is rejected with NumPy's verbatim message. (Likenp.nditer<T>, this is a caller contract, not a C# read-only guarantee — the iterator is never buffered, so assigning through therefalways writes physically.)
Returns
- np.FlatRefIter<T>
Type Parameters
TMust be EXACTLY the array's element type — no conversion or casting is performed, because a
refcannot convert. A mismatch throws rather than reinterpreting the bytes (cast first witha.astype(...)). This is why the typed form cannot do the NumPy-style scalar coercion the boxed np.FlatIterator's setters do.
Remarks
NumSharp extension: NumPy's flatiter hands back a boxed scalar per element
because Python has no unboxed generics. This is the same walk with the boxing and the
per-element view removed. It is exactly np.nditer<T>(a, order: 'C') with a
C-order default baked in to match flatiter's order (the
order-configurable nditer<T>(NDArray, bool, char) defaults instead to
memory order 'K'); it runs on the very same NDIterRef engine.
Empty arrays iterate zero times and a 0-d array yields its single element
— matching the boxed np.FlatIterator, and unlike the boxed np.nditer
which requires the zerosize_ok flag for an empty operand.
flatnonzero(NDArray)
Return indices that are non-zero in the flattened version of a.
This is equivalent to np.nonzero(np.ravel(a))[0].
public static NDArray<long> flatnonzero(NDArray a)
Parameters
aNDArrayInput data.
Returns
- NDArray<long>
1-D NDArray<TDType> of long (NumPy
intp) containing the indices of elements ofa.ravel()that are non-zero. For 0-d input, returns[0]when the value is truthy and an empty array otherwise. For empty input, returns an empty 1-D array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.flatnonzero.html
Faster than the literal composition nonzero(ravel(a))[0]: the engine
runs the SIMD popcount + bit-scan straight into the 1-D result buffer
without materializing the per-axis coordinate arrays produced by
nonzero(NDArray). For multi-dim inputs the cost is the same as a 1-D
input of equal element count (the layout is collapsed by materializing to
C-contig when needed).
flip(NDArray, int)
flip(NDArray, NDAxis?) with the axis as one int: the overload a C# integer binds
(its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer,
error, layout and subclass result is that overload's.
public static NDArray flip(NDArray m, int axis)
Parameters
Returns
- NDArray
A view of
mwith the entries of the selected axes reversed: it shares memory withm(a write through it changesm) and is read-only whenmis. Anumpy.char.chararrayoperand gives a chararray view, and a 0-d one its element: the read-only stand-in of NumPy's Pythonstr/bytes, stripped.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.flip.html. NumPy's statements:
axis = normalize_axis_tuple(axis, m.ndim), then m[indexer] with ::-1 on those axes.
One signature since API-parity batch 4 (2026-11-12): the int? and int[] overloads it
replaces made np.flip(m, null) ambiguous (CS0121) and had no tuple literal; both spellings convert to
NDAxis.
Exceptions
- ArgumentNullException
mis null.- AxisError
An axis is out of bounds for
m(the first one, reported as given; every axis is range-checked before the repeat check, so(0, 0, 5)reports axis 5). A 0-dmhas no axis to name.- ValueError
An axis is named twice (
repeated axis); anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
flip(NDArray, int[])
flip(NDArray, NDAxis?) with the axes as an int[]: the overload an int[]
binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to
the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is
()).
public static NDArray flip(NDArray m, int[] axis)
Parameters
Returns
- NDArray
A view of
mwith the entries of the selected axes reversed: it shares memory withm(a write through it changesm) and is read-only whenmis. Anumpy.char.chararrayoperand gives a chararray view, and a 0-d one its element: the read-only stand-in of NumPy's Pythonstr/bytes, stripped.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.flip.html. NumPy's statements:
axis = normalize_axis_tuple(axis, m.ndim), then m[indexer] with ::-1 on those axes.
One signature since API-parity batch 4 (2026-11-12): the int? and int[] overloads it
replaces made np.flip(m, null) ambiguous (CS0121) and had no tuple literal; both spellings convert to
NDAxis.
Exceptions
- ArgumentNullException
mis null.- AxisError
An axis is out of bounds for
m(the first one, reported as given; every axis is range-checked before the repeat check, so(0, 0, 5)reports axis 5). A 0-dmhas no axis to name.- ValueError
An axis is named twice (
repeated axis); anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
flip(NDArray, NDAxis?)
NumPy's np.flip(m, axis=None): a view of m with the order of the elements reversed
along the given axes (every axis by default). The shape is preserved; only the strides and the start of the
view change, so the call is constant time whatever the size.
public static NDArray flip(NDArray m, NDAxis? axis = null)
Parameters
mNDArrayInput array.
axisNDAxis?NumPy's
axis:null(None, the default) flips every axis; one axis (0,-1) flips that axis; a tuple ((0, 2)ornew[] { 0, 2 }) flips each of its axes, and the empty tuple flips none (an unreversed view). Negative axes count from the end.
Returns
- NDArray
A view of
mwith the entries of the selected axes reversed: it shares memory withm(a write through it changesm) and is read-only whenmis. Anumpy.char.chararrayoperand gives a chararray view, and a 0-d one its element: the read-only stand-in of NumPy's Pythonstr/bytes, stripped.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.flip.html. NumPy's statements:
axis = normalize_axis_tuple(axis, m.ndim), then m[indexer] with ::-1 on those axes.
One signature since API-parity batch 4 (2026-11-12): the int? and int[] overloads it
replaces made np.flip(m, null) ambiguous (CS0121) and had no tuple literal; both spellings convert to
NDAxis.
Exceptions
- ArgumentNullException
mis null.- AxisError
An axis is out of bounds for
m(the first one, reported as given; every axis is range-checked before the repeat check, so(0, 0, 5)reports axis 5). A 0-dmhas no axis to name.- ValueError
An axis is named twice (
repeated axis); anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
fliplr(NDArray)
Reverse the order of elements along axis 1 (left/right). For a 2-D array, this flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.
public static NDArray fliplr(NDArray m)
Parameters
mNDArrayInput array, must be at least 2-D.
Returns
- NDArray
A view of
mwith the columns reversed — equivalent to m[:, ::-1] or np.flip(m, axis: 1). Since a view is returned, this operation is done in constant time. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
Exceptions
- ValueError
When
mis less than 2-d ("Input must be >= 2-d.").- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
flipud(NDArray)
Reverse the order of elements along axis 0 (up/down). For a 2-D array, this flips the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before.
public static NDArray flipud(NDArray m)
Parameters
mNDArrayInput array, must be at least 1-D.
Returns
- NDArray
A view of
mwith the rows reversed — equivalent to m[::-1, ...] or np.flip(m, axis: 0). Since a view is returned, this operation is done in constant time. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
Exceptions
- ValueError
When
mis less than 1-d ("Input must be >= 1-d.").- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
float_power(NDArray, NDArray, NDArray, NDArray, DType)
First array elements raised to powers from second array, element-wise, at a MINIMUM precision of float64 (np.float_power).
Unlike power(NDArray,NDArray), float_power promotes every real input
(bool/integer/float16/float32/decimal/char) to float64 and a complex operand to
complex128 — the result is therefore always an inexact float. Because there is no
integer loop, a negative integer exponent is legal:
np.float_power(2, -1) == 0.5 where power(NDArray,NDArray) raises.
The computation is otherwise bit-identical to power(NDArray,NDArray) on
its float64/complex128 loops.
public static NDArray float_power(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayThe bases (any dtype; promoted to the float loop).
x2NDArrayThe exponents (any dtype; promoted to the float loop).
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): only float64 or complex128 select a loop — any other request raises "No loop matching the specified signature and casting was found for ufunc float_power".
Returns
- NDArray
The bases in x1 raised to the exponents in x2 at float64/complex128 precision (or
@out). A scalar NDArray if both x1 and x2 are scalars.
Remarks
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.).
float_power(NDArray, object)
First array elements raised to powers from second array, element-wise, at a minimum precision of float64 (np.float_power). Scalar or array-like exponent version.
public static NDArray float_power(NDArray x1, object x2)
Parameters
Returns
- NDArray
The bases in x1 raised to the exponents in x2 at float64/complex128 precision.
Remarks
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.).
floor(NDArray, NDArray, NDArray, DType)
Return the floor of the input, element-wise.
The floor of the scalar x is the largest integer i, such that i <= x. It is often denoted as \lfloor x \rfloor.
public static NDArray floor(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array
outNDArrayA location into which the result is stored (NumPy ufunc out=);
nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeThe loop dtype (NumPy's
dtype=):xmust cast to it undersame_kind, so a float input with an integer dtype is refused.nullkeeps the input's dtype (an integer input stays integer, as in NumPy 2.x).
Returns
- NDArray
The floor of each element in x, in the input's dtype unless
dtypenames another. This is a scalar if x is a scalar.
Remarks
Exceptions
- TypeError
A
dtypethe input cannot reach undersame_kind(Cannot cast ufunc 'floor' input from dtype('float64') to dtype('int64') with casting rule 'same_kind'; NumPy raisesUFuncTypeError).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
floor_divide(NDArray, NDArray, NDArray, NDArray, DType)
Return the largest integer smaller or equal to the division of the inputs.
It is equivalent to the Python // operator.
Mirrors NumPy's ufunc signature: floor_divide(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray floor_divide(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayDividend array.
x2NDArrayDivisor array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs in this dtype; inputs must be same_kind-castable to it.
Returns
- NDArray
y = floor(x1/x2). This is a scalar if both x1 and x2 are scalars.
Remarks
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.).- IncorrectTypeException
A bool or complex
dtype: floor_divide has integer and float loops only, so NumPy'sNo loop matching the specified signature and casting was found for ufunc floor_divide(parity QA-53).
floor_divide(NDArray, object)
Return the largest integer smaller or equal to the division of the inputs. Scalar or array-like divisor version.
public static NDArray floor_divide(NDArray x1, object x2)
Parameters
Returns
- NDArray
y = floor(x1/x2).
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.).
fmax(NDArray, NDArray, NDArray, NDArray, DType)
Element-wise maximum of array elements, IGNORING NaNs.
Compare two arrays and return a new array containing the element-wise maxima. If one element
is a NaN the non-NaN element is returned (both NaN → the first), so NaNs are ignored where
possible. Use maximum(NDArray, NDArray, NDArray, NDArray, DType) to propagate
NaNs instead. Mirrors NumPy's ufunc signature: fmax(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray fmax(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst operand. If shapes differ they must broadcast to a common shape.
x2NDArraySecond operand. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=): joins the broadcast without being stretched, same_kind-castable from the loop dtype, returned as-is. A read-only/broadcast out is refused.
whereNDArrayBoolean mask (NumPy ufunc where=): only mask-true elements are computed/written; masked-off
outslots keep prior contents. Must be a bool array.dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.
Returns
- NDArray
The element-wise NaN-ignoring maximum (or
outwhen supplied). A scalar if both inputs are scalars.
Remarks
Exceptions
- TypeError
outis not same_kind-castable (NumPy-verbatim text).- ArgumentException
whereis not bool, or the shapes do not broadcast (NumPy-verbatim texts).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
fmin(NDArray, NDArray, NDArray, NDArray, DType)
Element-wise minimum of array elements, IGNORING NaNs.
Compare two arrays and return a new array containing the element-wise minima. If one element
is a NaN the non-NaN element is returned (both NaN → the first), so NaNs are ignored where
possible. Use minimum(NDArray, NDArray, NDArray, NDArray, DType) to propagate
NaNs instead. Mirrors NumPy's ufunc signature: fmin(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray fmin(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst operand. If shapes differ they must broadcast to a common shape.
x2NDArraySecond operand. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=): joins the broadcast without being stretched, same_kind-castable from the loop dtype, returned as-is. A read-only/broadcast out is refused.
whereNDArrayBoolean mask (NumPy ufunc where=): only mask-true elements are computed/written; masked-off
outslots keep prior contents. Must be a bool array.dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.
Returns
- NDArray
The element-wise NaN-ignoring minimum (or
outwhen supplied). A scalar if both inputs are scalars.
Remarks
Exceptions
- TypeError
outis not same_kind-castable (NumPy-verbatim text).- ArgumentException
whereis not bool, or the shapes do not broadcast (NumPy-verbatim texts).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
fmod(NDArray, NDArray, NDArray, NDArray, DType)
Return the element-wise C-library remainder of division. Unlike
mod(NDArray, NDArray, NDArray, NDArray, DType) /
remainder(NDArray, NDArray, NDArray, NDArray, DType) (floored — result has the
DIVISOR's sign), fmod uses truncated division so the result has the DIVIDEND's sign:
fmod(-7, 3) == -1 where mod(-7, 3) == 2. Integer inputs stay integer (NEP50;
bool -> int8); floats follow C fmod (fmod(x, 0) == NaN, etc.). Complex is not
supported (NumPy has no complex fmod loop).
Mirrors NumPy's ufunc signature: fmod(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray fmod(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayDividend array.
x2NDArrayDivisor array; broadcasts against
x1.outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): computation runs in this dtype.
Returns
- NDArray
The truncated remainders, or
outitself when given.
Remarks
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.).- IncorrectTypeException
A bool or complex
dtype: fmod has integer and float loops only, so NumPy'sNo loop matching the specified signature and casting was found for ufunc fmod(parity QA-53).
fmod(NDArray, object)
public static NDArray fmod(NDArray x1, object x2)
Parameters
Returns
format_float_positional(object, int?, bool, bool, string, bool, int?, int?, int?)
Formats a floating-point scalar in positional notation with NumPy's Dragon4 (NumPy's
np.format_float_positional): the shortest digits that identify the value by default, every digit
under control of the options.
public static string format_float_positional(object x, int? precision = null, bool unique = true, bool fractional = true, string trim = "k", bool sign = false, int? pad_left = null, int? pad_right = null, int? min_digits = null)
Parameters
xobjectThe value. A Half formats as
np.float16and a float asnp.float32, each with its OWN shortest digits (0.1fprints'0.1', not float64's'0.10000000149011612'); a double asnp.float64; anything else converts like Python'sfloat(x)to a float64 — a C# integer or BigInteger (a Python int, correctly rounded), a bool, a char (NumSharp's Char dtype, NumPy'snp.uint16: its number), a decimal, a 0-d NDArray (its element; a 0-d text array parsed as a float literal).precisionint?The most digits to print after the point (with
fractionalfalse: significant digits); null prints the digitsuniqueasks for. The last digit is rounded (half to even on the exact value), and in unique mode a rounding that carries through 9s prints FEWER digits (1.99999at precision 2 is'2.').uniqueboolTrue: the shortest digits that read back as the value, cut at
precision. False: the value's exact digits toprecision, which is then required.fractionalboolTrue:
precisionandmin_digitscount digits after the point; false: all significant digits.trimstringTrailing zeros and point:
"k"keeps them (and pads exact mode to the precision),"."trims the zeros,"0"trims all but one zero after the point,"-"trims the zeros and the point.signboolPrint '+' before a non-negative value.
pad_leftint?Pad with spaces on the left until the integer part (with its sign) has this many characters.
pad_rightint?Pad with spaces on the right until the fraction has this many characters.
min_digitsint?The fewest digits to print in unique mode (zeros pad it); counted like
precision.
Returns
- string
The text; an infinity is
'inf'/'-inf'('+inf'withsign), a NaN'nan'(never signed), neither padded.
Remarks
NumPy's arrayprint.format_float_positional and its C dragon4_positional, statement for statement
(NumSharp.Backends.Printing.Dragon4's port of dragon4.c).
https://numpy.org/doc/stable/reference/generated/numpy.format_float_positional.html
Exceptions
- ValueError
A negative
precision/pad_left/pad_right/min_digits(precision must be >= 0, checked in that order);fractionalfalse with precision 0 (precision must be greater than 0 if fractional=False);min_digitsabove a positive precision (min_digits must be less than or equal to precision); a 0-d text array that spells no float.- TypeError
A trim other than one of the four characters (NumPy's text,
str(trim)right-aligned in 100 characters);uniquefalse without a precision (in non-unique mode); anprecisionmust be suppliedxthat is not a real number (must be real number, not str; an array of one or more dimensions:only 0-dimensional arrays can be converted to Python scalars) — raised in that order, after the ValueErrors.- OverflowError
A Python int beyond the float range (
int too large to convert to float).- RuntimeError
Zeros or padding beyond NumPy's 16384-character buffer (
Float formatting result too large).
format_float_scientific(object, int?, bool, string, bool, int?, int?, int?)
Formats a floating-point scalar in scientific notation with NumPy's Dragon4 (NumPy's
np.format_float_scientific): one digit before the point, the shortest digits that identify the value
after it by default, and an exponent of at least two digits.
public static string format_float_scientific(object x, int? precision = null, bool unique = true, string trim = "k", bool sign = false, int? pad_left = null, int? exp_digits = null, int? min_digits = null)
Parameters
xobjectThe value, as for format_float_positional(object, int?, bool, bool, string, bool, int?, int?, int?) (a Half / float formats with its own width's digits).
precisionint?The most digits to print after the point; null prints the digits
uniqueasks for. In unique mode a rounding that carries through 9s prints fewer digits (0.0995at precision 1 is'1.e-01').uniqueboolTrue: the shortest digits, cut at
precision; false: the exact digits toprecision, which is then required.trimstringAs for format_float_positional(object, int?, bool, bool, string, bool, int?, int?, int?), except that
"-"keeps the point when a fraction digit was generated and trimmed away ('1.e-01'), dropping it only when none was ('1e+00').signboolPrint '+' before a non-negative value.
pad_leftint?Pad with spaces on the left until the integer part (one digit and the sign) has this many characters.
exp_digitsint?The fewest exponent digits (default 2; at most 5 are honoured; 0 prints no exponent digit for exponent 0:
'1.5e+').min_digitsint?The fewest digits after the point in unique mode (zeros pad it).
Returns
- string
The text; the special values as for format_float_positional(object, int?, bool, bool, string, bool, int?, int?, int?).
Remarks
NumPy's arrayprint.format_float_scientific and its C dragon4_scientific, statement for
statement. NumPy's zero padding does not count down its buffer, so a huge precision in exact mode returns a
text a few characters longer than NumPy's 16383-character limit — NumPy's own result, reproduced.
https://numpy.org/doc/stable/reference/generated/numpy.format_float_scientific.html
Exceptions
- ValueError
A negative
precision/pad_left/exp_digits/min_digits(checked in that order);min_digitsabove a positive precision; a 0-d text array that spells no float.- TypeError
A bad trim;
uniquefalse without a precision; anxthat is not a real number — in that order, after the ValueErrors.- OverflowError
A Python int beyond the float range.
frexp(NDArray, (NDArray, NDArray), NDArray, DType)
Decompose each element of x into a normalized fraction and an integer power
of two, element-wise: returns (mantissa, exponent) such that
x == mantissa * 2^exponent, with the mantissa in the half-open interval [0.5, 1). This is
the two-output inverse of ldexp(NDArray, NDArray, NDArray, NDArray, DType).
Mirrors NumPy's ufunc frexp(x) -> (mantissa, exponent).
public static (NDArray Mantissa, NDArray Exponent) frexp(NDArray x, (NDArray, NDArray) @out = default, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array. Integer/bool inputs promote to a float per NumPy's width rule (bool/int8/uint8 → float16, int16/uint16/char → float32, int32+ → float64); Half/Single/Double are preserved and Decimal is a NumSharp extension (computed through the double bridge). A complex input is rejected — frexp has no complex loop.
out(NDArray Lhs, NDArray Rhs)NumPy's
out=(o1, o2): the mantissa output (same_kind-castable from the mantissa loop dtype) and the exponent output (same_kind-castable from int32; int64 accepted), each ofx's shape and returned as-is; either slot may be null (NumPy's(None, e)),defaultallocates both.whereNDArrayBoolean mask (NumPy ufunc
where=): with outputs supplied, only mask-true elements are written and masked-off slots keep their prior contents.dtypeDTypeNumPy's
dtype=, which frexp accepts only as null: any dtype would apply to both outputs and no loop has a non-int32 exponent, so NumPy raises "No loop matching ..." (2.4.2).
Returns
- (NDArray Lhs, NDArray Rhs)
A tuple
(Mantissa, Exponent): the mantissa in the promoted float dtype, and the int32 exponent (NumPy's exponent is always int32, regardless of the mantissa width) — or the supplied outputs. Both have the shape ofx; an F-contiguous input yields F-contiguous outputs. Each is a 0-d scalar whenxis a scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.frexp.html
Special values follow win-amd64 NumPy 2.4.2 exactly (its scalar C-runtime npy_frexp):
frexp(±0) = (±0, 0), frexp(±inf) = (±inf, -1), frexp(NaN) = (NaN, -1) — note
the exponent is -1, not 0, for ±inf/NaN — and a signalling NaN mantissa is quieted.
NumPy's signature frexp(x, /, out=(None, None), *, where=True, ..., dtype=None): the outputs are
ONE tuple parameter, as divmod(NDArray, NDArray, (NDArray Quotient, NDArray Remainder), NDArray, DType)'s (the former out1 / out2 parameters went on
2026-11-11). NumPy's single array as out ('out' must be a tuple of arrays) cannot be written in
C#.
Exceptions
- IncorrectTypeException
A complex input (no loop), or any
dtype.
frombuffer(MemoryView, DType, long, long)
Interpret a np.MemoryView (obtained from data) as a
1-dimensional array, sharing its memory (zero-copy) — the consumer side of ndarray.data.
public static NDArray frombuffer(np.MemoryView buffer, DType dtype = null, long count = -1, long offset = 0)
Parameters
buffernp.MemoryViewA np.MemoryView over a C-contiguous array.
dtypeDTypeData-type of the returned array; null is float64. Any dtype reads the array's bytes, whatever the array's own dtype.
countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
A 1-D NDArray that VIEWS the buffer's memory (writes through to the source); its base is the source array's owner, which stays alive while the result does. Read-only for good when the memoryview is (a broadcast or otherwise read-only source):
setflags(write: true)refuses it. For a non-nativedtype, a decoded native copy.
Remarks
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long), in its order.
- BufferError
The memoryview is not C-contiguous (NumPy's
memoryview: underlying buffer is not C-contiguous, raised after the dtype checks and before the range checks).- ArgumentNullException
bufferis null.- NotSupportedException
dtypehas no NumSharp storage.
frombuffer(MemoryView, NPTypeCode, long, long)
Interpret a np.MemoryView as a 1-dimensional array, the dtype given as a storage lane.
public static NDArray frombuffer(np.MemoryView buffer, NPTypeCode dtype, long count = -1, long offset = 0)
Parameters
buffernp.MemoryViewA np.MemoryView over a C-contiguous array.
dtypeNPTypeCodeData-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized
np.str_, refused.countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
A 1-D array that views the buffer (see frombuffer(MemoryView, DType, long, long)).
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long).
- BufferError
The memoryview is not C-contiguous.
- ArgumentNullException
bufferis null.
frombuffer(MemoryView, string, long, long)
Interpret a np.MemoryView as a 1-dimensional array, given a dtype STRING
(e.g. "<i4", ">u4" for big-endian uint32, "S3").
public static NDArray frombuffer(np.MemoryView buffer, string dtype, long count = -1, long offset = 0)
Parameters
buffernp.MemoryViewA np.MemoryView over a C-contiguous array.
dtypestringThe dtype's name, read by dtype(string, bool, bool, IReadOnlyDictionary<string, object>) (NumPy's
PyArray_DescrConverter: a sized or one-letter code with an optional byte-order prefix, a NumPy name, a fixed-width string); null is float64 (NumPy'sNone).countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
A 1-D array that views the buffer; a decoded native copy for a non-native name.
Exceptions
- ValueError
dtypespells NEP 55StringDType("T"): NumPy'scannot create an OBJECT array from memory buffer; or the texts of frombuffer(byte[], DType, long, long).- NotSupportedException
dtypenames no dtype (np.dtype'sdata type 'x' not understood, NumPy's TypeError, the empty name included) or one NumSharp does not have (complex64); raised before the buffer is read.- BufferError
The memoryview is not C-contiguous.
- ArgumentNullException
bufferis null.
frombuffer(ArraySegment<byte>, DType, long)
Interpret an ArraySegment as a 1-dimensional array: the segment IS the buffer (NumPy's frombuffer of a sliced memoryview), so its items end at the segment's end, not at the end of the array behind it.
public static NDArray frombuffer(ArraySegment<byte> segment, DType dtype = null, long count = -1)
Parameters
segmentArraySegment<byte>The array segment to interpret. A default segment (no array) is an empty buffer, as NumPy's
b''is.dtypeDTypeData-type of the returned array; null is float64.
countlongNumber of items to read. A negative number reads every whole item of the segment.
Returns
- NDArray
A 1-D array viewing the segment's bytes (it pins the array behind them; writeable).
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long), in its order.
- NotSupportedException
dtypehas no NumSharp storage.
frombuffer(ArraySegment<byte>, NPTypeCode, long)
Interpret an ArraySegment as a 1-dimensional array, the dtype given as a storage lane.
public static NDArray frombuffer(ArraySegment<byte> segment, NPTypeCode dtype, long count = -1)
Parameters
segmentArraySegment<byte>The array segment to interpret (a default segment is an empty buffer).
dtypeNPTypeCodeData-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized
np.str_, refused.countlongNumber of items to read. A negative number reads every whole item of the segment.
Returns
- NDArray
A 1-D array viewing the segment's bytes.
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long).
frombuffer(byte[], DType, long, long)
Interpret a buffer as a 1-dimensional array.
public static NDArray frombuffer(byte[] buffer, DType dtype = null, long count = -1, long offset = 0)
Parameters
bufferbyte[]The bytes (a C#
byte[]is mutable, NumPy'sbytearray: the result is writeable).dtypeDTypeData-type of the returned array; null is float64 (NumPy's default).
countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
A 1-D array that VIEWS the buffer (it pins the array and shares its memory: a write through it changes
buffer); it does not own its data. For a non-nativedtype('>i4') a decoded native copy, because NumSharp stores every array in host byte order.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html
The buffer stays pinned until the last array over it is disposed or collected.
Exceptions
- ValueError
NumPy's texts, in its order:
cannot create an OBJECT array from memory buffer(a NEP 55StringDType, whose cells hold references);itemsize cannot be zero in type(an unsized string dtype);offset must be non-negative and no greater than buffer length (N);buffer size must be a multiple of element size(a negativecountthat leaves a partial item);buffer is smaller than requested size.- ArgumentNullException
bufferis null (checked after the dtype, as NumPy asks for the buffer after its descriptor checks).- NotSupportedException
dtypehas no NumSharp storage.
frombuffer(byte[], NPTypeCode, long, long)
Interpret a buffer as a 1-dimensional array, the dtype given as a storage lane.
public static NDArray frombuffer(byte[] buffer, NPTypeCode dtype, long count = -1, long offset = 0)
Parameters
bufferbyte[]The bytes (writable: the result is writeable).
dtypeNPTypeCodeData-type of the returned array: a storage lane; Empty is float64, and String (a string lane without a width) is NumPy's unsized
np.str_, refused.countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
A 1-D array that views the buffer (see frombuffer(byte[], DType, long, long)).
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long); String raises
itemsize cannot be zero in typebefore the buffer is read.- ArgumentNullException
bufferis null.
frombuffer(byte[], string, long, long)
Interpret a buffer as a 1-dimensional array, given a dtype STRING (e.g. ">u4" for big-endian uint32).
public static NDArray frombuffer(byte[] buffer, string dtype, long count = -1, long offset = 0)
Parameters
bufferbyte[]The bytes (writable: the result is writeable).
dtypestringThe dtype's name, read by dtype(string, bool, bool, IReadOnlyDictionary<string, object>) (NumPy's
PyArray_DescrConverter: a sized or one-letter code with an optional byte-order prefix, a NumPy name, a fixed-width string); null is float64 (NumPy'sNone).countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
A 1-D array that views the buffer; a decoded native copy for a big-endian name (
">u4").
Exceptions
- ValueError
dtypespells NEP 55StringDType("T"): NumPy'scannot create an OBJECT array from memory buffer; or the texts of frombuffer(byte[], DType, long, long).- NotSupportedException
dtypenames no dtype (np.dtype'sdata type 'x' not understood, NumPy's TypeError, the empty name included) or one NumSharp does not have (complex64); raised before the buffer is read.- ArgumentNullException
bufferis null.
frombuffer(nint, long, DType, long, long, Action)
Interpret unmanaged memory at a pointer as a 1-dimensional array.
public static NDArray frombuffer(nint address, long byteLength, DType dtype = null, long count = -1, long offset = 0, Action dispose = null)
Parameters
addressnintPointer to the start of the buffer.
byteLengthlongTotal length of the buffer in bytes.
dtypeDTypeData-type of the returned array; null is float64.
countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongByte offset into the buffer. Default is 0.
disposeActionOptional cleanup action called when NDArray is disposed. Use to transfer ownership: dispose: () => Marshal.FreeHGlobal(ptr) If null, caller is responsible for memory lifetime (view semantics).
Returns
- NDArray
A 1-D array over the memory: without
disposea view that does not own its data (NumPy's array over a foreign buffer), with it an array that owns the memory and frees it throughdisposewhen the last array over it is released. An empty result withdisposeis a fresh empty array, and the memory is released at once through it. For a non-nativedtype, a decoded native copy (the memory is then released at once too).
Examples
// View only (caller manages lifetime): var arr = np.frombuffer(ptr, length, typeof(float));
// Take ownership (NumSharp frees on dispose): var ptr = Marshal.AllocHGlobal(1024); var arr = np.frombuffer(ptr, 1024, typeof(float), dispose: () => Marshal.FreeHGlobal(ptr));
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long), in its order: a count past the memory is refused (
buffer is smaller than requested size), never capped. On a refused requestdisposeis not called: the caller still owns the memory.- ArgumentNullException
addressis null.- NotSupportedException
dtypehas no NumSharp storage.
frombuffer(nint, long, NPTypeCode, long, long, Action)
Interpret unmanaged memory at a pointer as a 1-dimensional array, the dtype given as a storage lane.
public static NDArray frombuffer(nint address, long byteLength, NPTypeCode dtype, long count = -1, long offset = 0, Action dispose = null)
Parameters
addressnintPointer to the start of the buffer.
byteLengthlongTotal length of the buffer in bytes.
dtypeNPTypeCodeData-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized
np.str_, refused.countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongByte offset into the buffer. Default is 0.
disposeActionOptional cleanup action that transfers ownership of the memory to the array (see frombuffer(nint, long, DType, long, long, Action)).
Returns
- NDArray
A 1-D array over the memory (see frombuffer(nint, long, DType, long, long, Action)).
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long).
- ArgumentNullException
addressis null.
frombuffer(Memory<byte>, DType, long, long)
Interpret a Memory<byte> as a 1-dimensional array: a view of its bytes, whether an array or a memory manager backs it (the memory is pinned while an array over it lives).
public static NDArray frombuffer(Memory<byte> memory, DType dtype = null, long count = -1, long offset = 0)
Parameters
memoryMemory<byte>The memory to interpret; it bounds the buffer (the bytes of an array behind it past its end are never read).
dtypeDTypeData-type of the returned array; null is float64.
countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongByte offset within the memory. Default is 0.
Returns
- NDArray
A 1-D array viewing the memory (writeable). Footgun: a Memory<T> NumSharp hands out over an array's buffer (
nd.Unsafe.Memory<byte>()) does not keep that array alive, and neither does the result.
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long), in its order.
- NotSupportedException
dtypehas no NumSharp storage.
frombuffer(Memory<byte>, NPTypeCode, long, long)
Interpret a Memory<byte> as a 1-dimensional array, the dtype given as a storage lane.
public static NDArray frombuffer(Memory<byte> memory, NPTypeCode dtype, long count = -1, long offset = 0)
Parameters
memoryMemory<byte>The memory to interpret.
dtypeNPTypeCodeData-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized
np.str_, refused.countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongByte offset within the memory. Default is 0.
Returns
- NDArray
A 1-D array viewing the memory.
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long).
frombuffer(ReadOnlySpan<byte>, DType, long, long)
Interpret a ReadOnlySpan as a 1-dimensional array. Note: ReadOnlySpan cannot be pinned, so this always creates a copy.
public static NDArray frombuffer(ReadOnlySpan<byte> buffer, DType dtype = null, long count = -1, long offset = 0)
Parameters
bufferReadOnlySpan<byte>The bytes.
dtypeDTypeData-type of the returned array; null is float64.
countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
A new 1-D array that owns a copy of the selected bytes (decoded to native order for a non-native dtype).
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long), in its order.
- NotSupportedException
dtypehas no NumSharp storage.
frombuffer(ReadOnlySpan<byte>, NPTypeCode, long, long)
Interpret a ReadOnlySpan as a 1-dimensional array, the dtype given as a storage lane. Note: ReadOnlySpan cannot be pinned, so this always creates a copy.
public static NDArray frombuffer(ReadOnlySpan<byte> buffer, NPTypeCode dtype, long count = -1, long offset = 0)
Parameters
bufferReadOnlySpan<byte>The bytes.
dtypeNPTypeCodeData-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized
np.str_, refused.countlongNumber of items to read. A negative number reads every whole item after
offset.offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
A new 1-D array that owns a copy of the selected bytes.
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long).
frombuffer(void*, long, DType, long, long, Action)
Interpret unmanaged memory at a pointer as a 1-dimensional array.
public static NDArray frombuffer(void* address, long byteLength, DType dtype = null, long count = -1, long offset = 0, Action dispose = null)
Parameters
addressvoid*Pointer to the start of the buffer.
byteLengthlongTotal length of the buffer in bytes.
dtypeDTypeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data.
offsetlongByte offset into the buffer. Default is 0.
disposeActionOptional cleanup action called when NDArray is disposed.
Returns
- NDArray
1-dimensional NDArray viewing/owning the memory.
Exceptions
- ValueError
- ArgumentNullException
addressis null.
frombuffer(void*, long, NPTypeCode, long, long, Action)
Interpret unmanaged memory at a pointer as a 1-dimensional array.
public static NDArray frombuffer(void* address, long byteLength, NPTypeCode dtype, long count = -1, long offset = 0, Action dispose = null)
Parameters
addressvoid*Pointer to the start of the buffer.
byteLengthlongTotal length of the buffer in bytes.
dtypeNPTypeCodeData-type of the returned array, as a storage lane.
countlongNumber of items to read. -1 means all data.
offsetlongByte offset into the buffer. Default is 0.
disposeActionOptional cleanup action called when NDArray is disposed.
Returns
- NDArray
1-dimensional NDArray viewing/owning the memory.
Exceptions
- ValueError
- ArgumentNullException
addressis null.
frombuffer<TSource>(TSource[], DType, long, long)
Reinterpret a typed array as a different dtype. Like NumPy's view() but via frombuffer semantics.
public static NDArray frombuffer<TSource>(TSource[] array, DType dtype = null, long count = -1, long offset = 0) where TSource : unmanaged
Parameters
arrayTSource[]The source array to reinterpret: its bytes are the buffer (pinned while an array over it lives).
dtypeDTypeTarget data-type. Default (null) preserves the source type - a NumSharp extension: NumPy's frombuffer of an ndarray reads float64.
countlongNumber of items of target dtype. A negative number reads every whole item.
offsetlongByte offset. Default is 0.
Returns
- NDArray
1-dimensional NDArray viewing the array as the target dtype.
Type Parameters
TSourceSource element type.
Examples
var ints = new int[] { 1, 2, 3, 4 }; var asBytes = np.frombuffer(ints, typeof(byte)); // 16 bytes var asFloats = np.frombuffer(ints, typeof(float)); // 4 floats (same bits)
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long), in its order: a count past the array is refused (
buffer is smaller than requested size), never capped.- ArgumentNullException
arrayis null.- NotSupportedException
dtypehas no NumSharp storage.
frombuffer<TSource>(TSource[], NPTypeCode, long, long)
Reinterpret a typed array as a different dtype, the dtype given as a storage lane.
public static NDArray frombuffer<TSource>(TSource[] array, NPTypeCode dtype, long count = -1, long offset = 0) where TSource : unmanaged
Parameters
arrayTSource[]The source array to reinterpret (pinned while an array over it lives).
dtypeNPTypeCodeTarget data-type: a storage lane; Empty preserves the source type, and String is NumPy's unsized
np.str_, refused.countlongNumber of items of target dtype. A negative number reads every whole item.
offsetlongByte offset. Default is 0.
Returns
- NDArray
1-dimensional NDArray viewing the array as the target dtype.
Type Parameters
TSourceSource element type.
Exceptions
- ValueError
The texts of frombuffer(byte[], DType, long, long).
- ArgumentNullException
arrayis null.
fromfile(Stream, DType, long, string, long, NDArray)
Construct an array from data in an open Stream (NumPy's file-object form), from its current position. The stream stays open and ends where NumPy leaves the Python file: after the bytes the read consumed (a binary read's partial trailing item included, a text scanner's look-ahead byte excluded), also when the read raises.
public static NDArray fromfile(Stream stream, DType dtype = null, long count = -1, string sep = "", long offset = 0, NDArray like = null)
Parameters
streamStreamThe stream. A non-seekable one is read as NumPy cannot (it needs a seekable file descriptor): a binary count of -1 reads to the end, and a text read's look-ahead stays consumed.
dtypeDTypeElement type (default float64).
countlongElements to read; negative (default -1) reads to the end.
sepstringSeparator between items of a text file. Empty (default) reads binary.
offsetlongBytes to skip from the stream's position first. Binary only.
likeNDArrayAccepted for NumPy's signature; no effect.
Returns
- NDArray
The 1-D array of the elements read.
Exceptions
- ArgumentNullException
streamis null.- UnicodeEncodeError
sepholds a lone surrogate.- TypeError
sepis null, or anoffsetwith a text separator.- OSError
An offset before the start of the stream (
[Errno 22] Invalid argument).- ValueError
- NotSupportedException
An unsized string dtype with a count of 0 or more.
fromfile(string, DType, long, string, long, NDArray)
Construct an array from data in a text or binary file. Efficient for binary data of a known dtype, and parses simply-formatted text files. Data written with tofile(string, string, string) can be read back with this function.
public static NDArray fromfile(string file, DType dtype = null, long count = -1, string sep = "", long offset = 0, NDArray like = null)
Parameters
filestringA file name.
dtypeDTypeElement type (default float64). Binary: its item size; text: the scanner NumPy's dtype has (signed / unsigned integers through glibc's
fscanf, floats and bools through NumPy's own float reader, complex throughCDOUBLE_scan). A non-native byte order ('>i4') reads big-endian binary data into a native array.countlongElements to read; negative (default -1) reads the whole file.
sepstringSeparator between items of a text file. Empty (default) reads binary. A space of it matches any run of whitespace (none included), and whitespace around the separator is always allowed.
offsetlongBytes to skip from the file's current position first. Binary files only.
likeNDArrayReference array for NumPy's array-function dispatch: accepted for signature parity, no effect.
Returns
- NDArray
The 1-D array of the elements read.
Remarks
NumPy's checks, in its order: sep's conversion (a lone surrogate is CPython's
UnicodeEncodeError, a NUL embedded null character), an offset with a
separator, the file, the offset seek, then the dtype (a StringDType cannot be read, an unsized string dtype
builds count zero-width elements, a string dtype has no text scanner).
A text read stops at the end of the file, after count elements (the separator after the last
one is then optional), or at a separator that does not match; an element that does not scan is NumPy's
ValueError. The scanners consume what NumPy's do: "1.5e,2" reads 1.5 and 2 (the dangling
e is consumed), "1, " is an error for a float and not for an integer.
https://numpy.org/doc/stable/reference/generated/numpy.fromfile.html
Exceptions
- ArgumentNullException
fileis null.- UnicodeEncodeError
sepholds a lone surrogate.- TypeError
sepis null (NumPy'ssep=None:fromfile() argument 4 must be str, not None), or anoffsetwith a text separator ('offset' argument only permitted for binary files), checked before the file is opened.- FileNotFoundError
No such file (Python's
[Errno 2] No such file or directory: 'name').- PermissionError
The file cannot be opened for reading (
[Errno 13] Permission denied; on Windows also a directory).- IsADirectoryError
The name is a directory (Linux and macOS:
[Errno 21] Is a directory).- OSError
An offset before the start of the file (
[Errno 22] Invalid argument).- ValueError
sepholds a NUL; aStringDType(Cannot read into object array); an unsized string dtype with a negative count, or a count past the end of a binary file (negative dimensions are not allowed); a string dtype with a separator (Unable to read character files of that array type); text that does not scan to its end (string or file could not be read to its end due to unmatched data); a count no array can hold (array is too big).- NotSupportedException
An unsized string dtype with a count of 0 or more: NumPy builds zero-width elements, which NumSharp's string buffers cannot hold.
fromfunction(Func<NDArray[], NDArray>, Shape, DType)
Constructs an array by executing a function over each coordinate — NumPy's
np.fromfunction(function, shape, *, dtype=float): function is called ONCE with one
index grid per dimension (NumPy's np.indices(shape, dtype)), and its result is returned as is.
public static NDArray fromfunction(Func<NDArray[], NDArray> function, Shape shape, DType dtype = null)
Parameters
functionFunc<NDArray[], NDArray>The function, called once with the coordinate grids — NumPy's
function(*args)with the grids as one array:ix => ix[0] + ix[1]is NumPy'slambda i, j: i + j, for any rank. It must be vectorized (it receives whole grids, not single coordinates). NumPy's**kwargs(passed on to the function) are values the C# lambda captures instead.shapeShapeThe output shape, which also sets each grid's shape: a tuple (
(2, 3)), anint[]/long[]or a Shape.dtypeDTypeThe grids' dtype (NumPy's
dtype=floatdefault): null is float64; passnp.int64for integer coordinates.
Returns
- NDArray
Whatever
functionreturns — usually an array ofshape; a C# number the lambda returns arrives as a 0-d array (C# converts it to the NDArray the delegate returns, where NumPy hands back the Python number itself).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.fromfunction.html — NumPy's body is
args = indices(shape, dtype=dtype); return function(*args, **kwargs).
Ownership (the np.ma.fromfunction contract): whatever function
returns is the CALLER's, so the call runs outside any scope of this method's. The index grids handed to the
function are this method's own and are released when it returns (on a throw too) — so a function must not
keep its ARGUMENTS past the call. A grid it returns as is IS the result and is kept; a view of a grid holds
its own reference to the grid buffer.
Two C# differences (pinned as [Misaligned] tests): an int shape converts to
the 1-D shape (n,), where NumPy needs a tuple (TypeError: 'int' object is not iterable); and
the number-result conversion above. like= is not modelled (the parity plan's exclusion). Added to
np in API-parity batch 7 (it existed as np.ma.fromfunction).
Exceptions
- ValueError
A negative dimension (
negative dimensions are not allowed), raised beforefunctionruns, as NumPy'snp.indicesraises it.- TypeError
functionis null ('NoneType' object is not callable, raised after the grids are built, as in NumPy).- Exception
Whatever
functionthrows, unchanged.
fromiter(IEnumerable, DType, long)
Creates a new 1-D array from an iterable — NumPy's np.fromiter(iter, dtype, count=-1): every item is
converted into dtype the way NumPy's per-item store (PyArray_Pack, the dtype's
setitem) converts it, and the result holds exactly the items read.
public static NDArray fromiter(IEnumerable iter, DType dtype, long count = -1)
Parameters
iterIEnumerableAny C# sequence (an array, a list, a LINQ query, an iterator method, an NDArray). Items are Python values under NumSharp's boundary map: numbers by value (a float into an integer dtype truncates; an integer the dtype cannot hold is NumPy's OverflowError), text by parsing (
"1.5"into float64), null as None (NaN for a float, TypeError for an integer), a char as a one-character str (a string iterates its characters, as a Python str does), a 0-d NDArray as its value. Iterating an N-D NDArray yields its rows, as in NumPy.dtypeDTypeThe result's dtype — NumPy's required argument; null is NumPy's None, the default float64 (not a dtype inferred from the items).
countlongHow many items to read: -1 (the default) reads them all; a non-negative count reads at most that many (an infinite sequence is fine) and requires that many; any other negative count reads nothing (NumPy's loop,
i < count || count == -1, gives an empty array).
Returns
- NDArray
A new, owning, C-contiguous 1-D array of
dtype.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.fromiter.html — NumPy's PyArray_FromIter, step
for step: the iterator, the unsized-dtype check, one item at a time until count, each
item packed (its error raised at once, so a bad item beats a short iterator), then the short-iterator check.
The packing of plain items is array(Array, DType, int, bool, char) over the items read,
whose list conversion is NumPy's setitem per element. A SEQUENCE item (a C# array or list is a Python list, a
tuple a Python tuple, an array of rank 1 or more an ndarray) is answered here, because NumPy's per-item
store does not nest it the way np.array does: each dtype's setitem answers in its own words (an
integer's int() TypeError, a float's and text's "sequence" ValueError, complex's TypeErrors), a bool
dtype stores its truth value (a non-empty list is True; an array only when it has one element), and a
StringDType stores its str(). The items before it convert first, so their errors come
first.
like= is not modelled (the parity plan's exclusion). Added in API-parity batch 7 (the gap
document's OD10 row for fromiter, decided by the owner's approval).
Exceptions
- TypeError
iteris null ('NoneType' object is not iterable) or a 0-d array (iteration over a 0-d array) — checked first, as NumPy gets the iterator first; an item the dtype's conversion refuses with Python's TypeError (int() argument must be a string, a bytes-like object or a real number, not 'NoneType',float() argument must be a string or a real number, not 'complex'; for a sequence itemint() ... not 'list'into an integer dtype,must be real number, not list/only 0-dimensional arrays can be converted to Python scalarsinto complex).- ValueError
dtypeis an unsized text dtype ("U","S":Must specify length when using variable-size data-type.); fewer items than a non-negativecount(iterator too short: Expected 7 but iterator had only 5 items., after the items read converted); an item that does not parse (invalid literal for int() with base 10: 'a'), a NaN into an integer dtype, a sequence item into a float / text dtype (setting an array element with a sequence.; text's has no period).- OverflowError
An integer the dtype cannot hold (
Python integer 300 out of bounds for int8), an infinity into an integer dtype.- NotSupportedException
A dtype NumSharp has no storage for (object, void, a datetime before its storage stage).
frompyfunc(Delegate, int, int)
Builds a broadcasting callable from an arbitrary delegate — NumSharp's typed analog of NumPy's
frompyfunc(func, nin, nout). Divergence: NumPy's frompyfunc returns a ufunc over
OBJECT arrays; NumSharp has no object dtype, so this returns a Vectorized that produces
TYPED arrays of the delegate's own return type(s). The ufunc-only surface (reduce/accumulate/
identity) has no NumSharp analog and is not provided.
public static Vectorized frompyfunc(Delegate func, int nin, int nout)
Parameters
funcDelegateThe scalar function to broadcast (any supported arity; may return a tuple for multi-output).
ninintDeclared input count. Validated against the delegate's parameter count (C# knows the arity), unlike NumPy where it DEFINES the count.
noutintDeclared output count. Validated against the delegate's return (1, or its ValueTuple arity).
Returns
- Vectorized
A Vectorized applying
funcelement-wise; use Call(params NDArray[]) or CallMany(params NDArray[]).
Remarks
Exceptions
- ArgumentNullException
funcis null.- ValueError
ninornoutdisagrees with the delegate's actual arity / return-component count.
fromstring(byte[], DType, long, string, NDArray)
Construct a 1-D array from the numbers in a byte string (NumPy's bytes argument, read as it is).
public static NDArray fromstring(byte[] @string, DType dtype = null, long count = -1, string sep = null, NDArray like = null)
Parameters
stringbyte[]The text's bytes.
dtypeDTypeElement type of the result (default float64).
countlongElements to read; negative reads all of them.
sepstringSeparator between numbers; null or empty is the removed binary mode.
likeNDArrayAccepted for NumPy's signature; no effect.
Returns
- NDArray
The 1-D array.
Exceptions
- ArgumentNullException
stringis null.- UnicodeEncodeError
sepholds a lone surrogate.- ValueError
fromstring(string, DType, long, string, NDArray)
Construct a 1-D array from the numbers in a text string.
public static NDArray fromstring(string @string, DType dtype = null, long count = -1, string sep = null, NDArray like = null)
Parameters
stringstringThe text (NumPy's
strargument: read as its UTF-8 bytes).dtypeDTypeElement type of the result (default float64). Signed integers read with
PyOS_strtol(a sign, then whitespace and digits; past the 64-bit range it saturates), unsigned ones withPyOS_strtoul(no sign at all), bools, floats and complex numbers with NumPy's float reader. A non-native byte order reads as the native dtype.countlongElements to read; negative (default -1) reads all of them. With a count, the result ALWAYS has
countelements (NumPy's): the element after the last one read holds the value the failed scan produced (0 for an integer, -1.0 for a float), and the rest are 0 (uninitialized in NumPy).sepstringSeparator between numbers. A space of it matches any run of whitespace (none included), and whitespace around it is always allowed. Null or empty is the removed binary mode.
likeNDArrayReference array for NumPy's array-function dispatch: accepted for signature parity, no effect.
Returns
- NDArray
The 1-D array.
Remarks
A read stops at the end of the text, after count elements, or at a separator that does not
match. The scanners read what NumPy's do, which is more than a number in places: whitespace alone reads as 0
(or -1.0 for a float), "- 1" as -1, "1+2" as the complex 1+0j, "j" as -1j.
The integer readers work in a C long: NumSharp pins its LP64 (Linux / macOS) width, so a number past the
32-bit range wraps into a narrow dtype from its 64-bit value; Windows NumPy saturates it at 2^31 first.
https://numpy.org/doc/stable/reference/generated/numpy.fromstring.html
Exceptions
- ArgumentNullException
stringis null (NumPy'sNoneis aTypeError:a bytes-like object is required, not 'NoneType').- UnicodeEncodeError
stringorsepholds a lone surrogate (CPython's'utf-8' codec can't encode character '\ud800' in position 5: surrogates not allowed).- ValueError
NumPy's refusals, in NumPy's order: a NUL in
sep(embedded null character); no separator (The binary mode of fromstring is removed, use frombuffer instead); aStringDType(Cannot create an object array from a string); an unsized string dtype (zero-valued itemsize); a sized string dtype (don't know how to read character strings with that array type); a count no array can hold (array is too big); text that does not read to its end (string or file could not be read to its end due to unmatched data).
full(Shape, object, DType, char, string)
Return a new array of given shape and type, filled with fill_value — NumPy's one signature,
np.full(shape, fill_value, dtype=None, order='C', *, device=None).
public static NDArray full(Shape shape, object fill_value, DType dtype = null, char order = 'C', string device = null)
Parameters
shapeShapeThe dimensions: an int (
2), a tuple ((2, 3)), anint[]/long[]or a Shape (all convert implicitly). Only the dimensions are read: the layout comes fromorder, as NumPy's shape is a tuple of ints.fill_valueobjectFill value: a scalar, or an array (an NDArray of rank ≥ 1, a C# array) that broadcasts into the result, as NumPy's
copyto(a, fill_value, casting='unsafe')broadcasts it. A C# value's own type gives the default dtype (a C#intis int32, where NumPy's Python int is int64).dtypeDTypeThe desired dtype — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. Null infers it fromfill_value(an array fill value gives its own dtype).orderchar'C'(row-major, the default) or'F'(column-major), in either case: NumPy'sempty(shape, dtype, order)layout, so'A'and'K'are refused.devicestringNull or
"cpu"(the Array-API device; NumPy has no other).
Returns
- NDArray
A new, owned, writeable array of
shape's dimensions withfill_valuecast into every element.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.full.html — NumPy's a = empty(shape, dtype, order,
device=device); multiarray.copyto(a, fill_value, casting='unsafe'): CreationLayout(Shape, char, string) is empty's
argument handling, full(Shape, object, DType) the inference, allocation and fill.
A null fill_value is Python's None, filled the way NumPy's
copyto(a, None, casting='unsafe') fills it: NaN (the positive NPY_NAN) for a float dtype,
nan+nanj for complex, False for bool, 'None' (truncated) for S / U, a
StringDType's NA object or 'None'.
One signature since API-parity batch 8 (2026-11-12): the int[] / long[] shape overloads went
(both convert to Shape), the order arrived, and the generic full<T> forms went (write
the dtype: np.full(shape, value, np.int32)). The device moved from the fourth position to the fifth.
Exceptions
- ValueError
In NumPy's order:
orderis not one of C, F, A, K;deviceis not"cpu";orderis A or K (only 'C' or 'F' order is permitted); a negative dimension;fill_valueis null anddtypeis aStringDType(coerce=False); an array fill value that does not broadcast into the result (could not broadcast input array from shape (2,) into shape (3,)), or whose text does not parse into a numericdtype.- NotSupportedException
fill_valueis null (Python'sNone) anddtypeis null: NumPy builds an object array there, a dtype NumSharp does not have.- TypeError
fill_valueis null anddtypeis an integer (ordecimal) dtype, for a non-empty shape: Python'sint(None), raised by NumPy'scopyto(a, None, casting='unsafe')(an empty result converts nothing and returns).
full_like(NDArray, object, DType, char, Shape?, string)
Return a full array with the same shape and type as a given array: NumPy's
full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None, *, device=None).
public static NDArray full_like(NDArray a, object fill_value, DType dtype = null, char order = 'K', Shape? shape = null, string device = null)
Parameters
aNDArrayThe shape and data-type of
adefine these same attributes of the returned array.fill_valueobjectFill value: a scalar, or an array (an NDArray of rank ≥ 1, a C# array) that broadcasts into the result.
dtypeDTypeOverrides the data type of the result, or null for
a's.ordercharMemory layout:
'C','F','A'(F whenais F-contiguous and not C-contiguous, else C) or'K'(the default:a's axis order, kept also for ashapeof the same rank), in either case.shapeShape?Overrides the shape of the result (an int, an int[] or a tuple converts to Shape), or null for
a's. With'K'and a different rank the result is C-ordered, as NumPy's.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity; NumPy's is keyword-only).
Returns
- NDArray
Array of
fill_valuewith the requested shape and type. Anumpy.char.chararrayoperand gives a chararray (NumPy allocates the result as the subclass).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.full_like.html
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces the former <code>(a, fill_value, dtype, device)</code> / <code>(a, fill_value, dtype, order, device)</code>
pair,
so <code>order</code> no longer needs a <code>dtype</code> before it and <code>shape</code> takes None; a positional
<code>device</code> is written <code>device: "cpu"</code>. <code>subok</code> stays out (the parity plan's
exclusion).</p>
Exceptions
- ValueError
orderis not one of C, F, A, K in either case (order must be one of 'C', 'F', 'A', or 'K' (got 'Z')), reported before the device, as NumPy's empty_like converts its arguments in order;deviceis neither null nor"cpu"(NumPy'sDevice not understood. Only "cpu" is allowed, but received: ...); a negative dimension inshape(negative dimensions are not allowed); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- ValueError
A
numpy.char.chararrayoperand with a dtype that is not string data: NumPy's finalize error (Can only create a chararray from string data.), before anything is filled; or an array fill value that does not broadcast into the result, or whose text does not parse into a numeric result.- TypeError
Noneinto a non-empty integer (ordecimal) result.- OverflowError
A Python int outside the result's integer range (
np.full_like(int8_array, 1000)).
gcd(NDArray, NDArray, NDArray, NDArray, DType)
Returns the element-wise greatest common divisor of the absolute values of x1
and x2 (np.gcd). gcd(0, 0) == 0 and gcd(0, x) == |x|.
INTEGER-ONLY, exactly like NumPy: a bool/half/single/double/decimal/complex operand — or a
uint64 paired with a signed integer (they promote to float64 under NEP50) — has no
loop and raises the no-loop TypeError. Both inputs and the output share ONE
promoted integer dtype (NumPy's uniform resolver). The result is non-negative EXCEPT where the
magnitude wraps the signed range: gcd(int8 -128, -128) == -128 (no positive int8 holds
128), matching NumPy bit-for-bit. A C# integer literal binds as a weak scalar
(np.gcd(int8_arr, 3) stays int8), matching NEP50.
Mirrors NumPy's ufunc signature gcd(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray gcd(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array (integer dtype).
x2NDArraySecond input array (integer dtype); broadcasts against
x1.outNDArrayA location into which the result is stored (NumPy ufunc
out=); returned as-is.whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc
where=); masked-off slots keep their prior value.dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=): computation runs in this dtype; must name an integer loop.
Returns
- NDArray
The element-wise gcd. A scalar (0-d) when both inputs are scalars.
Remarks
Exceptions
- TypeError
The inputs (or
dtype) name no integer gcd loop.- TypeError
An input is not same_kind-castable to
dtype, oroutcannot take the loop dtype.- ArgumentException
whereis non-boolean, oroutdoes not broadcast.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
geomspace(NDArray, NDArray, long, bool, DType, int)
Return numbers spaced evenly on a log scale (a geometric progression) - NumPy's
np.geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0). Each output sample is a constant
multiple of the previous - like logspace(double, double, long, bool, double, DType, int) but with the
endpoints specified directly rather than as exponents. Array ends give one progression per end pair (they
broadcast), the samples along axis; complex ends give a logarithmic spiral.
public static NDArray geomspace(NDArray start, NDArray stop, long num = 50, bool endpoint = true, DType dtype = null, int axis = 0)
Parameters
startNDArrayThe starting value(s): a number (a C# number converts, read as NumPy reads a Python number), a Complex, or an array that broadcasts with
stop. No element may be zero (a geometric sequence cannot include zero).stopNDArrayThe final value(s) of the sequence, unless
endpointis False. In that casenum + 1values are spaced over the interval in log-space, of which all but the last are returned. No element may be zero.numlongNumber of samples to generate. Default 50. Must be non-negative.
endpointboolIf True (default)
stopis the last sample; otherwise it is excluded.dtypeDTypeThe dtype of the output — one descriptor parameter, like NumPy's
dtype=(Type/NPTypeCode/string/DType convert implicitly). If null (default) the result has the computation dtype: float64 for real number ends, complex128 for complex ones. The samples are computed in NumPy'sdt = result_type(start, stop, float(num), zeros((), dtype))and only then cast (an integer dtype TRUNCATES toward zero); requesting a complex dtype makes the computation complex (the interior then differs from the real path's), and float32 array ends with a float32 dtype compute in float32, as NumPy's do.axisintThe axis in the result that holds the samples (NumPy's trailing
moveaxis(result, 0, axis)): any axis in range for the result's rank, which is one more than the broadcast ends'. For number ends only 0 and -1 exist.
Returns
- NDArray
The samples, shape
(num, *broadcast(start, stop).shape)with the sample axis moved toaxis(for number ends a 1-D array ofnumsamples).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.geomspace.html
API-parity batch 10: one signature over NumPy's array_like ends. The double and
Complex overloads went: a number converts to a 0-d array, and number ends keep
their answers bit for bit (real) or within the complex-unary envelope (complex, as before). Computed by the
start operand's engine (Geomspace(NDArray, NDArray, long, bool, DType, int)). A
numpy.matrix or masked operand computes on its plain data and gives a plain array (NumPy's own answer
for a matrix is a matrix-product error from result *= out_sign).
Exceptions
- ArgumentNullException
startorstopis null.- ValueError
An end holds a zero (
Geometric sequence cannot include zero, NumPy's first check), ornumis negative.- DTypePromotionError
A
StringDTypedtype(no common DType with the ends).- TypeError
An
SorUdtype(signhas no string loop).- IncorrectShapeException
The ends do not broadcast.
- AxisError
axisis out of range for the result (NumPy's verbatimdestination:message).
get_printoptions()
Return the current print options as a dictionary (NumPy's np.get_printoptions).
public static IReadOnlyDictionary<string, object> get_printoptions()
Returns
Remarks
getbufsize()
Return the size of the buffer used in ufuncs (the default buffer size for buffered NDIter/ufunc iteration in the caller's flow).
public static long getbufsize()
Returns
- long
Size of the ufunc buffer, in elements. Defaults to 8192 (NumPy's
NPY_BUFSIZE).
Remarks
Mirrors numpy.getbufsize(). The value is context-local, as NumPy 2.x's extobj
ContextVar is under Python 3.12: it reflects the last setbufsize(long) call in the
caller's flow — an await continuation, Task.Run and the thread pool see their starter's size,
a dedicated thread (new Thread) starts at the 8192 default until it sets its own. The buffer size sets how buffered
iteration is chunked. For almost every operation that is invisible, but — exactly as in NumPy —
a reduction that CASTS through the buffer sums chunk by chunk: np.evaluate's flat
Mean of an integer / bool child adds one pairwise sum per chunk (NumPy's
np.mean(int_array) does the same), so its last bits follow this value. The flat
np.sum / np.mean of a float loop follow it too, exactly as NumPy's do: a cast operand
(dtype=, the mean of integers or float16) and a layout of several short runs (a sliced or
strided 2-D block) are summed one buffer fill at a time.
np.getbufsize(); // 8192
np.setbufsize(4096); // returns 8192 (the previous size)
np.getbufsize(); // 4096
gradient(NDArray, object, int, int)
gradient(NDArray, object, NDAxis?, int) with the axis as one int: the overload a C#
integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so
every answer, error, layout and subclass result is that overload's.
public static np.GradientResult gradient(NDArray f, object spacing, int axis, int edge_order = 1)
Parameters
fNDArrayInput array (samples of a scalar function).
spacingobjectOptional spacing between samples: a scalar sample distance applied to every requested axis, or a 1-D coordinate array giving the sample positions along the (single) requested axis.
null(the default) means unit spacing. Coordinates may be an NDArray, a typed C# array or a Python list (aList<T>, or anobject[]passed as anobject: as anobject[]it binds the spacing-list overload, one spacing per item). A scalar step keeps NumPy's kind: a C# number is a Python number, weak under NEP 50 (a float32fstays float32); a Half,charordecimalis a NumPy scalar and a 0-d NDArray an array, both strong (a float64 0-d step computes a float32fin float64, rounded once).axisintThe axis (NumPy's
axis=k; a negative value counts from the end).edge_orderintBoundary difference order, 1 (default) or 2.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.gradient.html. One signature for a single
spacing since API-parity batch 4 (2026-11-12): it replaces the int?-axis and int[]-axis forms,
so a tuple axis needs no spacing array and np.gradient(f, 2.0, null) is no longer ambiguous (CS0121).
The axis travels as an array (an int as NumPy's one-element tuple, which normalize_axis_tuple makes of
it).
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object, int[], int)
gradient(NDArray, object, NDAxis?, int) with the axes as an int[]: the overload an
int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new
int[0] is ()).
public static np.GradientResult gradient(NDArray f, object spacing, int[] axis, int edge_order = 1)
Parameters
fNDArrayInput array (samples of a scalar function).
spacingobjectOptional spacing between samples: a scalar sample distance applied to every requested axis, or a 1-D coordinate array giving the sample positions along the (single) requested axis.
null(the default) means unit spacing. Coordinates may be an NDArray, a typed C# array or a Python list (aList<T>, or anobject[]passed as anobject: as anobject[]it binds the spacing-list overload, one spacing per item). A scalar step keeps NumPy's kind: a C# number is a Python number, weak under NEP 50 (a float32fstays float32); a Half,charordecimalis a NumPy scalar and a 0-d NDArray an array, both strong (a float64 0-d step computes a float32fin float64, rounded once).axisint[]The axes as NumPy's tuple, or
nullfor None.edge_orderintBoundary difference order, 1 (default) or 2.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.gradient.html. One signature for a single
spacing since API-parity batch 4 (2026-11-12): it replaces the int?-axis and int[]-axis forms,
so a tuple axis needs no spacing array and np.gradient(f, 2.0, null) is no longer ambiguous (CS0121).
The axis travels as an array (an int as NumPy's one-element tuple, which normalize_axis_tuple makes of
it).
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object, NDAxis?, int)
Return the gradient of an N-dimensional array using second-order central differences in the interior and first/second-order one-sided differences at the boundaries.
public static np.GradientResult gradient(NDArray f, object spacing = null, NDAxis? axis = null, int edge_order = 1)
Parameters
fNDArrayInput array (samples of a scalar function).
spacingobjectOptional spacing between samples: a scalar sample distance applied to every requested axis, or a 1-D coordinate array giving the sample positions along the (single) requested axis.
null(the default) means unit spacing. Coordinates may be an NDArray, a typed C# array or a Python list (aList<T>, or anobject[]passed as anobject: as anobject[]it binds the spacing-list overload, one spacing per item). A scalar step keeps NumPy's kind: a C# number is a Python number, weak under NEP 50 (a float32fstays float32); a Half,charordecimalis a NumPy scalar and a 0-d NDArray an array, both strong (a float64 0-d step computes a float32fin float64, rounded once).axisNDAxis?NumPy's
axis(keyword-only there):null(None, the default) computes the gradient for every axis (returning a tuple); one axis, or a tuple ((0, 1),new[] { 0, 1 }) for those axes - a one-element tuple gives NumPy's single array, the empty tuple no component. Negative axes count from the end.edge_orderintBoundary difference order, 1 (default) or 2.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.gradient.html. One signature for a single
spacing since API-parity batch 4 (2026-11-12): it replaces the int?-axis and int[]-axis forms,
so a tuple axis needs no spacing array and np.gradient(f, 2.0, null) is no longer ambiguous (CS0121).
The axis travels as an array (an int as NumPy's one-element tuple, which normalize_axis_tuple makes of
it).
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object, object, int, int)
gradient(NDArray, object, object, NDAxis?, int) with the axis as one int: the
overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static np.GradientResult gradient(NDArray f, object spacing0, object spacing1, int axis, int edge_order = 1)
Parameters
fNDArrayspacing0objectspacing1objectaxisintThe axis (NumPy's
axis=k; a negative value counts from the end).edge_orderint
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object, object, int[], int)
gradient(NDArray, object, object, NDAxis?, int) with the axes as an int[]: the
overload an int[] binds, and a bare null too (null converts to int[] better than to
NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple
(new int[0] is ()).
public static np.GradientResult gradient(NDArray f, object spacing0, object spacing1, int[] axis, int edge_order = 1)
Parameters
fNDArrayspacing0objectspacing1objectaxisint[]The axes as NumPy's tuple, or
nullfor None.edge_orderint
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object, object, NDAxis?, int)
Two per-axis spacings — see the main overload.
public static np.GradientResult gradient(NDArray f, object spacing0, object spacing1, NDAxis? axis = null, int edge_order = 1)
Parameters
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object, object, object, int, int)
gradient(NDArray, object, object, object, NDAxis?, int) with the axis as one int:
the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static np.GradientResult gradient(NDArray f, object spacing0, object spacing1, object spacing2, int axis, int edge_order = 1)
Parameters
fNDArrayspacing0objectspacing1objectspacing2objectaxisintThe axis (NumPy's
axis=k; a negative value counts from the end).edge_orderint
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object, object, object, int[], int)
gradient(NDArray, object, object, object, NDAxis?, int) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static np.GradientResult gradient(NDArray f, object spacing0, object spacing1, object spacing2, int[] axis, int edge_order = 1)
Parameters
fNDArrayspacing0objectspacing1objectspacing2objectaxisint[]The axes as NumPy's tuple, or
nullfor None.edge_orderint
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object, object, object, NDAxis?, int)
Three per-axis spacings — see the main overload.
public static np.GradientResult gradient(NDArray f, object spacing0, object spacing1, object spacing2, NDAxis? axis = null, int edge_order = 1)
Parameters
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object[], int, int)
gradient(NDArray, object[], NDAxis?, int) with the axis as one int: the overload a
C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so
every answer, error, layout and subclass result is that overload's.
public static np.GradientResult gradient(NDArray f, object[] varargs, int axis, int edge_order = 1)
Parameters
fNDArrayvarargsobject[]axisintThe axis (NumPy's
axis=k; a negative value counts from the end).edge_orderint
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object[], int[], int)
gradient(NDArray, object[], NDAxis?, int) with the axes as an int[]: the overload
an int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new
int[0] is ()).
public static np.GradientResult gradient(NDArray f, object[] varargs, int[] axis, int edge_order = 1)
Parameters
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
gradient(NDArray, object[], NDAxis?, int)
N per-axis spacings passed explicitly (each a scalar or a 1-D coordinate array). Also the
form for a tuple axis with no spacing: pass an empty array.
public static np.GradientResult gradient(NDArray f, object[] varargs, NDAxis? axis = null, int edge_order = 1)
Parameters
Returns
Exceptions
- ArgumentNullException
fisnull.- AxisError
An
axisis outside[-f.ndim, f.ndim-1].- ValueError
A repeated
axis;edge_order> 2; an axis is shorter thanedge_order + 1; or a 1-D coordinate spacing whose length or rank does not match its axis ("distances must be either scalars or 1d" / "… must match the length …"); a ragged list spacing (np.ndim's "setting an array element with a sequence. …").- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of their empty differences).- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
The number of positional spacings equals neither 0, 1, nor the number of requested axes ("invalid number of arguments").
- TypeError
fis boolean and a statement subtracts it: a scalar step (the interior) or first-order edges (NumPy's boolean-subtract TypeError). A bool input keeps its dtype and gets float64 components, so with coordinates andedge_order = 2it has a gradient, as in NumPy.- TypeError
A str or None step (Python's own
2. * ax_dxrefuses it: "can't multiply sequence by non-int of type 'float'" / "unsupported operand type(s) for *: 'float' and 'NoneType'").- ZeroDivisionError
A zero step that is a Python number (a C# int, double, bool or Complex) with second-order edges: CPython's ZeroDivisionError of
-1.5 / ax_dx. A NumPy scalar or 0-d array zero step gives inf / nan, as in NumPy.- DivideByZeroException
A decimal input or step divided by zero (.NET's own: decimal has no inf).
- OverflowError
A
BigIntegerstep past the float range (CPython's "int too large to convert to float").- OverflowException
A decimal result past decimal's range.
greater(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 > x2) element-wise.
Mirrors NumPy's ufunc signature: greater(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the > operator for the typed wrapper).
public static NDArray greater(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).
greater(NDArray, object)
Return (x1 > x2) element-wise with scalar.
public static NDArray<bool> greater(NDArray x1, object x2)
Parameters
Returns
greater(object, NDArray)
Return (x1 > x2) element-wise with scalar on left.
public static NDArray<bool> greater(object x1, NDArray x2)
Parameters
Returns
greater_equal(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 >= x2) element-wise.
Mirrors NumPy's ufunc signature: greater_equal(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the >= operator for the typed wrapper).
public static NDArray greater_equal(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).
greater_equal(NDArray, object)
Return (x1 >= x2) element-wise with scalar.
public static NDArray<bool> greater_equal(NDArray x1, object x2)
Parameters
Returns
greater_equal(object, NDArray)
Return (x1 >= x2) element-wise with scalar on left.
public static NDArray<bool> greater_equal(object x1, NDArray x2)
Parameters
Returns
hamming(double)
Return the Hamming window — a taper formed by a weighted cosine (raised-cosine, 0.54/0.46).
public static NDArray hamming(double M)
Parameters
MdoubleNumber of points in the output window. If zero or less, an empty array is returned.
Returns
- NDArray
The window, maximum normalized to one (the value one appears only when
Mis odd).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.hamming.html
NumPy: 0.54 + 0.46*cos(pi*n/(M-1)) with n = arange(1-M, M, 2); the statements are
Hamming(double), called on the default engine.
Exceptions
- ValueError
Mis NaN, +infinity or too large for arange to size.- OutOfMemoryException
A finite count whose window does not fit in memory.
hanning(double)
Return the Hanning window — a taper formed by a weighted cosine (raised-cosine, 0.5/0.5).
public static NDArray hanning(double M)
Parameters
MdoubleNumber of points in the output window. If zero or less, an empty array is returned.
Returns
- NDArray
The window, maximum normalized to one (the value one appears only when
Mis odd).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.hanning.html
NumPy: 0.5 + 0.5*cos(pi*n/(M-1)) with n = arange(1-M, M, 2); the statements are
Hanning(double), called on the default engine.
Exceptions
- ValueError
Mis NaN, +infinity or too large for arange to size.- OutOfMemoryException
A finite count whose window does not fit in memory.
heaviside(NDArray, NDArray, NDArray, NDArray, DType)
Compute the Heaviside step function, element-wise.
heaviside(x1, x2) is 0 where x1 < 0, 1 where x1 > 0,
and x2 exactly where x1 == 0 (so x2 — often 0.5 — is the value AT
the step). A NaN in x1 yields NaN. x1 and x2 broadcast to a common shape.
Mirrors NumPy's ufunc signature: heaviside(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray heaviside(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput values; the sign of each element selects the branch (negative → 0, positive → 1, zero →
x2, NaN → NaN).x2NDArrayThe value of the function where
x1is 0. If shapes differ they must broadcast to a common shape. NOT interchangeable withx1— heaviside is not commutative.outNDArrayA location into which the result is stored (joins the broadcast without being stretched, same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only; int/bool/complex raise NumPy's "No loop matching" error, since heaviside has only the ee/ff/dd/gg loops — an integer/bool INPUT is cast to its float tier exactly as arctan2 does).
Returns
- NDArray
The element-wise Heaviside step function of
x1. A scalar if bothx1andx2are scalars.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.heaviside.html
Bit-identical to NumPy 2.4.2 for every dtype: the step is a port of npy_heaviside. Two
NaN behaviours are load-bearing — a NaN x1 gives the POSITIVE canonical NaN
(its own sign discarded), while the x1 == 0 case returns x2's EXACT
bits (a NaN or -0.0 x2 keeps its sign). Faster than NumPy (which has
no SIMD heaviside on any platform): the contiguous / scalar-broadcast float32/float64 cases run
a branchless vector kernel. See NDHeavisideMath.
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.).
histogram(NDArray, NDArray, (double, double)?, bool?, NDArray)
Compute the histogram over explicit, possibly non-uniform, monotonically-increasing bin edges.
public static np.HistogramResult histogram(NDArray a, NDArray bins, (double, double)? range = null, bool? density = null, NDArray weights = null)
Parameters
aNDArrayInput data; the histogram is computed over the flattened array.
binsNDArrayThe explicit bin edges (must increase monotonically).
range(double, double)?Ignored when explicit edges are given (accepted for signature parity).
densitybool?When true, return the probability density instead of raw counts.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional per-sample weights (same shape as
a).
Returns
- np.HistogramResult
A np.HistogramResult carrying the histogram values and the bin edges.
Remarks
Scoped ([NDScoped]; np.HistogramResult is an INDArrayCarrier): the raveled input and weights, the per-sample bin indices, the bincount/cumulative scratch and the density quotients are reclaimed; only the histogram and its edges leave.
Exceptions
- ValueError
The edges are not 1-D or not monotonically increasing.
- TypeError
Bool
weightsover data: NumPy's UFuncTypeErrorCannot cast ufunc 'add' output from dtype('int64') to dtype('bool') with casting rule 'same_kind'(NumPy adds the weights' int64 cumulative sum into a bool total in place).- ArgumentNullException
ais null.
histogram(NDArray, double[], (double, double)?, bool?, NDArray)
Convenience overload accepting explicit edges as a C# double[].
public static np.HistogramResult histogram(NDArray a, double[] bins, (double, double)? range = null, bool? density = null, NDArray weights = null)
Parameters
aNDArrayInput data.
binsdouble[]The explicit bin edges.
range(double, double)?Ignored when explicit edges are given.
densitybool?When true, return the probability density instead of raw counts.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional per-sample weights.
Returns
- np.HistogramResult
A np.HistogramResult carrying the histogram values and the bin edges.
Remarks
Scoped ([NDScoped]; np.HistogramResult is an INDArrayCarrier): the raveled input and weights, the per-sample bin indices, the bincount/cumulative scratch and the density quotients are reclaimed; only the histogram and its edges leave.
Exceptions
- ValueError
The edges are not monotonically increasing.
- TypeError
Bool
weightsover data: NumPy's UFuncTypeErrorCannot cast ufunc 'add' output from dtype('int64') to dtype('bool') with casting rule 'same_kind'(NumPy adds the weights' int64 cumulative sum into a bool total in place).- ArgumentNullException
ais null.
histogram(NDArray, int, (double, double)?, bool?, NDArray)
Compute the histogram of a dataset over bins equal-width bins.
All bins are half-open [l, r) except the last, which is closed [l, r];
samples outside the range are ignored.
public static np.HistogramResult histogram(NDArray a, int bins = 10, (double, double)? range = null, bool? density = null, NDArray weights = null)
Parameters
aNDArrayInput data; the histogram is computed over the flattened array.
binsintNumber of equal-width bins (default 10).
range(double, double)?Optional
(lower, upper)outer edges; defaults to(a.min(), a.max()).densitybool?When true, return the probability density (
count / total / bin_width) whose integral over the range is 1, instead of raw counts.null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional per-sample weights of the same shape as
a; each sample then contributes its weight instead of 1, andhist.dtypefollowsweights.
Returns
- np.HistogramResult
A np.HistogramResult carrying the histogram values and the bin edges.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
<p>Scoped (<code>[NDScoped]</code>; <xref href="NumSharp.np.HistogramResult" data-throw-if-not-resolved="false"></xref> is an <xref href="NumSharp.INDArrayCarrier" data-throw-if-not-resolved="false"></xref>): the raveled input and weights, the per-sample bin indices, the bincount/cumulative scratch and the density quotients are reclaimed; only the histogram and its edges leave.</p>
Exceptions
- ValueError
bins< 1, or the range is invalid/non-finite.- ArgumentNullException
ais null.
histogram(NDArray, string, (double, double)?, bool?, NDArray)
Compute the histogram using an automatic bin-count estimator (see histogram_bin_edges(NDArray, string, (double, double)?, NDArray) for the names).
public static np.HistogramResult histogram(NDArray a, string bins, (double, double)? range = null, bool? density = null, NDArray weights = null)
Parameters
aNDArrayInput data; the histogram is computed over the flattened array.
binsstringThe estimator name.
range(double, double)?Optional
(lower, upper)outer edges; also constrains the data the estimator sees.densitybool?When true, return the probability density instead of raw counts.
null(NumPy'sNone, the default) isfalse.weightsNDArrayWeighted data is not supported for automatic estimation.
Returns
- np.HistogramResult
A np.HistogramResult carrying the histogram values and the bin edges.
Remarks
Scoped ([NDScoped]; np.HistogramResult is an INDArrayCarrier): the raveled input and weights, the per-sample bin indices, the bincount/cumulative scratch and the density quotients are reclaimed; only the histogram and its edges leave.
Exceptions
- TypeError
weightsis supplied together with an estimator name.- ArgumentNullException
ais null.
histogram2d(NDArray, NDArray, NDArray, (double, double)?[], bool?, NDArray)
2-D histogram with a single edge array shared by both dimensions (x_edges = y_edges = bins).
public static np.Histogram2dResult histogram2d(NDArray x, NDArray y, NDArray bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
xNDArrayThe x coordinates, shape
(N,).yNDArrayThe y coordinates, shape
(N,).binsNDArrayShared bin edges for both dimensions (must have more than 2 entries — a 2-entry array is read as
[nx, ny]).range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.Histogram2dResult
A np.Histogram2dResult carrying
H, the x edges and the y edges.
Remarks
Scoped ([NDScoped]; np.Histogram2dResult is an INDArrayCarrier): the shared-edge conversions, the promoted coordinate columns and every per-dimension binning intermediate are reclaimed; only H and the two edge arrays leave.
Exceptions
- ArgumentNullException
xis null.
histogram2d(NDArray, NDArray, NDArray[], (double, double)?[], bool?, NDArray)
2-D histogram with explicit per-dimension edge arrays [x_edges, y_edges] (or a mixed [int, array]).
public static np.Histogram2dResult histogram2d(NDArray x, NDArray y, NDArray[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
xNDArrayThe x coordinates, shape
(N,).yNDArrayThe y coordinates, shape
(N,).binsNDArray[]Per-dimension edge arrays.
range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.Histogram2dResult
A np.Histogram2dResult carrying
H, the x edges and the y edges.
Remarks
Scoped ([NDScoped]; np.Histogram2dResult is an INDArrayCarrier): the shared-edge conversions, the promoted coordinate columns and every per-dimension binning intermediate are reclaimed; only H and the two edge arrays leave.
Exceptions
- ArgumentNullException
xis null.
histogram2d(NDArray, NDArray, double[], (double, double)?[], bool?, NDArray)
2-D histogram with a single edge array (C# double[]) shared by both dimensions.
public static np.Histogram2dResult histogram2d(NDArray x, NDArray y, double[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
xNDArrayThe x coordinates, shape
(N,).yNDArrayThe y coordinates, shape
(N,).binsdouble[]Shared bin edges (more than 2 entries).
range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.Histogram2dResult
A np.Histogram2dResult carrying
H, the x edges and the y edges.
Remarks
Scoped ([NDScoped]; np.Histogram2dResult is an INDArrayCarrier): the shared-edge conversions, the promoted coordinate columns and every per-dimension binning intermediate are reclaimed; only H and the two edge arrays leave.
Exceptions
- ArgumentNullException
xis null.
histogram2d(NDArray, NDArray, int, (double, double)?[], bool?, NDArray)
Compute the 2-D histogram of two data samples with bins equal-width bins along
each dimension. Note NumPy's convention: x is histogrammed along the first
(row) axis and y along the second (column) axis.
public static np.Histogram2dResult histogram2d(NDArray x, NDArray y, int bins = 10, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
xNDArrayThe x coordinates, shape
(N,).yNDArrayThe y coordinates, shape
(N,).binsintNumber of equal-width bins along both dimensions (default 10).
range(double, double)?[]Optional per-dimension
(lower, upper)outer edges ([[xmin,xmax],[ymin,ymax]]).densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.Histogram2dResult
A np.Histogram2dResult carrying
H, the x edges and the y edges.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html
<p>Scoped (<code>[NDScoped]</code>; <xref href="NumSharp.np.Histogram2dResult" data-throw-if-not-resolved="false"></xref> is an <xref href="NumSharp.INDArrayCarrier" data-throw-if-not-resolved="false"></xref>): the shared-edge conversions, the promoted coordinate columns and every per-dimension binning intermediate are reclaimed; only <code>H</code> and the two edge arrays leave.</p>
Exceptions
- ArgumentNullException
xis null.
histogram2d(NDArray, NDArray, int[], (double, double)?[], bool?, NDArray)
2-D histogram with a per-dimension bin count [nx, ny].
public static np.Histogram2dResult histogram2d(NDArray x, NDArray y, int[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
xNDArrayThe x coordinates, shape
(N,).yNDArrayThe y coordinates, shape
(N,).binsint[]Per-dimension bin counts
[nx, ny].range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.Histogram2dResult
A np.Histogram2dResult carrying
H, the x edges and the y edges.
Remarks
Scoped ([NDScoped]; np.Histogram2dResult is an INDArrayCarrier): the shared-edge conversions, the promoted coordinate columns and every per-dimension binning intermediate are reclaimed; only H and the two edge arrays leave.
Exceptions
- ArgumentNullException
xis null.
histogram2d(NDArray, NDArray, object[], (double, double)?[], bool?, NDArray)
2-D histogram with a mixed per-dimension bin spec [nx, y_edges] or [x_edges, ny].
public static np.Histogram2dResult histogram2d(NDArray x, NDArray y, object[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
xNDArrayThe x coordinates, shape
(N,).yNDArrayThe y coordinates, shape
(N,).binsobject[]Per-dimension spec, each entry an int count or an edge array.
range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.Histogram2dResult
A np.Histogram2dResult carrying
H, the x edges and the y edges.
Remarks
Scoped ([NDScoped]; np.Histogram2dResult is an INDArrayCarrier): the shared-edge conversions, the promoted coordinate columns and every per-dimension binning intermediate are reclaimed; only H and the two edge arrays leave.
Exceptions
- ArgumentNullException
xis null.
histogram_bin_edges(NDArray, NDArray, (double, double)?, NDArray)
Pass a pre-computed, monotonically-increasing edge array through unmodified (after a monotonicity check) — the identity form that lets histogram/histogram_bin_edges accept explicit non-uniform edges.
public static NDArray histogram_bin_edges(NDArray a, NDArray bins, (double, double)? range = null, NDArray weights = null)
Parameters
aNDArrayInput data (only its dtype/emptiness matters here).
binsNDArrayThe explicit bin edges (must increase monotonically; dtype preserved).
range(double, double)?Ignored when explicit edges are given (accepted for signature parity).
weightsNDArrayIgnored for edge computation.
Returns
- NDArray
The edges array (dtype preserved).
Remarks
Scoped ([NDScoped]): the raveled input, any weights ravel and every estimator/linspace intermediate are reclaimed; only the edge array leaves (an explicit edge array the caller passed through unchanged stays the caller's).
Exceptions
- ValueError
The edges are not 1-D or not monotonically increasing.
- ArgumentNullException
ais null.
histogram_bin_edges(NDArray, double[], (double, double)?, NDArray)
Convenience overload accepting explicit edges as a C# double[] — equivalent to
histogram_bin_edges(NDArray, NDArray, (double, double)?, NDArray) with
np.array(bins).
public static NDArray histogram_bin_edges(NDArray a, double[] bins, (double, double)? range = null, NDArray weights = null)
Parameters
aNDArrayInput data.
binsdouble[]The explicit bin edges.
range(double, double)?Ignored when explicit edges are given.
weightsNDArrayIgnored for edge computation.
Returns
- NDArray
The edges array (float64).
Remarks
Scoped ([NDScoped]): the raveled input, any weights ravel and every estimator/linspace intermediate are reclaimed; only the edge array leaves (an explicit edge array the caller passed through unchanged stays the caller's).
Exceptions
- ArgumentNullException
ais null.
histogram_bin_edges(NDArray, int, (double, double)?, NDArray)
Compute only the bin edges histogram(NDArray,int,ValueTuple<double,double>?,bool,NDArray)
would use, so one set of edges can be shared across several histograms. With an integer
bins the edges are equal-width across the range.
public static NDArray histogram_bin_edges(NDArray a, int bins = 10, (double, double)? range = null, NDArray weights = null)
Parameters
aNDArrayInput data; the histogram is computed over the flattened array.
binsintNumber of equal-width bins (default 10).
range(double, double)?Optional
(lower, upper)outer edges; defaults to(a.min(), a.max()).weightsNDArrayUnused for edge computation (accepted for signature parity, only shape-checked).
Returns
- NDArray
The bin edges (length
bins+ 1), dtype float (or the input's float width).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.histogram_bin_edges.html
<p>Scoped (<code>[NDScoped]</code>): the raveled input, any weights ravel and every estimator/linspace intermediate are reclaimed; only the edge array leaves (an explicit edge array the caller passed through unchanged stays the caller's).</p>
Exceptions
- ValueError
bins< 1, or the range is invalid/non-finite.- ArgumentNullException
ais null.
histogram_bin_edges(NDArray, string, (double, double)?, NDArray)
Compute the bin edges chosen by an automatic estimator ("auto", "fd",
"doane", "scott", "stone", "rice", "sturges", "sqrt").
The bin width is optimal for the data within the range while the bin count fills the whole range.
public static NDArray histogram_bin_edges(NDArray a, string bins, (double, double)? range = null, NDArray weights = null)
Parameters
aNDArrayInput data; the histogram is computed over the flattened array.
binsstringThe estimator name.
range(double, double)?Optional
(lower, upper)outer edges; also constrains the data the estimator sees.weightsNDArrayWeighted data is not supported for automatic estimation.
Returns
- NDArray
The estimator-chosen bin edges.
Remarks
Scoped ([NDScoped]): the raveled input, any weights ravel and every estimator/linspace intermediate are reclaimed; only the edge array leaves (an explicit edge array the caller passed through unchanged stays the caller's).
Exceptions
- ValueError
binsis not a known estimator, or the range is invalid.- TypeError
weightsis supplied (unsupported for estimators).- ArgumentNullException
ais null.
histogramdd(NDArray, NDArray[], (double, double)?[], bool?, NDArray)
Compute the D-dimensional histogram with explicit per-dimension bin edges.
public static np.HistogramddResult histogramdd(NDArray sample, NDArray[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
sampleNDArrayAn
(N, D)array of N points in D-dimensional space.binsNDArray[]Per-dimension edge arrays (length must equal D; a 0-d entry is read as a bin count).
range(double, double)?[]Optional per-dimension outer edges (used only where
binsgives a count).densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.HistogramddResult
A np.HistogramddResult carrying
Hand the per-dimension edges.
Remarks
Scoped ([NDScoped]; np.HistogramddResult is an INDArrayCarrier): the sample column views, the promoted columns, the per-dimension bin indices, the raveled multi-index and the density quotients are reclaimed; only H and the edge arrays leave.
Exceptions
- ArgumentNullException
sampleis null.
histogramdd(NDArray, int, (double, double)?[], bool?, NDArray)
Compute the D-dimensional histogram of sample with the same integer bin count
along every dimension. Each row of sample is one D-dimensional coordinate.
public static np.HistogramddResult histogramdd(NDArray sample, int bins = 10, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
sampleNDArrayAn
(N, D)array of N points in D-dimensional space.binsintNumber of equal-width bins along every dimension (default 10).
range(double, double)?[]Optional per-dimension
(lower, upper)outer edges; a null entry auto-detects that dim.densitybool?When true, return the probability density (
count / total / bin_volume).null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.HistogramddResult
A np.HistogramddResult carrying
Hand the per-dimension edges.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.histogramdd.html
<p>Scoped (<code>[NDScoped]</code>; <xref href="NumSharp.np.HistogramddResult" data-throw-if-not-resolved="false"></xref> is an <xref href="NumSharp.INDArrayCarrier" data-throw-if-not-resolved="false"></xref>): the sample column views, the promoted columns, the per-dimension bin indices, the raveled multi-index and the density quotients are reclaimed; only <code>H</code> and the edge arrays leave.</p>
Exceptions
- ArgumentNullException
sampleis null.
histogramdd(NDArray, int[], (double, double)?[], bool?, NDArray)
Compute the D-dimensional histogram with a per-dimension bin count.
public static np.HistogramddResult histogramdd(NDArray sample, int[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
sampleNDArrayAn
(N, D)array of N points in D-dimensional space.binsint[]Per-dimension bin counts (length must equal D).
range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.HistogramddResult
A np.HistogramddResult carrying
Hand the per-dimension edges.
Remarks
Scoped ([NDScoped]; np.HistogramddResult is an INDArrayCarrier): the sample column views, the promoted columns, the per-dimension bin indices, the raveled multi-index and the density quotients are reclaimed; only H and the edge arrays leave.
Exceptions
- ArgumentNullException
sampleis null.
histogramdd(NDArray, object[], (double, double)?[], bool?, NDArray)
Compute the D-dimensional histogram with a mixed per-dimension bin spec (each entry an int count or an edge array).
public static np.HistogramddResult histogramdd(NDArray sample, object[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
sampleNDArrayAn
(N, D)array of N points in D-dimensional space.binsobject[]Per-dimension spec: each entry an int count, an NDArray /
double[]edge array.range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.HistogramddResult
A np.HistogramddResult carrying
Hand the per-dimension edges.
Remarks
Scoped ([NDScoped]; np.HistogramddResult is an INDArrayCarrier): the sample column views, the promoted columns, the per-dimension bin indices, the raveled multi-index and the density quotients are reclaimed; only H and the edge arrays leave.
Exceptions
- ArgumentNullException
sampleis null.
histogramdd(NDArray[], NDArray[], (double, double)?[], bool?, NDArray)
Sequence-of-columns form with explicit per-dimension edge arrays.
public static np.HistogramddResult histogramdd(NDArray[] sample, NDArray[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
sampleNDArray[]D coordinate arrays, each of length N.
binsNDArray[]Per-dimension edge arrays.
range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.HistogramddResult
A np.HistogramddResult carrying
Hand the per-dimension edges.
Remarks
Scoped ([NDScoped]; np.HistogramddResult is an INDArrayCarrier): the sample column views, the promoted columns, the per-dimension bin indices, the raveled multi-index and the density quotients are reclaimed; only H and the edge arrays leave.
histogramdd(NDArray[], int, (double, double)?[], bool?, NDArray)
Compute the D-dimensional histogram from a sequence of D coordinate arrays (each element is the
list of values for one coordinate — NumPy's histogramdd((X, Y, Z)) form).
public static np.HistogramddResult histogramdd(NDArray[] sample, int bins = 10, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
sampleNDArray[]D coordinate arrays, each of length N.
binsintNumber of equal-width bins along every dimension (default 10).
range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.HistogramddResult
A np.HistogramddResult carrying
Hand the per-dimension edges.
Remarks
Scoped ([NDScoped]; np.HistogramddResult is an INDArrayCarrier): the sample column views, the promoted columns, the per-dimension bin indices, the raveled multi-index and the density quotients are reclaimed; only H and the edge arrays leave.
histogramdd(NDArray[], int[], (double, double)?[], bool?, NDArray)
Sequence-of-columns form with a per-dimension bin count.
public static np.HistogramddResult histogramdd(NDArray[] sample, int[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
sampleNDArray[]D coordinate arrays, each of length N.
binsint[]Per-dimension bin counts (length must equal D).
range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.HistogramddResult
A np.HistogramddResult carrying
Hand the per-dimension edges.
Remarks
Scoped ([NDScoped]; np.HistogramddResult is an INDArrayCarrier): the sample column views, the promoted columns, the per-dimension bin indices, the raveled multi-index and the density quotients are reclaimed; only H and the edge arrays leave.
histogramdd(NDArray[], object[], (double, double)?[], bool?, NDArray)
Sequence-of-columns form with a mixed per-dimension bin spec.
public static np.HistogramddResult histogramdd(NDArray[] sample, object[] bins, (double, double)?[] range = null, bool? density = null, NDArray weights = null)
Parameters
sampleNDArray[]D coordinate arrays, each of length N.
binsobject[]Per-dimension spec: each entry an int count or an edge array.
range(double, double)?[]Optional per-dimension outer edges.
densitybool?When true, return the probability density.
null(NumPy'sNone, the default) isfalse.weightsNDArrayOptional
(N,)per-point weights.
Returns
- np.HistogramddResult
A np.HistogramddResult carrying
Hand the per-dimension edges.
Remarks
Scoped ([NDScoped]; np.HistogramddResult is an INDArrayCarrier): the sample column views, the promoted columns, the per-dimension bin indices, the raveled multi-index and the density quotients are reclaimed; only H and the edge arrays leave.
hsplit(NDArray, int)
Split an array into multiple sub-arrays horizontally (column-wise).
public static NDArray[] hsplit(NDArray ary, int indices_or_sections)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintIf an integer, N, the array will be divided into N equal arrays along the axis. If such a split is not possible, an error is raised.
Returns
- NDArray[]
A list of sub-arrays as views into ary. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
For 1-D arrays, splits along axis 0. For 2-D+ arrays, splits along axis 1 (columns). https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html
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.).- ArgumentException
aryis 0-d ("hsplit only works on arrays of 1 or more dimensions"; NumPy raises the text as a ValueError).- ValueError
The sections are not positive ("number sections must be larger than 0."), or do not divide the axis ("array split does not result in an equal division").
- NullReferenceException
aryis null (its rank is read first).
hsplit(NDArray, int[])
Split an array into multiple sub-arrays horizontally (column-wise).
public static NDArray[] hsplit(NDArray ary, int[] indices)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indicesint[]A 1-D array of sorted integers indicating where along the axis the array is split. For example, [2, 3] would result in ary[:2], ary[2:3], ary[3:].
Returns
- NDArray[]
A list of sub-arrays as views into ary. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
For 1-D arrays, splits along axis 0. For 2-D+ arrays, splits along axis 1 (columns). https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html
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.).- ArgumentException
aryis 0-d ("hsplit only works on arrays of 1 or more dimensions"; NumPy raises the text as a ValueError).- ArgumentNullException
indicesis null (checked after the rank).- NullReferenceException
aryis null (its rank is read first).
hstack(params NDArray[])
Stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.Rebuilds arrays divided by hsplit. This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.
public static NDArray hstack(params NDArray[] tup)
Parameters
tupNDArray[]The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.
Returns
- NDArray
The array formed by stacking the given arrays. A
numpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
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.).- ArgumentNullException
tupis null.- ValueError
tupis empty ("need at least one array to concatenate").
hstack(NDArray[], DType, string)
NumPy's hstack(tup, *, dtype=None, casting='same_kind'): stack the arrays in sequence horizontally,
with np.concatenate's dtype / casting - along the first axis for 1-D arrays, the second
otherwise.
public static NDArray hstack(NDArray[] tup, DType dtype = null, string casting = "same_kind")
Parameters
tupNDArray[]The arrays (NumPy's sequence): the same shape along all but the second axis, except 1-D arrays, which can be any length.
dtypeDTypeThe result dtype handed to np.concatenate, or null for the arrays' promoted dtype.
castingstringThe casting rule handed to np.concatenate (
'no','equiv','safe','same_kind'or'unsafe').
Returns
- NDArray
The array formed by stacking the given arrays (a
numpy.matrixoperand gives a matrix, NumPy's subtype rule; a chararray a plain array).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.hstack.html
<p>NumPy's keywords beside NumSharp's <code>params</code> form, which the owner kept (API-parity batch 3): C#
allows nothing after a <code>params</code> array, so <code>np.hstack(a, b)</code> stays and <code>np.hstack(new[] { a, b },
dtype: np.float32)</code> (C# 12: <code>np.hstack([a, b], dtype: np.float32)</code>) binds here. A plain array argument
with no keyword binds here too (C# prefers the overload with more declared parameters); both answer
alike.</p>
Exceptions
- ArgumentNullException
tupis null.- ValueError
tupis empty ("need at least one array to concatenate"); anumpy.matrixresult of more than two long axes.- InvalidCastException
An array that does not cast to
dtypeundercasting(np.concatenate's refusal with NumPy's text; NumPy's type is TypeError, pinned inOpenBugs.ApiParity.cs).
hypot(NDArray, NDArray, NDArray, NDArray, DType)
Given the "legs" of a right triangle, return its hypotenuse.
Computes sqrt(x12 + x22), element-wise, without the intermediate overflow or
underflow a naive square-and-add would suffer (so hypot(1e200, 1e200) is
1.41e200, not inf). Both scalars and arrays are accepted; if their shapes
differ they must broadcast to a common shape.
Mirrors NumPy's ufunc signature: hypot(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray hypot(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayLeg of the triangle(s).
x2NDArrayLeg of the triangle(s). If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only; int/bool/complex raise NumPy's "No loop matching" error).
Returns
- NDArray
The hypotenuse of the triangle(s). This is a scalar if both x1 and x2 are scalars.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.hypot.html
float32/float16 results are bit-identical to NumPy; float64 is correctly-rounded, so it
matches NumPy on ~91% of inputs and is within 1 ULP (more accurate) on the rest — NumPy
calls the platform (UCRT) hypot, which is only faithfully-rounded. See
NDHypotMath.
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.).
i0(NDArray)
Modified Bessel function of the first kind, order 0 (I₀), evaluated element-wise —
the taper behind kaiser(double, double), exposed as NumPy's np.i0.
public static NDArray i0(NDArray x)
Parameters
xNDArrayArgument array. The float precision is PRESERVED and the whole cephes routine runs at that precision (float16→float16, float32→float32, float64→float64), matching NumPy's NEP50 weak-scalar promotion; bool / every integer width / Char promote to float64; Decimal is preserved via the double bridge (a NumSharp extension — NumPy has no decimal); Complex is refused (NumPy raises the same
TypeError).
Returns
- NDArray
A fresh array of
x's shape holding I₀ at each element. The dtype is the input float dtype (float64 for bool/int/Char inputs, Decimal for a Decimal input).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.i0.html
Unlike a ufunc, i0 has NO out/where/dtype parameters — the
signature is exactly i0(x). |x| ≥ ~710 (float64) overflows exp to +∞ and
non-finite inputs propagate NaN/∞ exactly as NumPy's chain does.
Bit-identical to NumPy 2.4.2 for every float64/float32/float16 input (the shared cephes recurrence is IEEE-exact per op at each width, and exp is NumPy's own kernel per width). A Decimal input whose magnitude overflows the double→decimal bridge (I₀ exceeds MaxValue at |x| ≳ 72) throws OverflowException, exactly as the other decimal transcendentals do.
Exceptions
- ArgumentNullException
xis null.- IncorrectTypeException
xis Complex — I₀ has no complex loop (NumPy'sTypeError("i0 not supported for complex values")).- OverflowException
xis Decimal and I₀ overflows the decimal range (double→decimal bridge limit).- ValueError
xis text and an element does not parse as a float (NumPy'sx.astype(float):could not convert string to float: np.str_('x')).
identity(int, DType)
Return the identity array. The identity array is a square array with ones on the main diagonal.
public static NDArray identity(int n, DType dtype = null)
Parameters
nintNumber of rows (and columns) in n x n output.
dtypeDTypeData-type of the output. Defaults to double.
Returns
- NDArray
n x n array with its main diagonal set to one, and all other elements 0.
Remarks
iinfo(DType)
Machine limits for integer types.
public static iinfo iinfo(DType int_type)
Parameters
int_typeDTypeThe integer dtype — one descriptor parameter under NumPy's keyword name: a C# Type (
typeof(int)), an NPTypeCode or a DType (np.int32,arr.dtype) convert implicitly; a string binds iinfo(string), which reads it as NumPy does.
Returns
- iinfo
An iinfo object describing the integer type limits.
Examples
var info = np.iinfo(np.int32);
Console.WriteLine(info.bits); // 32
Console.WriteLine(info.min); // -2147483648
Console.WriteLine(info.max); // 2147483647
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.iinfo.html
An ARRAY is not a dtype: NumPy's np.iinfo(arr) reads its type (ndarray, an object dtype) and
raises Invalid integer data type 'O'.; NumSharp has no array overload since API-parity batch 7, so pass
arr.dtype.
Exceptions
- ArgumentNullException
int_typeis null.- ValueError
Not an integer dtype: NumPy's
Invalid integer data type 'f'.(the kind character).
iinfo(NDScalarType)
Machine limits of an integer scalar CLASS — NumPy's np.iinfo(cls): a concrete class gives its dtype's
limits (np.iinfo((NDScalarType)np.int16) is np.iinfo(np.int16)), and a Python built-in class
the limits of the NumPy class NumPy reads it as (np.iinfo(NDScalarType.PyInt) is int64's on a 64-bit
host).
public static iinfo iinfo(NDScalarType int_type)
Parameters
int_typeNDScalarTypeThe scalar class (NumPy's keyword name).
Returns
- iinfo
The limits.
Exceptions
- ArgumentNullException
int_typeis null.- ValueError
The class's kind is not
'i'or'u'— NumPy's text, which names the kind ofnp.dtype(cls):Invalid integer data type 'f'.,'b'for bool,'m'for timedelta64,'c'for complex64,'O'for object_. An abstract class is'O': NumPy'siinforetries a value that converts to no dtype with the dtype of its TYPE, and the type of a class is Python'stype, an object dtype.
iinfo(string)
Machine limits of the integer dtype a STRING names — NumPy's np.iinfo("int32"), read as NumPy reads it:
numeric.dtype(int_type), and when that raises TypeError (the string names no dtype) the dtype of the
value's TYPE, str — so np.iinfo("foo") and np.iinfo("") are the str kind's
Invalid integer data type 'U'., exactly NumPy's answers.
public static iinfo iinfo(string int_type)
Parameters
int_typestringA dtype string (
"int32","i8","uint8"); null is NumPy's None, whichnp.dtypereads as the default float64 (so NumPy'sInvalid integer data type 'f'.).
Returns
- iinfo
An iinfo object describing the integer type limits.
Examples
var info = np.iinfo("int32");
Console.WriteLine(info.bits); // 32
Remarks
Before API-parity batch 7 the parameter was named dtypeName (NumPy's keyword is
int_type), a null or empty string raised NumSharp's own ArgumentException, and an unknown name
surfaced dtype(string)'s TypeError.
Exceptions
- ValueError
The string names a non-integer dtype (
"float32":'f') or no dtype at all ('U'), or is null ('f') — NumPy's texts.- NotSupportedException
The string names a NumPy dtype NumSharp does not model (
"O","V"): dtype(string)'s refusal, where NumPy would answer'O'/'V'.
imag(NDArray)
Return the imaginary part of the complex argument, element-wise.
One of the four basic complex-number accessors (with real(NDArray), angle(NDArray, bool)
and conjugate(NDArray, NDArray, NDArray, DType)) — the standard post-FFT spectrum component extractors: for
A = np.fft.fft(a), A.imag / np.imag(A) is the imaginary component.
public static NDArray imag(NDArray val)
Parameters
valNDArrayInput array.
Returns
- NDArray
For a COMPLEX input: a float64 VIEW onto the imaginary lane — it SHARES memory with
valand is writeable, sonp.imag(z)[i] = xwrites through toz[i]'s imaginary part (reproducing NumPy'sz.imag; complex128 -> float64). For a REAL / integer / boolean input: a fresh, READ-ONLY all-zeros array of the same shape and dtype (the imaginary part of a real number is zero), matching NumPy exactly.
Remarks
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.).
indices(Shape, DType, bool)
Return the indices of a grid — NumPy's np.indices(dimensions, dtype=int, sparse=False): the dense grid
of shape (len(dimensions), *dimensions) whose d-th sub-array holds the d-th coordinate
of each position, or with sparse one broadcast-shaped array per axis, axis d's of
shape (1, …, 1, dimensions[d], 1, …, 1).
public static np.IndicesResult indices(Shape dimensions, DType dtype = null, bool sparse = false)
Parameters
dimensionsShapeThe shape of the grid: a tuple (
(2, 3)), anint[]/long[](an array'sshape), a C# collection expression or a Shape, all converting implicitly. Only the dimension SIZES are read — any strides / offset a Shape carries are ignored. A 0-dimensional shape yields NumPy's(0,)dense result, or an empty sparse tuple.dtypeDTypeElement type of the result — any dtype spelling (Type, NPTypeCode, dtype string or DType) converts implicitly. Default (null) is long / int64 (NumPy's
int, the platform's intp).sparseboolNumPy's
sparse: return the per-axis arrays instead of the dense grid (each a VIEW of its arange,flags.owndataFalse as NumPy's reshape result is).
Returns
- np.IndicesResult
An np.IndicesResult: the dense grid (it converts implicitly to NDArray) or the sparse tuple; either deconstructs and indexes per axis.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.indices.html
Because a scalar converts implicitly to a 1-D Shape, np.indices(5) is accepted as the 1-D
grid (1, 5) — a NumSharp convenience (a Shape cannot tell 5 from (5,));
NumPy's np.indices(5) raises (TypeError: 'int' object is not iterable). C# has no 1-element
tuple, so a 1-D grid is np.indices([5]), np.indices(new long[] { 5 }) or np.indices(5).
API-parity batch 11 (the owner's decision 3): NumPy's sparse and the np.IndicesResult
return; the NumSharp-only np.indices_sparse (three overloads) went.
Exceptions
- ValueError
Dense: a dimension is negative (
negative dimensions are not allowed), or the grid's byte count overflows (array is too big; ...) - NumPy's allocation of the result, which comes before any arange. NumPy's sparse grid allocates nothing but its aranges, so a negative dimension is not refused there: its arange is empty and the reshape reads the negative entry as the unknown dimension ((2, -3)gives a(2, 1)and a(1, 0)array).- TypeError
An arange of
dtyperefuses, even for an empty grid: a text dtype (arange() not supported for inputs with DType ...), or bool with a dimension longer than two (arange() is only supported for booleans when the result has at most length 2.).
inner(NDArray, NDArray)
Inner product of two arrays — a sum product over the LAST axis of each.
public static NDArray inner(NDArray a, NDArray b)
Parameters
Returns
- NDArray
Shape
a.shape[:-1] + b.shape[:-1]. A 0-d operand makes this an ordinary multiply, and two 1-D operands give a 0-d scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.inner.html
Unlike dot(NDArray, NDArray, NDArray), which contracts a's last axis against b's
SECOND-TO-last, inner contracts the last axis of both. NumPy implements that by
swapping b's last two axes and handing the pair to the very same dispatcher
np.dot uses (PyArray_MatrixProduct2) — which is why an unaligned
inner reports b's shape ALREADY TRANSPOSED:
np.inner(ones((2,3)), ones((3,2))) raises
"shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)".
Complex operands are NOT conjugated (use vdot(NDArray, NDArray) or vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char) for the conjugating form).
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.).
insert(NDArray, NDArray, NDArray, int?)
NumPy's insert(arr, obj, values, axis=None): values inserted along
axis before the position(s) obj names. Dispatches:
- 0-D integer (what insert(NDArray, long, NDArray, int?) passes for a C# integer) ⇒ the
scalar single-index path, with NumPy's scalar-obj value rule (the values' first axis moved to
axis). - 1-element 1-D integer (
new[] { 1 }) ⇒ the single-index path without that move. - 1-D bool ⇒ flatnonzero(NDArray) ⇒ the multi-index path.
- 1-D integer ⇒ the multi-index path.
- > 1-D ⇒ NumPy's ValueError "index array argument obj to insert must be one dimensional or scalar".
public static NDArray insert(NDArray arr, NDArray obj, NDArray values, int? axis = null)
Parameters
arrNDArrayInput array.
objNDArrayA 0-d or 1-D integer index array (negative from the end,
Nappends), or a 1-D boolean mask of insertion positions; a C#int[]/long[]converts implicitly, and a C# integer binds insert(NDArray, long, NDArray, int?), which calls this form.valuesNDArrayThe values to insert, cast to
arr's dtype and broadcast to the insertion slot; a C# number is NumPy's Python scalar (range-checked:300into int8 is NumPy's OverflowError), a string is parsed by a numeric array, null is Python's None (NaN,nan+nanj,False,'None'or aStringDTypeNA object, converted after the index checks).axisint?The axis to insert along;
nullinserts into the flattened array.
Returns
- NDArray
A fresh array with the values inserted (F-ordered when
arris). Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.insert.html
Scoped by [NDScoped]: the ravel work array, the pre-order intermediate and the bool-mask
flatnonzero temp are released on return; an array passed as values was built before the
scope opened, so it is never disposed.
API-parity batch 13: one of np.insert's forms - the int / int[] / long[] obj forms and every
object values form went (their arguments convert to this one or the long form, which answer alike; a
C# List is passed as np.array(list)).
Exceptions
- ArgumentNullException
arrorobjis null.- ValueError
objis a boolean mask that is not 1-D, or an index array of more than one dimension (NumPy's two texts); text values that do not parse as the array's number type (NumPy converts the values witharray(values, dtype=arr.dtype):could not convert string to float); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- IndexOutOfRangeException
An insertion index is outside
[-N, N].- TypeError
A one-element text or complex
obj('<' not supported between instances of 'str' and 'int'), a textobjof any other size (ufunc 'less' did not contain a loop …), or a one-element float within bounds (slice indices must be integers …); None into an integer array (int()'s TypeError).- IndexError
A float / complex
objof any size but one (arrays used as indices must be of integer (or boolean) type), or a one-element float out of bounds.- OverflowError
A C# number literal outside the array dtype's range (NumPy's OverflowError).
insert(NDArray, Slice, NDArray, int?)
NumPy's insert(arr, obj, values, axis=None) with a slice: values is inserted along
axis before each position obj selects (expanded via Python's
slice.indices(N) into an index array, then the multi-index branch runs).
public static NDArray insert(NDArray arr, Slice obj, NDArray values, int? axis = null)
Parameters
arrNDArrayInput array.
objSliceThe insertion positions, as a slice (
new Slice(1, 3)is NumPy'sslice(1, 3)).valuesNDArrayThe values to insert, cast to
arr's dtype and broadcast to the insertion slots; a C# number, string or array converts implicitly (null is Python's None, converted after the index checks).axisint?The axis to insert along;
nullinserts into the flattened array.
Returns
- NDArray
A fresh array with the values inserted (F-ordered when
arris). Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.insert.html
One of np.insert's forms (API-parity batch 13): a slice has no NDArray form, so it keeps its own; one integer is insert(NDArray, long, NDArray, int?), every other obj NumPy takes the insert(NDArray, NDArray, NDArray, int?) form.
Exceptions
- ArgumentNullException
arrorobjis null.- ValueError
The values do not fit the insertion slots (MapIter's
shape mismatch: ...); text values that do not parse as a numeric array's number type; anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- TypeError
None into an integer array (
int()'s TypeError).- OverflowError
A C# number literal outside the array dtype's range (NumPy's OverflowError).
insert(NDArray, long, NDArray, int?)
NumPy's insert(arr, obj, values, axis=None) with one integer: values inserted along
axis before position obj - NumPy's scalar-obj path for a Python int (the
values' first axis moved to axis).
public static NDArray insert(NDArray arr, long obj, NDArray values, int? axis = null)
Parameters
arrNDArrayInput array.
objlongThe insertion position; negative counts from the end,
Nappends. Every C# integer type binds here.valuesNDArrayThe values to insert, cast to
arr's dtype and broadcast to the insertion slot; a C# number is NumPy's Python scalar (range-checked), a string is parsed by a numeric array, null is Python's None (converted after the index check).axisint?The axis to insert along;
nullinserts into the flattened array.
Returns
- NDArray
A fresh array with the values inserted (F-ordered when
arris). Anumpy.char.chararrayoperand gives a chararray VIEW of a text result; a result of another dtype stays plain.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.insert.html
The one integer form C# needs beside NumPy's two (API-parity batch 13): a C# int converts to both
Slice and NDArray by user-defined conversions, so without it
np.insert(a, 1, 9) would not compile (CS0121). It is the
insert(NDArray, NDArray, NDArray, int?) call with the Python int obj stands
for (NumPy's np.array(obj), a 0-d integer).
Exceptions
- ArgumentNullException
arris null.- IndexOutOfRangeException
objis outside[-N, N].- ValueError
The values do not fit the insertion slot; text values that do not parse as the array's number type; a
numpy.matrixoperand whose result cannot be a matrix.- TypeError
None into an integer array (
int()'s TypeError).- OverflowError
A C# number value outside the array dtype's range (NumPy's OverflowError).
interp(NDArray, NDArray, NDArray, NDArray, NDArray, double?)
One-dimensional linear interpolation for monotonically increasing sample points.
Returns the piecewise-linear interpolant to the discrete data points (xp, fp), evaluated
at each coordinate in x. Port of NumPy's numpy.interp
(compiled_base.c::arr_interp + the _function_base_impl.py wrapper).
public static NDArray interp(NDArray x, NDArray xp, NDArray fp, NDArray left = null, NDArray right = null, double? period = null)
Parameters
xNDArrayThe x-coordinates at which to evaluate the interpolated values (any shape; the result has the same shape).
xpNDArrayThe x-coordinates of the data points — 1-D, must be increasing unless
periodis given.fpNDArrayThe y-coordinates of the data points, same length as xp (float or complex).
leftNDArrayValue returned for
x < xp[0]; null (NumPy's None) meansfp[0]. Any number NumPy'sfloat()takes: a C# double or int (a Python float / int), a Complex for a complexfp(a Python complex), a NumPy scalar, a 0-d array. Ignored whenperiodis given.rightNDArrayValue returned for
x > xp[-1]; null meansfp[-1]. Asleft. Ignored whenperiodis given.perioddouble?A period for the x-coordinates, allowing proper interpolation of angular x-coordinates. Must be non-zero.
Returns
- NDArray
The interpolated values, same shape as x (float64, or complex128 when fp is complex). A scalar (0-d) if x is a scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.interp.html
Check order. NumPy picks the loop from fp alone (np.iscomplexobj(fp)). Without a
period, the compiled loop converts fp, then xp, then x (PyArray_ContiguousFromAny), each by checking the
operand's rank FIRST (fp and xp must be 1-D; x may have any rank) and then its 'safe' cast — so a 2-D text xp is
the rank's ValueError, not the cast's TypeError, and fp's error wins over xp's. With a period, NumPy instead
converts x, xp and fp with np.asarray(…, dtype=…), which PARSES text (an empty text array converts to an
empty float array without parsing).
The fill values are NumPy's Python objects, converted by the chosen loop after its operand and length
checks (left before right): the real loop takes PyFloat_AsDouble, the complex loop keeps both parts of
a Python complex or an np.complex128 scalar and takes PyFloat_AsDouble of anything else. So a
C# literal converts as its Python number, an element read from a complex array (an np.complex128
scalar) gives the real loop its REAL part (NumPy's ComplexWarning has no NumSharp channel), and an explicit
0-d array converts through float(): np.array("5") parses to 5.0 where the literal
"5" is refused. A period discards both before any conversion.
API-parity batch 12: one signature. The double? overload and the Complex? overload became
NDArray fills, which a C# double, int or Complex converts to implicitly; a
nullable variable is passed as value is { } v ? v : null (C# has no lifted conversion from
double? to a class).
Exceptions
- ValueError
fporxpis not 1-D (object too deep for desired array/object of too small depth for desired array), xp is empty, the lengths differ, orperiodis zero (and, with a period,Data points must be 1-D sequences).- InvalidCastException
Without a period, an operand does not cast 'safely' to the loop's dtype (text, or a complex x / xp — NumPy's TypeError
Cannot cast array data from dtype('<U2') to dtype('float64') according to the rule 'safe',Cannot cast scalar …for a 0-d x).- ValueError
With a period, a text operand that does not parse as float64: NumPy parses the text first (
np.asarray(…, dtype=float64):could not convert string to float). Without one, a 0-d text array fill that spells no float.- TypeError
Without a period, a fill value NumPy's loop refuses, raised AFTER the operand and length checks: a Complex for a real
fp(must be real number, not complex, even with a zero imaginary part), a C# string (must be real number, not str), an array of one or more dimensions (only 0-dimensional arrays can be converted to Python scalars), a 0-d complex array (float() argument must be a string or a real number, not 'complex', for either loop).- ArgumentNullException
xis null.
intersect1d(NDArray, NDArray, bool, bool)
Find the intersection of two arrays — NumPy's np.intersect1d(ar1, ar2, assume_unique=False,
return_indices=False), one signature: the sorted, unique values that are in both input arrays, and with
return_indices the indices of their first occurrences in each.
public static np.Intersect1dResult intersect1d(NDArray ar1, NDArray ar2, bool assume_unique = false, bool return_indices = false)
Parameters
ar1NDArrayInput array (flattened if not already 1-D).
ar2NDArrayInput array (flattened if not already 1-D).
assume_uniqueboolIf True, the input arrays are both assumed to be unique, which can speed up the calculation (and, when they are not, the result holds duplicates and wrong indices, as in NumPy).
return_indicesboolIf True, also return the indices of the first occurrences of the common values in
ar1andar2(NumPy sorts with the stable 'mergesort' here).
Returns
- np.Intersect1dResult
An np.Intersect1dResult: the values (it converts implicitly to NDArray), and with
return_indicescomm1 / comm2 (it deconstructs into the three).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.intersect1d.html
API-parity batch 11: one signature returning the result type (np.unique's pattern) - it replaces the
(ar1, ar2) and (ar1, ar2, assume_unique) overloads that returned the values and the
NDArray[] one that always returned an array of outputs.
Exceptions
- UnicodeDecodeError
The concatenation decodes
Stext besideUtext, and a byte is not ASCII (in the order of the unique values).- DTypePromotionError
A
StringDTypeoperand beside a class the concatenation finds no common DType with (a number, bool,Sbytes): NumPy's verbatim promotion text.- ValueError
A NEP 55
StringDTypearray whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy'sCannot compare null that is not a nan-like value.
invert(NDArray, NDArray, NDArray, DType)
Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays.For signed integer inputs, the two's complement is returned. In a two's-complement system negative numbers are represented by the two's complement of the absolute value.
public static NDArray invert(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
- NDArray
Result. This is a scalar if x is a scalar.
Remarks
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.).
isclose(NDArray, NDArray, double, double, bool)
Returns a boolean array where two arrays are element-wise equal within a
tolerance.
The tolerance values are positive, typically very small numbers.The
relative difference (rtol * abs(b)) and the absolute difference
atol are added together to compare against the absolute difference
between a and b.
Warning: The default atol is not appropriate for comparing numbers
that are much smaller than one(see Notes).
See also allclose(NDArray, NDArray, double, double, bool)
Notes: For finite values, isclose uses the following equation to test whether two floating point values are equivalent.
absolute(`a` - `b`) less than or equal to (`atol` + `rtol` * absolute(`b`))
Unlike the built-in math.isclose, the above equation is not symmetric
in a and b -- it assumes b is the reference value -- so that
isclose(a, b) might be different from isclose(b, a). Furthermore,
the default value of atol is not zero, and is used to determine what
small values should be considered close to zero.The default value is
appropriate for expected values of order unity: if the expected values
are significantly smaller than one, it can result in false positives.
atol should be carefully selected for the use case at hand. A zero value
for atol will result in False if either a or b is zero.
public static NDArray<bool> isclose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
Parameters
aNDArrayInput array to compare with b
bNDArrayInput array to compare with a.
rtoldoubleThe relative tolerance parameter(see Notes)
atoldoubleThe absolute tolerance parameter(see Notes)
equal_nanboolWhether to compare NaN's as equal. If True, NaN's in
awill be considered equal to NaN's inbin the output array.
Returns
- NDArray<bool>
Returns a boolean array of where
aandbare equal within the given tolerance.If bothaandbare scalars, returns a single boolean value.
iscomplex(NDArray)
Returns a bool array, where True if input element is complex.
public static NDArray iscomplex(NDArray x)
Parameters
xNDArrayInput array (NumPy's keyword
x).
Returns
- NDArray
Boolean array of same shape, True where element has non-zero imaginary part.
Examples
var a = np.array(new int[] {1, 2, 3});
np.iscomplex(a) // [False, False, False]
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.iscomplex.html
For non-complex arrays, all elements are considered not complex. For complex arrays, elements with non-zero imaginary part are complex.
[NDScoped] reclaims the np.imag view and the Scalar(0) temp the complex branch hands to np.not_equal.
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.).- ArgumentNullException
xis null.
iscomplexobj(NDArray)
Return True if x is a complex type or an array of complex numbers.
public static bool iscomplexobj(NDArray x)
Parameters
xNDArrayInput array or scalar (NumPy's keyword
x; a C# scalar converts to a 0-d array).
Returns
- bool
True if the array's dtype is complex.
Examples
var a = np.array(new int[] {1, 2, 3});
np.iscomplexobj(a) // False (dtype is int, not complex)
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.iscomplexobj.html
The type of the input is checked, not the value.
Exceptions
- ArgumentNullException
xis null.
isdtype(DType, DType)
Returns True if the two descriptors are instances of the same DType class — NumPy's np.isdtype(dtype, other_dtype)
compares the scalar TYPES, so isdtype('M8[s]', 'M8[ns]') is True while isdtype(float32, float64) is False.
public static bool isdtype(DType dtype, DType kind)
Parameters
Returns
- bool
True when both are instances of one class.
Remarks
A StringDType descriptor is the StringDType class on either side (NumPy 2.5.2's
_preprocess_dtype, gh-32030): np.isdtype(StringDType(), StringDType(na_object=None)) is True, and
a StringDType beside any NumPy class is False. NumPy 2.4 refused it on either side.
Exceptions
- ArgumentNullException
dtypeis null.- TypeError
kindis null (kind argument must be comprised of NumPy dtypes or strings only, but is a <class 'NoneType'>.).
isdtype(DType, params DType[])
Returns True if the descriptor is an instance of ANY of the given dtypes' classes — NumPy's tuple form
np.isdtype(dtype, (np.str_, np.bytes_)). Each entry is compared by class, like
isdtype(DType, DType), so the string LENGTH or the byte order never matter.
public static bool isdtype(DType dtype, params DType[] kinds)
Parameters
Returns
- bool
True when
dtype's class is the class of any entry.
Exceptions
- ArgumentNullException
dtypeorkindsis null.- TypeError
An entry is null (NumPy:
kind argument must be comprised of NumPy dtypes or strings only).
isdtype(DType, NDScalarType)
NumPy's np.isdtype(dtype, kind) with a scalar class as kind: true only when the dtype
IS that class. NumPy compares classes by identity here, NOT by subclass — np.isdtype(np.int64,
np.integer) is False; use issubdtype(DType, NDScalarType) for the hierarchy.
public static bool isdtype(DType dtype, NDScalarType kind)
Parameters
dtypeDTypeThe dtype (any spelling: a DType, Type, NPTypeCode or dtype string).
kindNDScalarTypeThe scalar class.
Returns
- bool
True when the dtype's scalar class is
kinditself.
Remarks
A StringDType dtype is the StringDType class (NumPy 2.5.2), which no
scalar class is: False.
Exceptions
- ArgumentNullException
dtypeis null.- TypeError
kindis null or Python's built-instr(NumPy's_preprocess_dtypetexts).
isdtype(DType, params object[])
NumPy's tuple form np.isdtype(dtype, (kind, ...)) with MIXED kinds — names, dtypes and scalar classes
(np.isdtype(x, np.int64, "real floating")): true when the dtype is in any of them. A name selects its
concrete classes, a dtype or a class matches by identity; every kind is validated before the answer, as NumPy
processes the whole tuple first.
public static bool isdtype(DType dtype, params object[] kinds)
Parameters
dtypeDTypeThe dtype (any spelling).
kindsobject[]Each a kind name (string), a DType, an NDScalarType, a C# element Type or an NPTypeCode.
Returns
- bool
True when the dtype belongs to at least one kind.
Remarks
A StringDType dtype or kind is the StringDType class (NumPy 2.5.2): it matches only
itself.
Exceptions
- ArgumentNullException
dtypeorkindsis null.- TypeError
A kind is Python's built-in
str, of another type, or null:kind argument must be comprised of NumPy dtypes or strings only, but is a <class 'int'>.(NumPy's text, Python's class name).- ValueError
An unknown kind name.
isdtype(DType, string)
Returns True if the descriptor is of a specified category — NumPy 2.x's np.isdtype(dtype, kind) over a
DType: kind is one of "bool", "signed integer",
"unsigned integer", "integral", "real floating", "complex floating", "numeric"
(case-sensitive, as in NumPy). The datetime classes belong to none of them (NumPy builds the categories from
sctypes, which exclude datetime64/timedelta64).
This is the ONE entry for every dtype spelling: a C# Type (typeof(int)), an
NPTypeCode (NPTypeCode.Int32) or a dtype string all convert implicitly to DType
(the earlier NPTypeCode/Type twins accepted issubdtype's looser vocabulary — "floating",
"integer" — which NumPy's isdtype rejects; they were folded into this overload).
public static bool isdtype(DType dtype, string kind)
Parameters
Returns
Examples
np.isdtype(NPTypeCode.Int32, "integral") // True
np.isdtype(typeof(double), "real floating") // True
np.isdtype(np.int32, "numeric") // True
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isdtype.html — a NumPy 2.0+ function.
Exceptions
- ValueError
kind argument is a string, but '…' is not a known kind name.— verbatim NumPy.- TypeError
kindis null.
isdtype(DType, params string[])
Returns True if the descriptor is of any of the specified categories (NumPy's tuple form).
public static bool isdtype(DType dtype, params string[] kinds)
Parameters
dtypeDTypeThe descriptor to test.
kindsstring[]The category names (see isdtype(DType, string)).
Returns
- bool
True when
dtypeis under any of the categories.
Exceptions
- ArgumentNullException
dtypeorkindsis null.- TypeError
An entry is null.
- ValueError
An entry is not a known kind name.
isdtype(NDScalarType, DType)
NumPy's np.isdtype(dtype, kind) with a scalar class as dtype and a dtype as
kind: true when the class is the dtype's class (np.isdtype((NDScalarType)np.int64,
np.int64)); an abstract class never is one.
public static bool isdtype(NDScalarType dtype, DType kind)
Parameters
dtypeNDScalarTypeThe scalar class tested.
kindDTypeThe dtype (any spelling).
Returns
- bool
True when
dtypeiskind's scalar class.
Remarks
A StringDType kind is the StringDType class (NumPy 2.5.2), which no
scalar class is: False.
Exceptions
- TypeError
Either argument is null, or
dtypeis Python's built-instr(NumPy's texts).
isdtype(NDScalarType, NDScalarType)
NumPy's np.isdtype(dtype, kind) over two scalar classes: identity (np.isdtype(np.integer,
np.integer) is True, np.isdtype(np.integer, np.number) False).
public static bool isdtype(NDScalarType dtype, NDScalarType kind)
Parameters
dtypeNDScalarTypeThe scalar class tested.
kindNDScalarTypeThe scalar class compared with.
Returns
- bool
True when both are the same class.
Exceptions
- TypeError
Either argument is null or Python's built-in
str(NumPy's texts).
isdtype(NDScalarType, params object[])
isdtype(DType, params object[]) with a scalar class as dtype: an abstract class matches only itself, never a kind name.
public static bool isdtype(NDScalarType dtype, params object[] kinds)
Parameters
dtypeNDScalarTypeThe scalar class.
kindsobject[]Each a kind name, a DType, an NDScalarType, a C# element Type or an NPTypeCode.
Returns
- bool
True when the class belongs to at least one kind.
Exceptions
- ArgumentNullException
kindsis null.- TypeError
dtypeis null, or a kind of another type.- ValueError
An unknown kind name.
isdtype(NDScalarType, string)
NumPy's np.isdtype(dtype, kind) with a SCALAR CLASS as dtype: a concrete class
answers as its descriptor does (np.isdtype((NDScalarType)np.int8, "integral") is True), an abstract one
belongs to none of the named kinds (np.isdtype(np.integer, "integral") is False: NumPy builds each kind
from the CONCRETE classes of sctypes).
public static bool isdtype(NDScalarType dtype, string kind)
Parameters
dtypeNDScalarTypeThe scalar class.
kindstringOne of
"bool","signed integer","unsigned integer","integral","real floating","complex floating","numeric".
Returns
- bool
True when the class is one of the kind's concrete classes.
Exceptions
- TypeError
dtypeorkindis null (NumPy's texts forNone).- ValueError
An unknown kind name — verbatim NumPy.
isdtype(NDScalarType, params string[])
NumPy's tuple form of isdtype(NDScalarType, string): true when the class is in ANY of the kinds (every kind is validated first, as NumPy does).
public static bool isdtype(NDScalarType dtype, params string[] kinds)
Parameters
dtypeNDScalarTypeThe scalar class.
kindsstring[]The kind names.
Returns
- bool
True when the class belongs to at least one kind.
Exceptions
- ArgumentNullException
kindsis null.- TypeError
dtypeor a kind is null.- ValueError
An unknown kind name.
isdtype(string, string)
isdtype(DType, string) for a dtype STRING (np.isdtype("i4", "integral")). Exists so that a
string first argument binds the dtype grammar rather than NumSharp's string→NDArray conversion.
public static bool isdtype(string dtype, string kind)
Parameters
Returns
isdtype(string, params string[])
isdtype(DType, params string[]) for a dtype STRING.
public static bool isdtype(string dtype, params string[] kinds)
Parameters
Returns
isfinite(NDArray, NDArray, NDArray, DType)
Test element-wise for finiteness (not infinity and not Not a Number).
Mirrors NumPy's ufunc signature: isfinite(x, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool).
public static NDArray isfinite(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
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.).
isfortran(NDArray)
Check if the array is Fortran contiguous but not C contiguous — exactly NumPy's
a.flags.fnc (numpy/_core/numeric.py::isfortran, a pure flags read).
public static bool isfortran(NDArray a)
Parameters
aNDArrayInput array.
Returns
- bool
True iff
ais F-contiguous and not C-contiguous. Note the asymmetry NumPy documents: a 1-D (or 0-d / empty) array is BOTH C- and F-contiguous, soisfortranis False for it — this reports column-major MEMORY ORDER, not mere F-contiguity (usea.flags.f_contiguousfor that).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isfortran.html
<p>It reads the operand's layout only, so no class rule applies (a numpy.matrix answers for its own
layout).</p>
Exceptions
- ArgumentNullException
ais null.
isin(NDArray, NDArray, bool, bool, string)
Calculates element in test_elements, broadcasting over element only.
Returns a boolean array of the same shape as element that is True where an
element of element is in test_elements and False otherwise.
public static NDArray isin(NDArray element, NDArray test_elements, bool assume_unique = false, bool invert = false, string kind = null)
Parameters
elementNDArrayInput array.
test_elementsNDArrayThe values against which to test each value of
element. Flattened before use.assume_uniqueboolIf True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Where NumPy takes its sort path, repeated values then get NumPy's answer for them: an element is flagged when an equal value follows it in
elementor lies intest_elements.invertboolIf True, the values in the returned array are inverted, as if calculating
element not in test_elements. Default is False.kindstringThe algorithm to use:
null(auto),"sort", or"table". Every path gives the same membership, except underassume_uniquewith repeated values (which only the sort path reads)."table"is only valid for boolean/integer arrays (char is NumPy's uint16).
Returns
- NDArray
A boolean array with the same shape as
element.
Remarks
Exceptions
- ValueError
An unknown
kind(Invalid kind: 'x'. Please use None, 'sort' or 'table'.),kind='table'for a non-integer array, orkind='table'over a set whose range is2**63 - 1or more (Maximum allowed dimension exceeded, NumPy's table allocation).- InvalidOperationException
kind='table'with a range wider than the dtype's maximum (NumPy's RuntimeError text).- UnicodeDecodeError
A string operand on NumPy's sort path whose concatenation decodes
Stext holding a byte that is not ASCII intoU(seeDefaultEngine.IsinText).- NotSupportedException
A
StringDTypeset whose NA object is a sequence, held by an NA cell (NumPy broadcasts the comparison against it; seeDefaultEngine.IsinVString).
isinf(NDArray, NDArray, NDArray, DType)
Test element-wise for positive or negative infinity.
Mirrors NumPy's ufunc signature: isinf(x, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool).
public static NDArray isinf(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isinf.html
- Float/Double: True if value is +Inf or -Inf
- Integer types: Always False (integers cannot be Inf)
- NaN: Returns False (NaN is not infinity)
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.).
isnan(NDArray, NDArray, NDArray, DType)
Test element-wise for Not a Number.
Mirrors NumPy's ufunc signature: isnan(x, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool).
public static NDArray isnan(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
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.).
isneginf(NDArray, NDArray)
Test element-wise for negative infinity, return result as a bool array.
public static NDArray isneginf(NDArray x, NDArray @out = null)
Parameters
xNDArrayThe input array.
outNDArrayA location into which the result is stored (NumPy's positional
out). If provided it must have a shape the input broadcasts to; if its dtype is numeric the result is stored as 0/1, if boolean as False/True. The same instance is returned. Ifnull, a freshly allocated boolean array is returned.
Returns
- NDArray
A boolean array (or
out), True where the element is -Inf.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isneginf.html
Port of NumPy's numpy.isneginf (numpy/lib/_ufunclike_impl.py), defined as
logical_and(isinf(x), signbit(x)) — i.e. exactly x == -inf. Integer and boolean
inputs return all-False. A complex input raises TypeError
("This operation is not supported for complex128 values because it would be ambiguous."),
matching NumPy 2.4.2.
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.).
isposinf(NDArray, NDArray)
Test element-wise for positive infinity, return result as a bool array.
public static NDArray isposinf(NDArray x, NDArray @out = null)
Parameters
xNDArrayThe input array.
outNDArrayA location into which the result is stored (NumPy's positional
out). If provided it must have a shape the input broadcasts to; if its dtype is numeric the result is stored as 0/1, if boolean as False/True. The same instance is returned. Ifnull, a freshly allocated boolean array is returned.
Returns
- NDArray
A boolean array (or
out), True where the element is +Inf.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isposinf.html
Port of NumPy's numpy.isposinf (numpy/lib/_ufunclike_impl.py), defined as
logical_and(isinf(x), ~signbit(x)) — i.e. exactly x == +inf. Integer and boolean
inputs return all-False (they cannot be infinite). A complex input raises
TypeError ("This operation is not supported for complex128 values because it would
be ambiguous.") — NumPy's signbit is ambiguous on complex, so the whole function is —
matching NumPy 2.4.2.
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.).
isreal(NDArray)
Returns a bool array, where True if input element is real.
public static NDArray isreal(NDArray x)
Parameters
xNDArrayInput array (NumPy's keyword
x).
Returns
- NDArray
Boolean array of same shape, True where element has no imaginary part.
Examples
var a = np.array(new int[] {1, 2, 3});
np.isreal(a) // [True, True, True]
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isreal.html
For non-complex arrays, all elements are considered real. For complex arrays, elements with zero imaginary part are real.
[NDScoped] reclaims the np.imag view and the Scalar(0) temp the complex branch hands to np.equal.
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.).- ArgumentNullException
xis null.
isrealobj(NDArray)
Return True if x is a not complex type or an array of complex numbers.
public static bool isrealobj(NDArray x)
Parameters
xNDArrayInput array or scalar (NumPy's keyword
x; a C# scalar converts to a 0-d array).
Returns
- bool
True if the array's dtype is not complex.
Examples
var a = np.array(new int[] {1, 2, 3});
np.isrealobj(a) // True (dtype is int, not complex)
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isrealobj.html
The type of the input is checked, not the value. Even an array of complex numbers with zero imaginary parts will return False.
Exceptions
- ArgumentNullException
xis null.
isscalar(object)
Returns true incase of a number, bool or string. If null, returns false.
public static bool isscalar(object element)
Parameters
elementobjectAny object, null included (NumPy's keyword
element).
Returns
- bool
True for a C# number (a primitive, a decimal, a Complex, a Half, a BigInteger), a bool, a string, a Char8, a DateTime64 and a NumPy scalar - a 0-d NDArray that was not built as an explicit array (
a.sum(),a[0],NDArray.Scalar(1.5)); false for null, an explicit 0-d array (np.array(5), as in NumPy), any NDArray with dimensions, a C# array, a Type (NumPy'sisscalar(int)is False) and any other object.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isscalar.html
<p>NumPy's statement is the array object's (<code>NDArray.isscalar</code>, whose remarks hold the one answer that
differs from NumPy's: a 0-d array built another way than <code>np.array(x)</code> / <code>np.asarray(x)</code>, such as
<code>np.zeros(())</code>, answers True, because NumSharp's scalar is a 0-d array). The object has no array class to
decide, so no class rule applies.</p>
issctype(object)
Determines whether the given object represents a scalar dtype — NumPy 1.x's np.issctype(rep). Kept on
purpose, so code written against NumPy 1.x compiles and runs unchanged, although NumPy 2.0 removed it
(AttributeError: ). New code writes NumPy 2's test, np.issctype was removed in the NumPy 2.0 release. Use issubclass(rep, np.generic)
instead.np.generic.subclasscheck(rep).
public static bool issctype(object rep)
Parameters
repobjectThe object to check: a DType (what
np.int32is), an NPTypeCode or a C# Type. Anything else, null included, is not a scalar type.
Returns
- bool
True when
repnames a NumSharp storage type: every dtype except Empty. The string classes count, as in NumPy 1.x, wherenp.issctype(np.str_),np.issctype(np.dtype('S3'))andnp.issctype(str)are True: their descriptors (np.str_,np.bytes_,'U5','S3',StringDType),typeof(string)and their lane String.
Examples
np.issctype(np.int32) // True
np.issctype(typeof(int)) // True
np.issctype(NPTypeCode.Int32) // True
np.issctype(np.str_) // True
np.issctype(typeof(NDArray)) // False
Remarks
https://numpy.org/doc/1.26/reference/generated/numpy.issctype.html
NumPy 1.x answered False only for object_ (and for anything that is no type or dtype), and NumSharp
cannot store object_, so every descriptor with a storage lane answers True.
The answer is the descriptor's STORAGE code, so a datetime64 / timedelta64 descriptor (no storage lane yet)
answers false where NumPy 1.x answered true. NDScalarType classes are not accepted (NumPy 1.x
answered true for every subclass of np.generic, abstract ones included): ask
np.generic.__subclasscheck__ for those.
issubdtype(DType, DType)
Returns True if the scalar class of arg1 is the scalar class of arg2 or a
subclass of it — NumPy's issubdtype(dtype1, dtype2) over two DESCRIPTORS, which compares their
.type: instances of one class compare equal whatever their parameters
(issubdtype('M8[s]', 'M8[ns]') is True, as is issubdtype('>i4', 'i4')), and distinct concrete
classes are never related (issubdtype(int32, int64) is False).
public static bool issubdtype(DType arg1, DType arg2)
Parameters
arg1DTypeThe dtype tested; null is NumPy's
None, i.e. float64.arg2DTypeThe dtype tested against; null is float64.
Returns
- bool
True when both descriptors belong to the same dtype class.
issubdtype(DType, NDScalarType)
Returns True if the dtype arg1 is under the scalar class arg2 — NumPy's
most common type test, np.issubdtype(a.dtype, np.integer). Every dtype spelling binds here: a
DType, a C# Type (typeof(int)), an NPTypeCode and a dtype
string ("i4") all convert to DType implicitly.
public static bool issubdtype(DType arg1, NDScalarType arg2)
Parameters
arg1DTypeThe dtype tested (NumPy's
dtype(arg1).typeis the class compared); null is NumPy'sNone, i.e. float64.arg2NDScalarTypeThe scalar class, usually an abstract one (integer, floating, ...); null is float64.
Returns
- bool
True when
arg1's scalar class isarg2or derives from it.
Examples
np.issubdtype(np.int32, np.integer) // True
np.issubdtype(np.float32, np.floating) // True
np.issubdtype(np.bool_, np.number) // False: bool is not a number in NumPy 2.x
np.issubdtype("m8[s]", np.signedinteger) // True: timedelta64 is a signed integer
Exceptions
- TypeError
A dtype string that is not one (NumPy's
data type 'x' not understood), raised while convertingarg1.- NotSupportedException
A dtype string naming a dtype NumSharp has no class for (complex64, object, void).
issubdtype(DType, string)
issubdtype(DType, DType) with the second argument a NumPy dtype STRING, parsed by
dtype(string, bool, bool, IReadOnlyDictionary<string, object>) as NumPy
parses it: np.issubdtype(np.float64, "f8") and np.issubdtype(np.float64, "float") are True,
np.issubdtype(np.float32, "float") is False ("float" names float64, not the floating family).
public static bool issubdtype(DType arg1, string arg2)
Parameters
arg1DTypeThe dtype tested; null is NumPy's
None, i.e. float64.arg2stringA dtype string; null is float64.
Returns
- bool
True when both name the same dtype class.
Remarks
BREAKING (NumPy 2.x parity): NumSharp used to read this string as an abstract category name
("integer", "floating", "signed", "float"), which NumPy rejects or reads as a dtype —
so issubdtype(np.float32, "float") answered True where NumPy answers False. Spell the category as the
class: np.issubdtype(x, np.floating).
Exceptions
- NotSupportedException
arg2is not a dtype string (data type 'integer' not understood, NumPy's text for itsTypeError). The abstract classes are objects, not strings: integer, floating.
issubdtype(NDScalarType, DType)
Returns True if the scalar class arg1 is under the dtype arg2's class:
np.issubdtype(np.integer, "i4") is False, since a concrete class has no subclasses but itself.
public static bool issubdtype(NDScalarType arg1, DType arg2)
Parameters
arg1NDScalarTypeThe scalar class tested; null is NumPy's
None, i.e. float64.arg2DTypeThe dtype (any spelling: a DType, Type, NPTypeCode or dtype string); null is float64.
Returns
- bool
True when
arg1isarg2's scalar class or derives from it.
Exceptions
- TypeError
A dtype string that is not one (NumPy's
data type 'x' not understood), raised while convertingarg2.- NotSupportedException
A dtype string naming a dtype NumSharp has no class for (complex64, object, void).
issubdtype(NDScalarType, NDScalarType)
Returns True if the first argument is a scalar class lower than or equal to the second in NumPy's type
hierarchy — np.issubdtype(arg1, arg2) for two scalar classes (np.issubdtype(np.integer, np.number)
is True, np.issubdtype(np.number, np.integer) False).
public static bool issubdtype(NDScalarType arg1, NDScalarType arg2)
Parameters
arg1NDScalarTypeThe class tested; a DType also converts here (its scalar class). Null is NumPy's
None, i.e. float64.arg2NDScalarTypeThe class tested against; null is NumPy's
None, i.e. float64.
Returns
- bool
True when
arg2isarg1or one of its base classes.
Examples
np.issubdtype(np.floating, np.inexact) // True
np.issubdtype(np.integer, np.floating) // False
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.issubdtype.html — the abstract classes are generic, number, integer, signedinteger, unsignedinteger, inexact, floating, complexfloating, flexible and character. bool is directly under generic (not a number), datetime64 directly under generic, timedelta64 under signedinteger.
issubdtype(NPTypeCode, NPTypeCode)
Returns True if the two storage codes name the same dtype class: issubdtype(int32, int32) is True,
issubdtype(int32, int64) False — concrete classes are never subclasses of one another.
public static bool issubdtype(NPTypeCode arg1, NPTypeCode arg2)
Parameters
arg1NPTypeCodeThe storage code tested.
arg2NPTypeCodeThe storage code tested against.
Returns
- bool
True when the codes are equal.
Remarks
For the abstract families use the class objects: np.issubdtype(NPTypeCode.Int32, np.integer).
issubdtype(NPTypeCode, string)
issubdtype(DType, string) for an NPTypeCode first argument.
public static bool issubdtype(NPTypeCode arg1, string arg2)
Parameters
arg1NPTypeCodeThe storage code tested.
arg2stringA dtype string; null is NumPy's
None, i.e. float64.
Returns
- bool
True when both name the same dtype class.
Exceptions
- TypeError
arg2is not a dtype string (NumPy'sdata type 'x' not understood).- NotSupportedException
arg1has no dtype class, orarg2names a dtype NumSharp has no class for.
issubdtype(string, string)
issubdtype(DType, string) for a dtype STRING first argument (np.issubdtype("i4", "i8")).
Exists so that a string first argument binds the dtype grammar rather than NumSharp's string → NDArray
(character array) conversion.
public static bool issubdtype(string arg1, string arg2)
Parameters
arg1stringA dtype string; null is NumPy's
None, i.e. float64.arg2stringA dtype string; null is float64.
Returns
- bool
True when both name the same dtype class.
Exceptions
- TypeError
Either string is not a dtype string (NumPy's
data type 'x' not understood).- NotSupportedException
Either string names a dtype NumSharp has no class for.
issubdtype(Type, string)
issubdtype(DType, string) for a C# element Type first argument (typeof(int) is int32).
public static bool issubdtype(Type arg1, string arg2)
Parameters
arg1TypeThe C# element type tested; null is NumPy's
None, i.e. float64.arg2stringA dtype string; null is float64.
Returns
- bool
True when both name the same dtype class.
Exceptions
- TypeError
arg2is not a dtype string (NumPy'sdata type 'x' not understood).- NotSupportedException
arg1is no dtype's element type, orarg2names a dtype NumSharp has no class for.
issubdtype(Type, Type)
Returns True if the two C# element types are the same dtype's: issubdtype(typeof(int), typeof(long)) is
False, as NumPy's issubdtype(np.int32, np.int64) is.
public static bool issubdtype(Type arg1, Type arg2)
Parameters
Returns
- bool
True when both map to the same storage code.
issubsctype(NPTypeCode, NPTypeCode)
Determine if a class is a subclass of a second class — NumPy 1.x's np.issubsctype(arg1, arg2). Kept on
purpose, so code written against NumPy 1.x compiles and runs unchanged, although NumPy 2.0 removed it
(AttributeError: ).
New code writes issubdtype(NPTypeCode, NPTypeCode), which this delegates to.np.issubsctype was removed in the NumPy 2.0 release. Use np.issubdtype instead.
public static bool issubsctype(NPTypeCode arg1, NPTypeCode arg2)
Parameters
arg1NPTypeCodeThe dtype to check; a DType such as
np.int32converts implicitly.arg2NPTypeCodeThe dtype to compare against; a DType converts implicitly.
Returns
- bool
True if arg1 is a subtype of arg2.
Remarks
https://numpy.org/doc/1.26/reference/generated/numpy.issubsctype.html
Only concrete dtypes are accepted (two storage codes), so the abstract-class form NumPy 1.x allowed
(np.issubsctype(np.int32, np.integer)) does not compile; np.issubdtype takes the classes.
iterable(object)
Check whether or not an object can be iterated over. Returns true if
y has an iterator method or is a sequence, and false otherwise.
public static bool iterable(object y)
Parameters
yobjectInput object.
Returns
- bool
trueif the object is iterable,falseotherwise.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.iterable.html
Port of NumPy's numpy.iterable (numpy/lib/_function_base_impl.py), whose whole
body is try: iter(y); return True; except TypeError: return False. It is a pure
predicate — it does NOT iterate the data, it only tests whether iteration is possible — so it
needs no kernel/NDIter/loop of any kind (O(1) rank/type check).
The one surprise NumPy documents is 0-dimensional arrays: although a 0-d NDArray
is a collection type, iter() on it raises TypeError("iteration over a 0-d array")
(see GetEnumerator()), so np.iterable(np.array(1.0)) is false
while any array of rank ≥ 1 (empty included) is true.
C# type mapping (each matches NumPy's iter() outcome, probed against NumPy 2.4.2):
null→ false (NumPy'siter(None)raises TypeError).- NDArray →
ndim != 0(0-d is the only non-iterable array). - string → true (Python strings are iterable).
- Any IEnumerable — C# arrays, lists, dictionaries, sets … → true.
- Everything else — the scalar value types int/double/bool/Complex/Half/decimal/char … → false.
Deliberate C# divergences (probed against NumPy 2.4.2): NumSharp maps Python's
iter()-ability onto C#'s IEnumerable — i.e. "is this foreach-able?".
Four inputs are iterable in Python but their C# analogs cannot be foreach'd, so they
return false here while NumPy returns true: a bare IEnumerator /
IEnumerator<T> cursor (a Python iterator is self-iterable, but a C# enumerator
has no GetEnumerator), and ValueTuple / Tuple / ITuple
(they implement no IEnumerable). Real ported code passes the collection itself —
an array, List, or NDArray, all foreach-able — which matches NumPy exactly.
ix_(params object[])
Construct an open mesh from multiple sequences.
public static NDArray[] ix_(params object[] args)
Parameters
argsobject[]N 1-D sequences of integer or boolean type. A boolean sequence is interpreted as a mask for the corresponding dimension (equivalent to passing nonzero(NDArray) of it). Accepts anything asanyarray(in object, DType, char?, string, bool?) understands — NDArray, C# arrays, collections, tuples.
Returns
- NDArray[]
N arrays with N dimensions each, shape 1 in every axis but the k-th (which carries the k-th sequence). Together they form an open mesh:
a[np.ix_(rows, cols)]selects the cross producta[rows][:, cols].
Remarks
Port of NumPy 2.x numpy.ix_ (numpy/lib/_index_tricks_impl.py). The reshape is a
VIEW when the source permits one, so the outputs share memory with an NDArray
input (NumPy does the same — shares_memory is True there too) and remain writeable.
Every output is a NEW view, a single sequence's too (NumPy's reshape to the same shape): never the
input array itself, and never an array that owns its data.
The dtype is PRESERVED, not forced to intp: ix_ performs no integer validation,
so a float or byte sequence comes back as float/byte and only fails later, at the indexing
call. The single exception is NumPy's: a non-ndarray input that turns out EMPTY is cast to
intp (int64) to avoid the float64 default of an untyped empty list. A typed C# array
(new int[0]) or Memory<T> is an ndarray in NumSharp's boundary map and keeps
its dtype; an empty object[] or collection is a Python list and becomes int64.
https://numpy.org/doc/stable/reference/generated/numpy.ix_.html
Exceptions
- ValueError
A sequence is not 1-D ("Cross index must be 1 dimensional").
kaiser(double, double)
Return the Kaiser window — a taper formed by a Bessel function.
public static NDArray kaiser(double M, double beta)
Parameters
MdoubleNumber of points in the output window. If zero or less, an empty array is returned.
betadoubleShape parameter for the window. As
betagrows the window narrows;beta == 0is a rectangular window. Typical values: 5 (~Hamming), 6 (~Hanning), 8.6 (~Blackman).
Returns
- NDArray
The window, maximum normalized to one (the value one appears only when
Mis odd).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.kaiser.html
NumPy: i0(beta * sqrt(1 - ((n-alpha)/alpha)**2)) / i0(beta) with
n = arange(0, M) and alpha = (M-1)/2; the statements are Kaiser(double, double), called
on the default engine. The modified Bessel function BesselI0(double) is the cephes Chebyshev evaluation
NumPy's np.i0 uses, applied per element in the fused pass (bit-identical to NumPy's piecewise
result).
Exceptions
- ValueError
Mis NaN, or an infinity or too large for arange to size.- OutOfMemoryException
A finite count whose window does not fit in memory.
kron(NDArray, NDArray)
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the second array
scaled by the first. If a.shape = (r0,r1,...,rN) and b.shape = (s0,s1,...,sN)
the result has shape (r0*s0, r1*s1, ..., rN*sN) with
kron(a,b)[k0,...,kN] = a[i0,...,iN] * b[j0,...,jN] where kt = it*st + jt.
The number of dimensions of a and b need not match —
the smaller is treated as if prepended with size-1 axes (NumPy's ndmin behaviour).
public static NDArray kron(NDArray a, NDArray b)
Parameters
Returns
- NDArray
A fresh, writeable, C-contiguous array. The result dtype follows NumPy's
multiplypromotion (NEP50). Ifbis 0-d the result is the element-wisea * b(which is itself the degenerate Kronecker product). Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.kron.html
The body is Kron(NDArray, NDArray) (the np-layer dtype plan); this facade keeps the
numpy.matrix and numpy.char.chararray rules.
Exceptions
- NullReferenceException
aorbis null.- 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.
lcm(NDArray, NDArray, NDArray, NDArray, DType)
Returns the element-wise lowest common multiple of the absolute values of x1
and x2 (np.lcm). lcm(x, 0) == 0; otherwise |x1| / gcd * |x2|
(divide-before-multiply, and the product WRAPS the dtype on overflow — e.g.
lcm(int16 21000, 14000) == -23536 — matching NumPy exactly).
Shares every rule with gcd(NDArray, NDArray, NDArray, NDArray, DType): integer-only
loops (bool/float/complex/decimal and uint64+signed raise the no-loop TypeError),
one shared promoted integer dtype, and NEP50 weak-scalar binding for C# integer literals.
Mirrors NumPy's ufunc signature lcm(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray lcm(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array (integer dtype).
x2NDArraySecond input array (integer dtype); broadcasts against
x1.outNDArrayA location into which the result is stored (NumPy ufunc
out=); returned as-is.whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc
where=); masked-off slots keep their prior value.dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=): computation runs in this dtype; must name an integer loop.
Returns
- NDArray
The element-wise lcm. A scalar (0-d) when both inputs are scalars.
Remarks
Exceptions
- TypeError
The inputs (or
dtype) name no integer lcm loop.- TypeError
An input is not same_kind-castable to
dtype, oroutcannot take the loop dtype.- ArgumentException
whereis non-boolean, oroutdoes not broadcast.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
ldexp(NDArray, NDArray, NDArray, NDArray, DType)
Compute x1 * 2^x2 element-wise — the inverse of frexp(NDArray, (NDArray, NDArray), NDArray, DType). Given a
mantissa and an integer power of two it reconstructs the value (ldexp(*frexp(x)) == x).
Mirrors NumPy's ufunc ldexp(x1, x2).
public static NDArray ldexp(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayMantissa/base values. Integer/bool inputs promote to a float per NumPy's width rule (bool/int8/uint8 → float16, int16/uint16/char → float32, int32+ → float64); Half/Single/Double are preserved and Decimal is a NumSharp extension. A complex mantissa is rejected.
x2NDArrayInteger exponents (a Python/C# int scalar converts implicitly). Accepted dtypes are bool and the integers that safely cast to int64 (int8..int64, uint8..uint32) plus char; uint64, any float, and complex exponents are rejected (NumPy's TypeError). The exponent does NOT widen
x1's dtype — the result is purelyx1's float tier. An exponent too large for the C-int range is clamped, so it overflows to ±inf / underflows to ±0 exactly as NumPy's int64 loop specifies.x1andx2broadcast to a common shape.outNDArrayA location into which the result is stored (NumPy ufunc
out=): must be same_kind-castable from the loop dtype (x1's float tier) and match the broadcast shape; the same instance is returned. A float32 result up-casts into a float64out.whereNDArrayBoolean mask (NumPy ufunc
where=): only mask-true elements are written toout; masked-off slots keep their prior contents. Must be boolean and broadcast to the result shape.dtypeDTypeNumPy's
dtype=: the loop's float dtype (float16 / float32 / float64), or null forx1's float tier. The operands must reach that float x int loop under 'safe' casting (x1 to the dtype, x2 to int64); anything else is NumPy's "No loop matching the specified signature and casting was found" TypeError.
Returns
- NDArray
x1 * 2^x2inx1's float tier (ordtype), broadcast to the common shape (a scalar if both inputs are scalars). An F-contiguous input set yields an F-contiguous result.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ldexp.html
Bit-identical to win-amd64 NumPy 2.4.2 — ScaleB(double, int) is
the C ldexp, including the IEEE special values (ldexp(±inf, n) = ±inf,
ldexp(NaN, n) = NaN, ldexp(±0, n) = ±0).
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.).- IncorrectTypeException
No loop: a complex mantissa, a non-integer exponent, or a
dtypethe operands do not reach under 'safe' casting.
left_shift(NDArray, NDArray, NDArray, NDArray, DType)
Shift the bits of an integer to the left.
Mirrors NumPy's ufunc signature: left_shift(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray left_shift(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayValue operand (integer/bool/char only; bool promotes to int8).
x2NDArrayShift-count operand (integer/bool/char only).
outNDArrayA location into which the result is stored; must be same_kind-castable from the promoted loop dtype (int32→int16/float64 work; int32→uint8/bool raise). Returned as-is.
whereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeOptional loop dtype override; must be an integer/char loop — a float/complex/decimal request raises NumPy's no-loop TypeError.
Returns
- NDArray
Array with bits shifted left (or
outwhen provided).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.left_shift.html
One signature, NumPy's ufunc form (2026-11-11): the former overload that took the shift count as an
object read a boxed number as a STRONG array; a C# literal converts to a 0-d array marked as the
Python scalar it stands for (NEP 50's weak scalar), and a value held in an object variable goes
through asanyarray(in object, DType, char?, string, bool?).
Bits are shifted to the left by appending x2 0s at the right of x1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying x1 by 2**x2.
Example: np.left_shift(5, 2) = 20 # 0b101 -> 0b10100
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.).
less(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 < x2) element-wise.
Mirrors NumPy's ufunc signature: less(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the < operator for the typed wrapper).
public static NDArray less(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).
less(NDArray, object)
Return (x1 < x2) element-wise with scalar.
public static NDArray<bool> less(NDArray x1, object x2)
Parameters
Returns
less(object, NDArray)
Return (x1 < x2) element-wise with scalar on left.
public static NDArray<bool> less(object x1, NDArray x2)
Parameters
Returns
less_equal(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 <= x2) element-wise.
Mirrors NumPy's ufunc signature: less_equal(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the <= operator for the typed wrapper).
public static NDArray less_equal(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).
less_equal(NDArray, object)
Return (x1 <= x2) element-wise with scalar.
public static NDArray<bool> less_equal(NDArray x1, object x2)
Parameters
Returns
less_equal(object, NDArray)
Return (x1 <= x2) element-wise with scalar on left.
public static NDArray<bool> less_equal(object x1, NDArray x2)
Parameters
Returns
lexsort(NDArray, int)
np.lexsort with the keys packed in ONE array, exactly as NumPy reads it as a
sequence: a (k, …) array contributes its k SUB-ARRAYS as the keys (last row = primary).
A 1-D input therefore degenerates into N scalar (0-d) keys and returns the 0-d
0 — NumPy's probed quirk, not an error.
public static NDArray lexsort(NDArray keys, int axis = -1)
Parameters
keysNDArrayArray whose first-axis sub-arrays are the sort keys.
axisintAxis to sort along (default -1).
Returns
Remarks
Exceptions
- TypeError
A 0-d array or an empty first axis (
need sequence of keys with len > 0 in lexsort).- AxisError
The axis is out of bounds for a key's rank.
- ValueError
A
StringDTypekey line holding a None-like NA (see lexsort(NDArray[], int)).
lexsort(NDArray[], int)
Perform an indirect stable sort using a sequence of keys — the LAST key is the
PRIMARY sort key, the second-to-last breaks its ties, and so on (NumPy
np.lexsort). Returns int64 indices that sort every key line lexicographically.
public static NDArray lexsort(NDArray[] keys, int axis = -1)
Parameters
keysNDArray[]The k sort keys, all the same shape. Keys are only read.
axisintAxis to sort along (default -1, the last axis).
Returns
- NDArray
int64 index array of the keys' shape. A
numpy.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.lexsort.html
Port of PyArray_LexSort (item_selection.c), the engine's
LexSort(NDArray[], int) (the np-layer dtype plan, phase PE, E5): each key is run
through a STABLE argsort from FIRST to LAST, every pass re-sorting the running permutation — NumSharp's
radix argsort is stable, so the composition
perm = take_along_axis(perm, argsort(take_along_axis(key, perm))) reproduces
NumPy's mechanism pass for pass. Validation order is NumPy's: non-empty keys
(TypeError "need sequence of keys with len > 0 in lexsort") → same shape
(ValueError "all keys need to be the same shape") → axis bounds (0-d keys let axis
0/-1 slip through, NumPy's backwards-compat quirk) → the size ≤ 1 early return
(a 0-filled int64 array of the keys' shape). NaN keys sort last (stable argsort policy);
ties across ALL keys keep ascending index order.
Exceptions
- TypeError
No key (
need sequence of keys with len > 0 in lexsort).- ArgumentNullException
A key is null (
lexsort key 1 is null).- ValueError
Keys of different shapes (
all keys need to be the same shape).- AxisError
The axis is out of bounds for the keys' rank.
- ValueError
A
StringDTypekey line of two or more elements holding an NA whose NA object is neither NaN-like nor a string (Cannot compare null that is not a nan-like value). Text keys sort by their text: fixed-width ones (S/U) with the stable string argsort,StringDTypeones with NumPy's timsort (two adjacent NaN-like NAs of a line come out reversed, as in NumPy).
linspace(NDArray, NDArray, long, bool, DType, int, string)
Return evenly spaced numbers over a specified interval: num samples from
start to stop, NumPy's np.linspace. The ends may be numbers or
arrays; array ends give one ramp per element, along a new axis placed by axis.
public static NDArray linspace(NDArray start, NDArray stop, long num = 50, bool endpoint = true, DType dtype = null, int axis = 0, string device = null)
Parameters
startNDArrayThe starting value of the sequence: a number or an array. A C# number is a Python number, WEAK under NEP 50 (it takes the other end's dtype);
NDArray.Scalar(0.1f)or a float32 array is a NumPy float32, so two of them compute in float32 (NumPy's bits, which differ from float64 samples cast to float32).stopNDArrayThe end value of the sequence, unless
endpointis false; then the sequence is all but the last ofnum + 1evenly spaced samples, and the step changes. Broadcast againststart.numlongNumber of samples to generate. Default is 50. Must be non-negative.
endpointboolIf true,
stopis the last sample (written exactly). Default is true.dtypeDTypeThe type of the output array: a C# Type, an NPTypeCode, a NumPy dtype string (
"f4") or a DType. Null (the default) keeps the computation dtype,result_type(start, stop, 1.0): float64 for numbers and integer arrays, float32 for float32 ends, complex for complex ends. An integer dtype floors the samples first; a text dtype formats them.axisintThe axis in the result to store the samples (relevant only for array ends): 0 puts them first, -1 last.
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
The samples, shape
(num, *broadcast(start, stop).shape)with the sample axis moved toaxis. Anumpy.matrixend gives a matrix, as NumPy's_array_converter.wrapdoes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linspace.html
NumPy's retstep=True is the overload that takes object ends,
linspace(object, object, long, bool, bool, DType, int, string): a call that names
retstep binds it, every other call binds this one.
Computed by the start operand's engine (Linspace(NDArray, NDArray, long, bool, DType, int, string)).
Exceptions
- ArgumentNullException
startorstopis null.- ValueError
A negative
num(Number of samples, -1, must be non-negative.), checked first, as NumPy checks it; adeviceother than"cpu"(Device not understood. Only "cpu" is allowed, but received: ...).- DTypePromotionError
Ends with no inexact common dtype (text ends).
- IncorrectShapeException
Array ends that do not broadcast (NumPy's ValueError text).
- AxisError
axisout of range for the result (destination: axis 3 is out of bounds for array of dimension 2).- TypeError
An integer
dtypeover complex ends.
linspace(object, object, long, bool, bool, DType, int, string)
NumPy's whole np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, *,
device=None), retstep included: the samples, and with retstep the step between
them. The ends are any array_like NumPy takes - a number, an NDArray, a C# array or an
object[] list.
public static np.LinspaceResult linspace(object start, object stop, long num = 50, bool endpoint = true, bool retstep = false, DType dtype = null, int axis = 0, string device = null)
Parameters
startobjectThe starting value: a number (a weak Python number), a NumPy scalar or array, or a list.
stopobjectThe end value (see linspace(NDArray, NDArray, long, bool, DType, int, string)).
numlongNumber of samples to generate. Default is 50. Must be non-negative.
endpointboolIf true,
stopis the last sample. Default is true.retstepboolIf true, the result also carries the step (step).
dtypeDTypeThe type of the output array, or null for the computation dtype.
axisintThe axis in the result to store the samples (array ends).
devicestringTarget device. Only
"cpu"andnullare accepted.
Returns
- np.LinspaceResult
The samples, and the step when
retstepis true; it converts implicitly to the samples' NDArray and deconstructs into(samples, step).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.linspace.html
C# binds a call to this overload when it names retstep (or passes it fifth,
np.linspace(0, 1, 5, true, true)), or when an end is typed object: an NDArray is a
better conversion target than object, so every other call binds the NDArray overload, under C# 12 and
13 alike.
The step is NumPy's delta / div computed with the public ufuncs, so a numpy.matrix end gives
a matrix step, as in NumPy; there is no step (a NaN) for no samples or one with the endpoint.
Exceptions
- ArgumentNullException
startorstopis null.- ValueError
A negative
num, or adeviceother than"cpu"; a ragged list end.- DTypePromotionError
Ends with no inexact common dtype (text ends).
- IncorrectShapeException
Ends that do not broadcast.
- AxisError
axisout of range for the result.- TypeError
An integer
dtypeover complex ends.- NotSupportedException
An end of a type NumSharp has no array for.
load(byte[], string, bool, bool, string, long)
Load an array or archive from an in-memory .npy/.npz image.
public static object load(byte[] bytes, string mmap_mode = null, bool allow_pickle = false, bool fix_imports = true, string encoding = "ASCII", long max_header_size = 10000)
Parameters
bytesbyte[]mmap_modestringMemory-map mode for a
.npyfile:"r"/"readonly"(read-only),"r+"(read-write, flushed to disk) or"c"(copy-on-write, not flushed); null (default) reads the whole array into owned memory. Ignored for a.npzarchive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).allow_pickleboolWhether to trust the file. Default false, as in NumPy since 1.16.3: an object array is a Python pickle, and unpickling untrusted data can execute arbitrary code in NumPy. With true, NumSharp reads the one pickle it can represent — NumPy's pickle of a NEP 55
StringDTypearray, in a.npyfile, an.npzmember or a bare pickle file — without executing anything it names, and refuses every other pickle. Per NumPy it also liftsmax_header_size.fix_importsboolPresent for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.
encodingstringPresent for NumPy parity; validated but otherwise unused. Must be
"ASCII","latin1"or"bytes".max_header_sizelongReject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when
allow_pickleis true.
Returns
- object
An NDArray for a
.npyfile, or an NpzFile for a.npzarchive — mirroring NumPy, whose return type also depends on the content. Prefer load_npy(string, bool, long) or load_npz(string, bool, long) when the kind is known: they are typed and need no cast.An NpzFile owns a file handle and must be disposed.
Examples
var arr = (NDArray)np.load("data.npy");
if (np.load("data.npz") is NpzFile npz)
using (npz)
{ NDArray w = npz["weights"]; }
Remarks
Exceptions
- EOFError
The file is empty.
- FormatException
The content is not a .npy or .npz file, or is malformed; or it is a pickle and
allow_pickleis false (NumPy's texts).- NotSupportedException
A pickle that is not NumPy's pickle of a
StringDTypearray.- ValueError
Array can't be memory-mapped: Python objects in dtype.(a pickled file with ammap_mode).- UnicodeError
A
.npypickle whose text is not UTF-8: NumPy'sUnpickling a python object failed: UnicodeDecodeError(...)text (a ValueError, as in Python).
load(Stream, string, bool, bool, string, long)
Load an array or archive from an open stream. The stream must be readable and seekable, and is left open — the caller owns it.
public static object load(Stream file, string mmap_mode = null, bool allow_pickle = false, bool fix_imports = true, string encoding = "ASCII", long max_header_size = 10000)
Parameters
fileStreamPath to the file. The type is detected from its magic bytes, not its extension.
mmap_modestringMemory-map mode for a
.npyfile:"r"/"readonly"(read-only),"r+"(read-write, flushed to disk) or"c"(copy-on-write, not flushed); null (default) reads the whole array into owned memory. Ignored for a.npzarchive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).allow_pickleboolWhether to trust the file. Default false, as in NumPy since 1.16.3: an object array is a Python pickle, and unpickling untrusted data can execute arbitrary code in NumPy. With true, NumSharp reads the one pickle it can represent — NumPy's pickle of a NEP 55
StringDTypearray, in a.npyfile, an.npzmember or a bare pickle file — without executing anything it names, and refuses every other pickle. Per NumPy it also liftsmax_header_size.fix_importsboolPresent for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.
encodingstringPresent for NumPy parity; validated but otherwise unused. Must be
"ASCII","latin1"or"bytes".max_header_sizelongReject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when
allow_pickleis true.
Returns
- object
An NDArray for a
.npyfile, or an NpzFile for a.npzarchive — mirroring NumPy, whose return type also depends on the content. Prefer load_npy(string, bool, long) or load_npz(string, bool, long) when the kind is known: they are typed and need no cast.An NpzFile owns a file handle and must be disposed.
Examples
var arr = (NDArray)np.load("data.npy");
if (np.load("data.npz") is NpzFile npz)
using (npz)
{ NDArray w = npz["weights"]; }
Remarks
Exceptions
- EOFError
The file is empty.
- FormatException
The content is not a .npy or .npz file, or is malformed; or it is a pickle and
allow_pickleis false (NumPy's texts).- NotSupportedException
A pickle that is not NumPy's pickle of a
StringDTypearray.- ValueError
Array can't be memory-mapped: Python objects in dtype.(a pickled file with ammap_mode).- UnicodeError
A
.npypickle whose text is not UTF-8: NumPy'sUnpickling a python object failed: UnicodeDecodeError(...)text (a ValueError, as in Python).
load(string, string, bool, bool, string, long)
Load an array or archive from a .npy or .npz file.
public static object load(string file, string mmap_mode = null, bool allow_pickle = false, bool fix_imports = true, string encoding = "ASCII", long max_header_size = 10000)
Parameters
filestringPath to the file. The type is detected from its magic bytes, not its extension.
mmap_modestringMemory-map mode for a
.npyfile:"r"/"readonly"(read-only),"r+"(read-write, flushed to disk) or"c"(copy-on-write, not flushed); null (default) reads the whole array into owned memory. Ignored for a.npzarchive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).allow_pickleboolWhether to trust the file. Default false, as in NumPy since 1.16.3: an object array is a Python pickle, and unpickling untrusted data can execute arbitrary code in NumPy. With true, NumSharp reads the one pickle it can represent — NumPy's pickle of a NEP 55
StringDTypearray, in a.npyfile, an.npzmember or a bare pickle file — without executing anything it names, and refuses every other pickle. Per NumPy it also liftsmax_header_size.fix_importsboolPresent for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.
encodingstringPresent for NumPy parity; validated but otherwise unused. Must be
"ASCII","latin1"or"bytes".max_header_sizelongReject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when
allow_pickleis true.
Returns
- object
An NDArray for a
.npyfile, or an NpzFile for a.npzarchive — mirroring NumPy, whose return type also depends on the content. Prefer load_npy(string, bool, long) or load_npz(string, bool, long) when the kind is known: they are typed and need no cast.An NpzFile owns a file handle and must be disposed.
Examples
var arr = (NDArray)np.load("data.npy");
if (np.load("data.npz") is NpzFile npz)
using (npz)
{ NDArray w = npz["weights"]; }
Remarks
Exceptions
- EOFError
The file is empty.
- FormatException
The content is not a .npy or .npz file, or is malformed; or it is a pickle and
allow_pickleis false (NumPy's texts).- NotSupportedException
A pickle that is not NumPy's pickle of a
StringDTypearray.- ValueError
Array can't be memory-mapped: Python objects in dtype.(a pickled file with ammap_mode).- UnicodeError
A
.npypickle whose text is not UTF-8: NumPy'sUnpickling a python object failed: UnicodeDecodeError(...)text (a ValueError, as in Python).
load_npy(byte[], bool, long)
Load a single array from an in-memory .npy image.
public static NDArray load_npy(byte[] bytes, bool allow_pickle = false, long max_header_size = 10000)
Parameters
bytesbyte[]allow_pickleboolWhether the file is trusted; see load(string, string, bool, bool, string, long).
max_header_sizelongReject headers larger than this.
Returns
Exceptions
- FormatException
The file is not a .npy file, or is malformed; or it holds a pickle (a
StringDTypearray) andallow_pickleis false.- NotSupportedException
A pickle that is not NumPy's pickle of a
StringDTypearray.- UnicodeError
A pickled text that is not UTF-8 (NumPy's
Unpickling a python object failedtext).
load_npy(Stream, bool, long)
Read one array from a stream positioned at a .npy magic string. The stream is left
just past that array's data, so successive calls read successively saved arrays.
public static NDArray load_npy(Stream file, bool allow_pickle = false, long max_header_size = 10000)
Parameters
fileStreamAn open, readable stream.
allow_pickleboolWhether the file is trusted.
max_header_sizelongReject headers larger than this.
Returns
Exceptions
- EOFError
The stream is already at its end.
load_npy(string, bool, long)
Load a single array from a .npy file — load(string, string, bool, bool, string, long)
without the cast.
public static NDArray load_npy(string file, bool allow_pickle = false, long max_header_size = 10000)
Parameters
filestringPath to a
.npyfile.allow_pickleboolWhether the file is trusted; see load(string, string, bool, bool, string, long).
max_header_sizelongReject headers larger than this.
Returns
Exceptions
- FormatException
The file is not a .npy file, or is malformed; or it holds a pickle (a
StringDTypearray) andallow_pickleis false.- NotSupportedException
A pickle that is not NumPy's pickle of a
StringDTypearray.- UnicodeError
A pickled text that is not UTF-8 (NumPy's
Unpickling a python object failedtext).
load_npz(byte[], bool, long)
Open a .npz archive from an in-memory image.
public static NpzFile load_npz(byte[] bytes, bool allow_pickle = false, long max_header_size = 10000)
Parameters
bytesbyte[]allow_pickleboolWhether members are trusted.
max_header_sizelongReject member headers larger than this.
Returns
- NpzFile
A lazily-loading, dictionary-like archive. It holds an open file handle — dispose it:
using var npz = np.load_npz("m.npz");
Exceptions
- FormatException
The file is not a ZIP archive.
load_npz(Stream, bool, bool, long)
Open a .npz archive over a stream.
public static NpzFile load_npz(Stream file, bool own_stream = false, bool allow_pickle = false, long max_header_size = 10000)
Parameters
fileStreamA readable, seekable stream.
own_streamboolWhen true, disposing the archive also disposes the stream.
allow_pickleboolWhether members are trusted.
max_header_sizelongReject member headers larger than this.
Returns
load_npz(string, bool, long)
Open a .npz archive — load(string, string, bool, bool, string, long)
without the cast.
public static NpzFile load_npz(string file, bool allow_pickle = false, long max_header_size = 10000)
Parameters
filestringPath to a
.npzarchive.allow_pickleboolWhether members are trusted.
max_header_sizelongReject member headers larger than this.
Returns
- NpzFile
A lazily-loading, dictionary-like archive. It holds an open file handle — dispose it:
using var npz = np.load_npz("m.npz");
Exceptions
- FormatException
The file is not a ZIP archive.
loadtxt(IEnumerable<string>, DType, object, string, object, int, int[], bool, int, string, int?, string)
Load data from a sequence of lines (NumPy's list or generator of str).
public static NDArray loadtxt(IEnumerable<string> lines, DType dtype = null, object comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, string encoding = null, int? max_rows = null, string quotechar = null)
Parameters
linesIEnumerable<string>The lines: each element is one line, as given — it may end in a newline, but a newline inside it (outside quotes) is NumPy's
Found an unquoted embedded newline within a single line of input.error, and a quoted field may continue into the next element.dtypeDTypeThe result's dtype (default float64): a numeric dtype, a fixed-width string dtype (
'U5','S'; an unsized class takes the longest field's width), or aStringDType('T',np.dtypes.StringDType(...)), which stores every field's text whole.commentsobjectWhat starts a comment (the rest of the line is ignored): a string (a Latin-1
byte[]and a char are one too), a sequence of them (string[], any IEnumerable; each is cut off at its first occurrence, in order), or null for none. Default"#". As in NumPy, a null element of a sequence keeps each line's first whitespace-separated word (line.split(None, 1)[0]), and an element of another type raises at the first line read.delimiterstringThe column separator, one character; null (default) splits on runs of whitespace and ignores leading whitespace.
convertersobjectPer-field parsers: a Func<T, TResult> for every column, or an IDictionary<TKey, TValue> mapping a column (negative counts from the end without
usecols; with it, a column is matched against theusecolsentries as given) to a parser. The parser's result is stored with the dtype's element setter (NumPy'sPyArray_Pack).skiprowsintSkip this many leading lines (blank lines and comments included; quotes are not honored while skipping).
usecolsint[]Which columns to read, in this order (negatives count from the end). Null reads all.
unpackboolTranspose the result, so its columns unpack as separate arrays.
ndminintThe minimum number of dimensions (0, 1 or 2); size-1 axes beyond it are squeezed.
encodingstringAs for a TextReader: only
"bytes"has an effect (a converter's input is the field's Latin-1 form).max_rowsint?Read at most this many data rows after
skiprows(blank and comment-only lines are not counted). Null reads all.quotecharstringThe quote character: inside a quoted field, delimiters, comments and newlines are data, and two quotes are one literal quote. Null (default) disables quoting.
Returns
- NDArray
The array:
(rows, cols), then squeezed tondmin(one row or one column gives a 1-D result, one value a 0-d one), transposed whenunpack.
Remarks
Parity with NumPy 2.4.2's np.loadtxt. NumPy's warnings (an input without data, an empty line under
max_rows) are not raised: NumSharp has no warnings channel.
https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
Exceptions
- ArgumentNullException
linesis null.- ValueError
NumPy's texts: an invalid
ndmin, a negativeskiprows/max_rows, an empty comment, a field that cannot be converted (could not convert string 'x' to float64 at row 0, column 1., the cause attached), a row with another number of columns, an invalid column index, a converter for a column that does not exist, an unquoted newline inside one line of a line-iterated input.- TypeError
NumPy's texts: a control character that is not one character or None, or that matches another (
The values for control characters 'quotechar' and 'delimiter' are incompatible), a newline as a control character, a comment sequence holding the delimiter, converters of another kind, a null converter in the dictionary,commentsthat are not iterable ('int' object is not iterable) or hold an element that is neither a string nor null (must be str or None, not int, at the first line read).- IndexError
A null comment element over an empty or whitespace-only line (
list index out of range, NumPy'sstr.split(None, 1)[0]).- TypeError
A null element (
non-string returned while reading data).- AttributeError
A null element when multiple or multi-character comments are stripped from each line first (NumPy's
_preprocess_commentsmeets it:'NoneType' object has no attribute 'split').
loadtxt(Stream, DType, object, string, object, int, int[], bool, int, string, int?, string)
Load data from an open byte Stream (NumPy's binary file object, io.BytesIO): read from the
current position and left open.
public static NDArray loadtxt(Stream stream, DType dtype = null, object comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, string encoding = null, int? max_rows = null, string quotechar = null)
Parameters
streamStreamThe bytes. They are iterated line by line as Python iterates a binary file — split after every
'\n', each line decoded on its own, no newline translation (a'\r'inside a line, outside quotes, is NumPy's embedded-newline error).dtypeDTypeThe result's dtype (default float64): a numeric dtype, a fixed-width string dtype (
'U5','S'; an unsized class takes the longest field's width), or aStringDType('T',np.dtypes.StringDType(...)), which stores every field's text whole.commentsobjectWhat starts a comment (the rest of the line is ignored): a string (a Latin-1
byte[]and a char are one too), a sequence of them (string[], any IEnumerable; each is cut off at its first occurrence, in order), or null for none. Default"#". As in NumPy, a null element of a sequence keeps each line's first whitespace-separated word (line.split(None, 1)[0]), and an element of another type raises at the first line read.delimiterstringThe column separator, one character; null (default) splits on runs of whitespace and ignores leading whitespace.
convertersobjectPer-field parsers: a Func<T, TResult> for every column, or an IDictionary<TKey, TValue> mapping a column (negative counts from the end without
usecols; with it, a column is matched against theusecolsentries as given) to a parser. The parser's result is stored with the dtype's element setter (NumPy'sPyArray_Pack).skiprowsintSkip this many leading lines (blank lines and comments included; quotes are not honored while skipping).
usecolsint[]Which columns to read, in this order (negatives count from the end). Null reads all.
unpackboolTranspose the result, so its columns unpack as separate arrays.
ndminintThe minimum number of dimensions (0, 1 or 2); size-1 axes beyond it are squeezed.
encodingstringThe encoding of the bytes (the codecs of the file-name overload). Null (and
"bytes") is Latin-1, NumPy's default for a binary file object (getattr(fname, 'encoding', 'latin1')): every byte is one character. NumPy decodes each line on its own as it reads it (bytes.decode: a BOM codec reads a BOM per line, native little-endian without one), so an unknown name raises LookupError at the first line, and a stream without lines never meets it.max_rowsint?Read at most this many data rows after
skiprows(blank and comment-only lines are not counted). Null reads all.quotecharstringThe quote character: inside a quoted field, delimiters, comments and newlines are data, and two quotes are one literal quote. Null (default) disables quoting.
Returns
- NDArray
The array:
(rows, cols), then squeezed tondmin(one row or one column gives a 1-D result, one value a 0-d one), transposed whenunpack.
Remarks
Parity with NumPy 2.4.2's np.loadtxt. NumPy's warnings (an input without data, an empty line under
max_rows) are not raised: NumSharp has no warnings channel.
https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
Exceptions
- ArgumentNullException
streamis null.- LookupError
An unknown or non-text
encoding, once the stream has a line.- NotSupportedException
A Python codec NumSharp does not implement, once the stream has a line.
- ValueError
NumPy's texts: an invalid
ndmin, a negativeskiprows/max_rows, an empty comment, a field that cannot be converted (could not convert string 'x' to float64 at row 0, column 1., the cause attached), a row with another number of columns, an invalid column index, a converter for a column that does not exist, an unquoted newline inside one line of a line-iterated input.- TypeError
NumPy's texts: a control character that is not one character or None, or that matches another (
The values for control characters 'quotechar' and 'delimiter' are incompatible), a newline as a control character, a comment sequence holding the delimiter, converters of another kind, a null converter in the dictionary,commentsthat are not iterable ('int' object is not iterable) or hold an element that is neither a string nor null (must be str or None, not int, at the first line read).- IndexError
A null comment element over an empty or whitespace-only line (
list index out of range, NumPy'sstr.split(None, 1)[0]).- UnicodeDecodeError
Bytes the encoding cannot decode.
loadtxt(TextReader, DType, object, string, object, int, int[], bool, int, string, int?, string)
Load data from an open TextReader (NumPy's in-memory text stream, io.StringIO): read from
the current position and left open.
public static NDArray loadtxt(TextReader reader, DType dtype = null, object comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, string encoding = null, int? max_rows = null, string quotechar = null)
Parameters
readerTextReaderThe text. It is iterated line by line as Python iterates
io.StringIO— split after every'\n', a'\r'left as data (outside quotes, NumPy's embedded-newline error).dtypeDTypeThe result's dtype (default float64): a numeric dtype, a fixed-width string dtype (
'U5','S'; an unsized class takes the longest field's width), or aStringDType('T',np.dtypes.StringDType(...)), which stores every field's text whole.commentsobjectWhat starts a comment (the rest of the line is ignored): a string (a Latin-1
byte[]and a char are one too), a sequence of them (string[], any IEnumerable; each is cut off at its first occurrence, in order), or null for none. Default"#". As in NumPy, a null element of a sequence keeps each line's first whitespace-separated word (line.split(None, 1)[0]), and an element of another type raises at the first line read.delimiterstringThe column separator, one character; null (default) splits on runs of whitespace and ignores leading whitespace.
convertersobjectPer-field parsers: a Func<T, TResult> for every column, or an IDictionary<TKey, TValue> mapping a column (negative counts from the end without
usecols; with it, a column is matched against theusecolsentries as given) to a parser. The parser's result is stored with the dtype's element setter (NumPy'sPyArray_Pack).skiprowsintSkip this many leading lines (blank lines and comments included; quotes are not honored while skipping).
usecolsint[]Which columns to read, in this order (negatives count from the end). Null reads all.
unpackboolTranspose the result, so its columns unpack as separate arrays.
ndminintThe minimum number of dimensions (0, 1 or 2); size-1 axes beyond it are squeezed.
encodingstringText needs no decoding, so only NumPy's
"bytes"has an effect: a converter's input is the field's Latin-1 form (a field holding a character pastU+00FFfails its conversion with NumPy's UnicodeEncodeError as the cause). Any other name is accepted and ignored, as NumPy ignores it for a text stream.max_rowsint?Read at most this many data rows after
skiprows(blank and comment-only lines are not counted). Null reads all.quotecharstringThe quote character: inside a quoted field, delimiters, comments and newlines are data, and two quotes are one literal quote. Null (default) disables quoting.
Returns
- NDArray
The array:
(rows, cols), then squeezed tondmin(one row or one column gives a 1-D result, one value a 0-d one), transposed whenunpack.
Remarks
Parity with NumPy 2.4.2's np.loadtxt. NumPy's warnings (an input without data, an empty line under
max_rows) are not raised: NumSharp has no warnings channel.
https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
Exceptions
- ArgumentNullException
readeris null.- ValueError
NumPy's texts: an invalid
ndmin, a negativeskiprows/max_rows, an empty comment, a field that cannot be converted (could not convert string 'x' to float64 at row 0, column 1., the cause attached), a row with another number of columns, an invalid column index, a converter for a column that does not exist, an unquoted newline inside one line of a line-iterated input.- TypeError
NumPy's texts: a control character that is not one character or None, or that matches another (
The values for control characters 'quotechar' and 'delimiter' are incompatible), a newline as a control character, a comment sequence holding the delimiter, converters of another kind, a null converter in the dictionary,commentsthat are not iterable ('int' object is not iterable) or hold an element that is neither a string nor null (must be str or None, not int, at the first line read).- IndexError
A null comment element over an empty or whitespace-only line (
list index out of range, NumPy'sstr.split(None, 1)[0]).
loadtxt(string, DType, object, string, object, int, int[], bool, int, string, int?, string)
Load data from a text file into an array (NumPy's np.loadtxt).
public static NDArray loadtxt(string fname, DType dtype = null, object comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, string encoding = null, int? max_rows = null, string quotechar = null)
Parameters
fnamestringPath to the file, found and opened as NumPy's
DataSourcedoes: when nothing has that name, the name with.bz2,.gz,.xzor.lzmaappended is tried, in that order; a name whose extension is exactly.gzis decompressed (.GZis plain text, as in NumPy). The file is read in text mode with universal newlines ("\r\n"and'\r'end lines too), so a quoted field may span lines.dtypeDTypeThe result's dtype (default float64): a numeric dtype, a fixed-width string dtype (
'U5','S'; an unsized class takes the longest field's width), or aStringDType('T',np.dtypes.StringDType(...)), which stores every field's text whole.commentsobjectWhat starts a comment (the rest of the line is ignored): a string (a Latin-1
byte[]and a char are one too), a sequence of them (string[], any IEnumerable; each is cut off at its first occurrence, in order), or null for none. Default"#". As in NumPy, a null element of a sequence keeps each line's first whitespace-separated word (line.split(None, 1)[0]), and an element of another type raises at the first line read.delimiterstringThe column separator, one character; null (default) splits on runs of whitespace and ignores leading whitespace.
convertersobjectPer-field parsers: a Func<T, TResult> for every column, or an IDictionary<TKey, TValue> mapping a column (negative counts from the end without
usecols; with it, a column is matched against theusecolsentries as given) to a parser. The parser's result is stored with the dtype's element setter (NumPy'sPyArray_Pack).skiprowsintSkip this many leading lines (blank lines and comments included; quotes are not honored while skipping).
usecolsint[]Which columns to read, in this order (negatives count from the end). Null reads all.
unpackboolTranspose the result, so its columns unpack as separate arrays.
ndminintThe minimum number of dimensions (0, 1 or 2); size-1 axes beyond it are squeezed.
encodingstringThe file's text encoding: any name Python's
codecs.lookupresolves (aliases included:"utf-16le","Windows-1252","L1") for UTF-8 (utf-8-sigtoo), UTF-16 and UTF-32 (with or without a BOM; the BOM forms require one, CPython'sUTF-16 stream does not start with BOM), Latin-1, ASCII and the single-byte code pages. Null (and NumPy's"bytes", and"locale") is UTF-8 here, NumPy's default on Linux and macOS (Windows NumPy uses the ANSI code page). Decoding is strict: undecodable bytes raise UnicodeDecodeError, with CPython's text and a position counted within the chunk NumPy's TextIOWrapper decodes.max_rowsint?Read at most this many data rows after
skiprows(blank and comment-only lines are not counted). Null reads all.quotecharstringThe quote character: inside a quoted field, delimiters, comments and newlines are data, and two quotes are one literal quote. Null (default) disables quoting.
Returns
- NDArray
The array:
(rows, cols), then squeezed tondmin(one row or one column gives a 1-D result, one value a 0-d one), transposed whenunpack.
Remarks
Parity with NumPy 2.4.2's np.loadtxt. NumPy's warnings (an input without data, an empty line under
max_rows) are not raised: NumSharp has no warnings channel.
https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
Exceptions
- ArgumentNullException
fnameis null.- ValueError
NumPy's texts: an invalid
ndmin, a negativeskiprows/max_rows, an empty comment, a field that cannot be converted (could not convert string 'x' to float64 at row 0, column 1., the cause attached), a row with another number of columns, an invalid column index, a converter for a column that does not exist, an unquoted newline inside one line of a line-iterated input.- TypeError
NumPy's texts: a control character that is not one character or None, or that matches another (
The values for control characters 'quotechar' and 'delimiter' are incompatible), a newline as a control character, a comment sequence holding the delimiter, converters of another kind, a null converter in the dictionary,commentsthat are not iterable ('int' object is not iterable) or hold an element that is neither a string nor null (must be str or None, not int, at the first line read).- IndexError
A null comment element over an empty or whitespace-only line (
list index out of range, NumPy'sstr.split(None, 1)[0]).- UnicodeDecodeError
Bytes the encoding cannot decode.
- FileNotFoundError
No file named
fname, nor any of its compressed variants (NumPy's<path> not found., no errno), reported before the encoding is looked up.- PermissionError
The file it found cannot be opened for reading (
[Errno 13] Permission denied).- LookupError
An unknown
encoding(CPython'sunknown encoding: name), or a codec that is not a text encoding ('base64' is not a text encoding; use codecs.open() to handle arbitrary codecs).- UnicodeError
A
utf-16/utf-32file that does not start with a BOM; theundefinedcodec.- NotSupportedException
A
.bz2,.xzor.lzmafile (.NET has no decompressor for them), or a Python codec NumSharp does not implement (the multi-byte CJK codecs,utf-7, …).
log(NDArray, NDArray, NDArray, DType)
Natural logarithm, element-wise.
Mirrors NumPy's ufunc signature: log(x, /, out=None, *, where=True, dtype=None).
public static NDArray log(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput value.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
The natural logarithm of each element (NaN for a negative real input), or
outitself when given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.log.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.log(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.log(x))</code>), as for every other ufunc.</p>
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.).
log10(NDArray, NDArray, NDArray, DType)
Return the base 10 logarithm of the input array, element-wise.
public static NDArray log10(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput value.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is), or null for a fresh result.
whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=); null is NumPy'swhere=True.dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=): the input must be same_kind-castable to it.
Returns
- NDArray
The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.log10.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.log10(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.log10(x))</code>), as for every other ufunc.</p>
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.).
log1p(NDArray, NDArray, NDArray, DType)
Return the natural logarithm of one plus the input array, element-wise.
Calculates log(1 + x).
public static NDArray log1p(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput value.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is), or null for a fresh result.
whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=); null is NumPy'swhere=True.dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=): the input must be same_kind-castable to it.
Returns
- NDArray
Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.log1p.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.log1p(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.log1p(x))</code>), as for every other ufunc.</p>
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.).
log2(NDArray, NDArray, NDArray, DType)
Base-2 logarithm of x.
public static NDArray log2(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput value.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is), or null for a fresh result.
whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=); null is NumPy'swhere=True.dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=): the input must be same_kind-castable to it.
Returns
- NDArray
Base-2 logarithm of x. This is a scalar if x is a scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.log2.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.log2(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.log2(x))</code>), as for every other ufunc.</p>
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.).
logaddexp(NDArray, NDArray, NDArray, NDArray, DType)
Logarithm of the sum of exponentiations of the inputs.
Calculates log(exp(x1) + exp(x2)), element-wise, without overflow/underflow —
the stable way to add probabilities held as logarithms.
Mirrors NumPy's ufunc signature: logaddexp(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray logaddexp(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array (a log-domain value).
x2NDArraySecond input array. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only; int/bool/complex raise NumPy's "No loop matching" error).
Returns
- NDArray
log(exp(x1) + exp(x2)). This is a scalar if both x1 and x2 are scalars.
Remarks
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.).
logaddexp2(NDArray, NDArray, NDArray, NDArray, DType)
Logarithm of the sum of exponentiations of the inputs in base-2.
Calculates log2(2x1 + 2x2), element-wise — the base-2 analogue of
logaddexp(NDArray, NDArray, NDArray, NDArray, DType), useful in machine
learning when the calculated probabilities are expressed in base-2.
Mirrors NumPy's ufunc signature: logaddexp2(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray logaddexp2(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array (a log2-domain value).
x2NDArraySecond input array. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only).
Returns
- NDArray
log2(2x1 + 2x2). This is a scalar if both x1 and x2 are scalars.
Remarks
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.).
logical_and(NDArray, NDArray, NDArray, NDArray, DType)
Compute the truth value of x1 AND x2 element-wise.
Mirrors NumPy's ufunc signature: logical_and(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray logical_and(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array (any dtype; reduced to its truth value).
x2NDArrayInput array (any dtype; reduced to its truth value).
outNDArrayA location into which the result is stored; any numeric dtype (bool casts same_kind to all of them, True→1); returned as-is. The result shape is set by broadcasting.
whereNDArrayBoolean mask: only mask-true elements are written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): logical ufuncs have bool-output loops only, so any non-bool request raises the no-loop TypeError.
Returns
- NDArray
The element-wise AND of the operands' truth values (bool, or
out). Anumpy.char.chararrayinput gives a chararray VIEW of a text result (NumPy'sarray_wrap), a plain array of a result of another dtype; a chararrayoutcomes back as a new chararray view of it.
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).- ValueError
A read-only
out.- IncorrectTypeException
A non-bool
dtype(NumPy's no-loop text).- TypeError
A detailed or non-legacy
dtypedescriptor, or a text call NumPy's string loop refuses.- SystemError
A
Uoperand holding a unit above U+10FFFF (NumPy's bool cast of the text).- TypeError
An
outthe bool result cannot be cast into.- ArgumentException
A
wherethat is not bool, or a mask oroutthat does not broadcast with the operands.- IncorrectShapeException
Operands that do not broadcast together.
logical_not(NDArray, NDArray, NDArray, DType)
Compute the truth value of NOT x element-wise.
Mirrors NumPy's ufunc signature: logical_not(x, /, out=None, *, where=True, dtype=None).
public static NDArray logical_not(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array (any dtype). Logical NOT is applied to its truth value: nonzero→False, zero→True. A NaN is truthy (so logical_not(NaN)→False, matching
x == 0).outNDArrayA location into which the result is stored; any numeric dtype; returned as-is.
whereNDArrayBoolean mask: only mask-true elements are written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): non-bool raises the no-loop TypeError.
Returns
- NDArray
The element-wise NOT of
x's truth values (bool, orout).
Remarks
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.).- ValueError
A read-only
out.- IncorrectTypeException
A non-bool
dtype(NumPy's no-loop text).- TypeError
A text operand (no string loop in NumPy), or a detailed or non-legacy
dtypedescriptor.- TypeError
An
outthe bool result cannot be cast into, or a fixed-width text operand underdtype=bool(NumPy's input-cast refusal).- ArgumentException
A
wherethat is not bool, or a mask oroutthat does not broadcast with the operand.
logical_or(NDArray, NDArray, NDArray, NDArray, DType)
Compute the truth value of x1 OR x2 element-wise.
Mirrors NumPy's ufunc signature: logical_or(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray logical_or(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array (any dtype; reduced to its truth value).
x2NDArrayInput array (any dtype; reduced to its truth value).
outNDArrayA location into which the result is stored; any numeric dtype; returned as-is.
whereNDArrayBoolean mask: only mask-true elements are written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): non-bool raises the no-loop TypeError.
Returns
- NDArray
The element-wise OR of the operands' truth values (bool, or
out). Anumpy.char.chararrayinput gives a chararray VIEW of a text result (NumPy'sarray_wrap), a plain array of a result of another dtype; a chararrayoutcomes back as a new chararray view of it.
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).- ValueError
A read-only
out.- IncorrectTypeException
A non-bool
dtype(NumPy's no-loop text).- TypeError
A detailed or non-legacy
dtypedescriptor, or a text call NumPy's string loop refuses.- SystemError
A
Uoperand holding a unit above U+10FFFF.- TypeError
An
outthe bool result cannot be cast into.- ArgumentException
A
wherethat is not bool, or a mask oroutthat does not broadcast with the operands.- IncorrectShapeException
Operands that do not broadcast together.
logical_xor(NDArray, NDArray, NDArray, NDArray, DType)
Compute the truth value of x1 XOR x2 element-wise.
Mirrors NumPy's ufunc signature: logical_xor(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray logical_xor(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array (any dtype; reduced to its truth value).
x2NDArrayInput array (any dtype; reduced to its truth value).
outNDArrayA location into which the result is stored; any numeric dtype; returned as-is.
whereNDArrayBoolean mask: only mask-true elements are written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): non-bool raises the no-loop TypeError.
Returns
- NDArray
The element-wise XOR of the operands' truth values (bool, or
out). Anumpy.char.chararrayinput gives a chararray VIEW of a text result (NumPy'sarray_wrap), a plain array of a result of another dtype; a chararrayoutcomes back as a new chararray view of it.
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).- ValueError
A read-only
out.- IncorrectTypeException
A non-bool
dtype(NumPy's no-loop text).- TypeError
A detailed or non-legacy
dtypedescriptor, or a text call NumPy's string loop refuses.- SystemError
A
Uoperand holding a unit above U+10FFFF.- TypeError
An
outthe bool result cannot be cast into.- ArgumentException
A
wherethat is not bool, or a mask oroutthat does not broadcast with the operands.- IncorrectShapeException
Operands that do not broadcast together.
logspace(double, double, long, bool, double, DType, int)
Return numbers spaced evenly on a log scale.
In linear space, the sequence starts at base ** start and ends with base ** stop
(see endpoint). Equivalent to power(base, linspace(start, stop, num, endpoint)).
public static NDArray logspace(double start, double stop, long num = 50, bool endpoint = true, double @base = 10, DType dtype = null, int axis = 0)
Parameters
startdoublebase ** startis the starting value of the sequence.stopdoublebase ** stopis the final value of the sequence, unlessendpointis False. In that casenum + 1values are spaced over the interval in log-space, of which all but the last are returned (so the step size changes whenendpointis False).numlongNumber of samples to generate. Default 50. Must be non-negative.
endpointboolIf True (default)
stopis the last sample; otherwise it is excluded.basedoubleThe base of the log space (default 10.0). The step between the elements in
log_base(samples)is uniform. A negative base with fractional exponents yields NaN (real power of a negative base), matching NumPy.dtypeDTypeThe dtype of the output — one descriptor parameter, like NumPy's
dtype=: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. If null (default) the result is float64. The computation ALWAYS runs in float64 and is then cast todtype— so an integer dtype TRUNCATES toward zero (NumPy'spower(...).astype(dtype)), unlike linspace(NDArray, NDArray, long, bool, DType, int, string) which floors.axisintThe axis in the result to store the samples. Relevant only for array-like inputs, which NumSharp's scalar
logspacedoes not take, so it is a no-op here — but it is still validated against the 1-D output: only0and-1are accepted (NumPymoveaxisdestination), anything else raises AxisError with NumPy's verbatim "destination:" message.
Returns
- NDArray
A 1-D array of
numsamples, equally spaced on a log scale.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.logspace.html
<p>One count type since API-parity batch 6: an <code>int</code> converts to <code>long</code> (the <code>int</code> forms,
which only widened, are gone).</p>
Exceptions
- ValueError
If
numis negative (NumPy's ValueError).- AxisError
If
axisis neither 0 nor -1 (out of bounds for the 1-D output).
mask_indices(int, Func<NDArray, int, NDArray>, int)
Return the indices to access (n, n) arrays, given a masking function.
public static NDArray<long>[] mask_indices(int n, Func<NDArray, int, NDArray> mask_func, int k = 0)
Parameters
nintThe returned indices will be valid to access arrays of shape
(n, n).mask_funcFunc<NDArray, int, NDArray>A function whose call signature is
(arr, k)and which returnsn-by-nmasked arrays — e.g. triu(NDArray, int) or tril(NDArray, int).kintAn optional argument passed through to
mask_func.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.mask_indices.html
The returned arity follows mask_func's output rank, not
n: passing diag(NDArray, int) — which reduces a 2-D input to its 1-D
diagonal — yields a single index array, matching NumPy (probed).
It stays a facade, NumPy's three statements here: the callback's result, of whatever class the callback
returns, goes through np.not_equal and np.nonzero, whose class rules NumPy's a != 0 and
nonzero(a) apply to that class (np.apply_over_axes keeps its statements for the same reason).
Exceptions
- ArgumentNullException
mask_funcis null.
matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char)
Matrix product of two arrays — the gufunc (n?,k),(k,m?)->(n?,m?), with NumPy's
full keyword surface.
public static NDArray matmul(NDArray x1, NDArray x2, NDArray @out = null, int[][] axes = null, int? axis = null, bool? keepdims = null, DType dtype = null, string casting = "same_kind", char order = 'K')
Parameters
x1NDArrayLhs input array, scalars not allowed.
x2NDArrayRhs input array, scalars not allowed.
outNDArrayWhere to deposit the answer; returned as-is when given. Like a ufunc's
out(and unlike dot(NDArray, NDArray, NDArray)'s strict one) it may be strided and takes a cast from the product dtype undercasting.axesint[][]Which axes carry the core dimensions, per operand:
{x1, x2, out}. A 2-D operand names TWO axes, a 1-D operand ONE (its optional core dim is absent); the output entry may be omitted only for the 1-D·1-D product, whose result has no core axes. Cannot be combined withaxis.axisint?Present for signature parity only. NumPy raises
TypeErrorfor any value, becausematmul's signature has three DISTINCT core dimensions — useaxes.keepdimsbool?Present for signature parity only. NumPy raises
TypeErrorfor ANY value (True OR False), because its output has core dimensions. Modelled with abool?sentinel so that, like NumPy'snp._NoValuedefault, an explicitfalsealso rejects.dtypeDTypeSelects the LOOP: the product runs at this dtype, not merely the result.
castingstringCasting rule (default
"same_kind", the ufunc default) gating BOTH the input→loop cast adtypeforces and the product→outcast.ordercharMemory layout of the result —
'C','F','A'or'K', in either case (NumPy's order converter).
Returns
- NDArray
The matrix product, or
outwhen one is given (a textoutreceives each product as its scalar'sstr()).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.matmul.html
The product itself is unchanged — TensorEngine.Matmul, which routes
float32/float64/complex128 through OpenBLAS when NumSharp.Interop.OpenBLAS is
referenced (byte-identical to NumPy) and through the managed GEMM otherwise. A
dtype request is applied by casting the operands to that dtype BEFORE
the product, so the loop — and thus the backend route — follows it.
Like the five sibling product gufuncs, NumPy's remaining ufunc keywords subok and
signature are not modelled (signature is what dtype
does; subok concerns ndarray subclasses NumSharp does not have). A
out with a wrong CORE dim reports NumPy's verbatim core-dimension
message; extra leading LOOP dims broadcast (replicating the product, as NumPy does), and
a loop-dimension mismatch raises the ValueError texts of NumPy's gufunc iterator, before the
product runs (GufuncGuard.CheckLoopBroadcast).
The result is NumPy's output object: a fresh array that owns its data, its loop axes in the
inputs' K order and its core axes innermost (with order 'K'), the C or F
order of the iterator's axes otherwise, remapped by axes; two vectors give
the 0-d stand-in of NumPy's scalar (an owner, read-only).
The whole call is the engine member
TensorEngine.Matmul(x1, x2, out, axes, axis, keepdims, dtype, casting, order) since the np-layer
dtype plan's P2; this function's woven subclass path answers for a numpy.matrix operand.
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.).- TypeError
Text operands or a string
dtype(no matmul loop),keepdimsoraxis(NumPy's matmul refusals); a nullcasting(casting must be str, not NoneType).- ValueError
An
orderletter or acastingname NumPy refuses, with its texts.- INumSharpException
A read-only
out(NumPy's ValueError "output array is read-only").- TypeError
A cast
castingrefuses (NumPy's UFuncTypeError text).- NullReferenceException
x1orx2is null.
matrix(NDArray, DType, bool)
NumPy's np.matrix(data, dtype=None, copy=True): builds an NDMatrix — a
two-dimensional array whose * is the matrix product — from an array. Use
asmatrix(NDArray, DType) when a view is enough; this call copies by default.
public static NDMatrix matrix(NDArray data, DType dtype = null, bool copy = true)
Parameters
dataNDArrayThe array. Zero axes become
(1, 1), one axis a row(1, N); more than two axes are allowed only when all but two have length 1.dtypeDTypeThe dtype of the matrix, or
nullto keep the dtype ofdata.copyboolfalsereturns a view ofdata(ordataitself when it is a matrix) if no dtype conversion is needed.
Returns
- NDMatrix
The matrix. With
copyit owns its data in C order.
Remarks
NumPy calls the matrix class "not the recommended way to represent matrices" and plans to remove it; it exists here so that code written against it ports. See NDMatrix for how the matrix semantics bind in C#.
A C# number passed directly (np.matrix(5)) binds this overload as a 0-d array of its C#
type and gives a (1, 1) matrix (int32 for an int, where NumPy's Python int is
int64).
https://numpy.org/doc/stable/reference/generated/numpy.matrix.html
Exceptions
- ArgumentNullException
dataisnull.- ValueError
More than two axes of
dataare longer than 1 (shape too large to be a matrix.).- IncorrectShapeException
datahas more than two axes and one of extent 0.
matrix(Array, DType, bool)
NumPy's np.matrix(data) for a C# array: a typed array of a NumSharp dtype
(double[,], int[]) is converted like np.array; any other array
(object[], a jagged double[][], an NDArray[]) is a Python list and is coerced by
NumPy's sequence rules.
public static NDMatrix matrix(Array data, DType dtype = null, bool copy = true)
Parameters
dataArrayThe array, with at most two axes after conversion.
dtypeDTypeThe dtype, or
nullfor the element type (a typed array) or NumPy's discovered dtype (a list: C# integers are int64, as Python ints are).copyboolAccepted for signature parity; a C# array is always copied into new memory.
Returns
- NDMatrix
A new matrix. Its
flags.owndatais false, as in NumPy, where the matrix is a view of the arraynp.arraybuilt.
Remarks
Exceptions
- ArgumentNullException
dataisnull.- ValueError
More than two axes (
matrix must be 2-dimensional), or a ragged list (NumPy's inhomogeneous-shape text).- NotSupportedException
A list holding strings,
nullor other objects.
matrix(object, DType, bool)
NumPy's np.matrix(data) for any other value: a tuple or a collection (a Python sequence, nested
up to two levels), an NDArray or string held in an object reference, or
a boxed number.
public static NDMatrix matrix(object data, DType dtype = null, bool copy = true)
Parameters
dataobjectThe value.
dtypeDTypeThe dtype, or
nullfor the discovered one.copyboolRead for an NDArray only; every other value is converted into new memory.
Returns
- NDMatrix
The matrix.
Remarks
Exceptions
- ArgumentNullException
dataisnull(NumPy builds an object matrix holdingNone).- ValueError
More than two axes, a ragged sequence, or an array that cannot be a matrix.
- SyntaxError
A matrix literal with a token that is not Python syntax.
- NotSupportedException
Strings or other objects inside a sequence.
matrix(string, DType, bool)
NumPy's np.matrix("1 2; 3 4"): builds a matrix from a literal. Rows are separated by
;, columns by commas and/or white space; square brackets are ignored.
public static NDMatrix matrix(string data, DType dtype = null, bool copy = true)
Parameters
datastringThe literal. Each token is one Python literal: an integer in any base (
10,0x1F,1_000), a float (.5,1e3), a complex number (1+2j), orTrue/False.dtypeDTypeThe dtype, or
nullfor NumPy's discovered dtype: bool when every token is a bool, int64 for integers, float64 once a float appears, complex128 once a complex appears, and float64 for a literal without elements.copyboolAccepted for signature parity; a literal is always converted into new memory.
Returns
- NDMatrix
A new
(rows, columns)matrix;(1, 0)for an empty literal.
Remarks
Exceptions
- ArgumentNullException
dataisnull.- ValueError
Rows of different lengths (
Rows not the same size.), or a token that is Python but not a literal (nan,2*3).- SyntaxError
A token that is not Python syntax (
1L, a lone+).- NotSupportedException
A string,
Noneor...token, or an integer beyond uint64: NumPy's str / object dtypes.
matrix_transpose(NDArray)
Transposes a matrix (or a stack of matrices) x.
Swaps the two innermost dimensions, i.e. an array of shape (..., M, N) becomes (..., N, M).
Equivalent to np.swapaxes(x, -1, -2). This function is Array API compatible.
public static NDArray matrix_transpose(NDArray x)
Parameters
xNDArrayInput array having shape
(..., M, N)and whose two innermost dimensions formMxNmatrices.
Returns
- NDArray
An array containing the transpose for each matrix and having shape
(..., N, M). A view is returned whenever possible. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
Exceptions
- ArgumentException
If
xhas fewer than 2 dimensions.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
matvec(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char)
Matrix-vector product (NumPy 2.2) — the gufunc (m,n),(n)->(m), NumPy's
gemv route.
public static NDArray matvec(NDArray x1, NDArray x2, NDArray @out = null, int[][] axes = null, int? axis = null, bool keepdims = false, DType dtype = null, string casting = "same_kind", char order = 'K')
Parameters
x1NDArrayMatrix operand, at least 2-D. Leading axes broadcast.
x2NDArrayVector operand, at least 1-D. NOT conjugated.
outNDArrayWhere to deposit the answer. Returned as-is when given.
axesint[][]Which axes carry the core dimensions, per operand:
{(m,n), (n), (m)}. All THREE entries are required — the output has a core axis, so its entry cannot be omitted the way vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char)'s can.axisint?Present for signature parity only. NumPy raises
TypeErrorfor any value, because this signature's core dimensions are two DISTINCT ones — useaxes.keepdimsboolPresent for signature parity only. NumPy raises
TypeErrorwhen true, for the same reason.dtypeDTypeSelects the LOOP: computation runs at this dtype, not merely the result.
castingstringNumPy's
casting=: the rule each input's cast to the loop, and the answer's cast intoout, is checked under -no,equiv,safe,same_kind(the default) orunsafe.ordercharNumPy's
order=, the layout of an allocated result:'K'(the default: the loop axes in the inputs' memory order),'C','F', or'A'(F when both inputs are F-contiguous, else C); lowercase is accepted, and it is ignored without.
Returns
- NDArray
The matrix-vector products (the operands' loop axes broadcast together), or
outitself holding them.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.matvec.html
This differs from matmul(x1, x2) with a 1-D x2 in how it BROADCASTS:
matmul treats a 1-D second operand as a one-off shape promotion, while
matvec is a true gufunc whose vector operand carries its own leading axes.
Unlike vecmat(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char) it does not conjugate — the transformation, not the inner
product, is what this computes.
NumPy's subok and signature keywords are absent: subok concerns ndarray
subclasses, which the woven subclass path already decides, and signature is what
dtype does.
The whole call is the engine member TensorEngine.Matvec(x1, x2, out, axes, axis, keepdims, dtype, casting, order)
since the np-layer dtype plan's P2; this function's woven subclass path answers for a numpy.matrix operand.
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.); an operand with too few dimensions; core axes of different lengths; anaxeslist without three entries; loop axes that do not broadcast together, or a read-onlyoutor one the answer does not broadcast into (NumPy's gufunc iterator texts).- TypeError
axiswithaxes, or either given; adtypewith details beyond its class; text operands or a textdtype;keepdims.- AxisError
An
axesentry of the wrong length, or an axis out of range.- TypeError
An input cannot be cast to the loop, or the answer into
out, undercasting(NumPy's UFuncTypeError text:Cannot cast ufunc 'matvec' input 0 from dtype('int32') to dtype('float64') with casting rule 'no').- ValueError
A
castingorordername NumPy refuses (casting first).- IncorrectShapeException
Loop axes that do not broadcast.
- NullReferenceException
x1orx2is null.
max(NDArray, int, NDArray, bool, object, NDArray)
max(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axis as one int: the
overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray max(NDArray a, int axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates (use nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayThe array the result is written into and returned. It must have the result's shape (the keepdims shape with
keepdims); its dtype may differ — the loop runs in the promotion of (out,a), and the result is cast into it unsafely (a float64 maximum lands in a bool out asTrue). Footgun: a narrowing out is lossy DURING the reduction too, as in NumPy — each output's first element (or the initial value) is stored in out's dtype before the rest folds in, and the running value round-trips through it at every buffer fill (np.max(int16 [300, 100], out=int8)is 100). Footgun: this is the THIRD positional parameter, as in NumPy, sonp.max(a, 1, true)passes the bool as out and raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions, so the result broadcasts against
a.initialobjectThe value every output starts from, converted into the loop dtype the way NumPy's element setter converts a Python value: a C# integer is a Python int (range-checked, never wrapped), a C#
double/floata Python float (truncated into an integer loop), a 0-d NDArray is cast. It makes an empty reduction valid (the result is the value) and is REQUIRED withwhere.nullis NumPy'sNone: no initial value.whereNDArrayA bool mask broadcast against
a: only the selected elements are reduced; an output with none selected keepsinitial. The C# literals are NumPy's Python bools:true(which converts to a 0-d array) is NumPy's defaultwhere=True, no mask at all, andfalseselects nothing (it needsinitial). Footgun: a 0-d bool ARRAY holding true is read the same way, where NumPy treatsnp.array(True)as a mask that needsinitial(withinitialboth give NumPy's result).nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype — 0-d (NumPy's read-only scalar) for a flat reduction withoutkeepdims. Anumpy.matrixoperand gets the matrix method's answer: the scalar without an axis, else a row(1, N)or a column(N, 1); with a matrixout, that out along an axis and a copy of its element without one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.max.html. There is no dtype=: NumPy's np.max has
none. A flat result is a 0-d array; read it as a C# value with a cast ((double)np.max(a)).
Exceptions
- TypeError
outis a C# scalar converted to a 0-d array (a bool, number, string, Half orcharliteral, as innp.max(a, 1, true)): NumPy's "return arrays must be of ArrayType", raised before any other argument is looked at. Also:initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(NumPy calls the matrix method, which has none of them; the first one passed, in that order, ismatrix.max() got an unexpected keyword argument 'initial'), raised before anything is computed.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out: NumPy's matrix method stores the maxima into it, then fails onout._collapse('numpy.ndarray' object has no attribute '_collapse'), so the out holds the values when this is raised.- ValueError
A read-only or misshapen
out; a mask with more axes thana;wherewithoutinitial("reduction operation 'maximum' does not have an identity, so to use a where mask one has to specify 'initial'"); an empty reduced axis withoutinitial("zero-size array to reduction operation maximum which has no identity"); an unconvertibleinitial(a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast againsta(NumPy's "remapped shapes" text).- OverflowError
initialdoes not fit an integer loop ("Python integer 1000 out of bounds for int8").- ArgumentNullException
ais null.
max(NDArray, int[], NDArray, bool, object, NDArray)
max(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static NDArray max(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates (use nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayThe array the result is written into and returned. It must have the result's shape (the keepdims shape with
keepdims); its dtype may differ — the loop runs in the promotion of (out,a), and the result is cast into it unsafely (a float64 maximum lands in a bool out asTrue). Footgun: a narrowing out is lossy DURING the reduction too, as in NumPy — each output's first element (or the initial value) is stored in out's dtype before the rest folds in, and the running value round-trips through it at every buffer fill (np.max(int16 [300, 100], out=int8)is 100). Footgun: this is the THIRD positional parameter, as in NumPy, sonp.max(a, 1, true)passes the bool as out and raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions, so the result broadcasts against
a.initialobjectThe value every output starts from, converted into the loop dtype the way NumPy's element setter converts a Python value: a C# integer is a Python int (range-checked, never wrapped), a C#
double/floata Python float (truncated into an integer loop), a 0-d NDArray is cast. It makes an empty reduction valid (the result is the value) and is REQUIRED withwhere.nullis NumPy'sNone: no initial value.whereNDArrayA bool mask broadcast against
a: only the selected elements are reduced; an output with none selected keepsinitial. The C# literals are NumPy's Python bools:true(which converts to a 0-d array) is NumPy's defaultwhere=True, no mask at all, andfalseselects nothing (it needsinitial). Footgun: a 0-d bool ARRAY holding true is read the same way, where NumPy treatsnp.array(True)as a mask that needsinitial(withinitialboth give NumPy's result).nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype — 0-d (NumPy's read-only scalar) for a flat reduction withoutkeepdims. Anumpy.matrixoperand gets the matrix method's answer: the scalar without an axis, else a row(1, N)or a column(N, 1); with a matrixout, that out along an axis and a copy of its element without one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.max.html. There is no dtype=: NumPy's np.max has
none. A flat result is a 0-d array; read it as a C# value with a cast ((double)np.max(a)).
Exceptions
- TypeError
outis a C# scalar converted to a 0-d array (a bool, number, string, Half orcharliteral, as innp.max(a, 1, true)): NumPy's "return arrays must be of ArrayType", raised before any other argument is looked at. Also:initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(NumPy calls the matrix method, which has none of them; the first one passed, in that order, ismatrix.max() got an unexpected keyword argument 'initial'), raised before anything is computed.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out: NumPy's matrix method stores the maxima into it, then fails onout._collapse('numpy.ndarray' object has no attribute '_collapse'), so the out holds the values when this is raised.- ValueError
A read-only or misshapen
out; a mask with more axes thana;wherewithoutinitial("reduction operation 'maximum' does not have an identity, so to use a where mask one has to specify 'initial'"); an empty reduced axis withoutinitial("zero-size array to reduction operation maximum which has no identity"); an unconvertibleinitial(a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast againsta(NumPy's "remapped shapes" text).- OverflowError
initialdoes not fit an integer loop ("Python integer 1000 out of bounds for int8").- ArgumentNullException
ais null.
max(NDArray, NDAxis?, NDArray, bool, object, NDArray)
Return the maximum of an array or the maximum along an axis — NumPy's np.max(a, axis=None, out=None,
keepdims=<no value>, initial=<no value>, where=<no value>), i.e.
np.maximum.reduce(a, axis, out=out, keepdims=keepdims, initial=initial, where=where). This is the only
overload: NumPy's whole signature, with NumPy's names, order and defaults.
public static NDArray max(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates (use nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).
axisNDAxis?The axis to reduce (negative counts from the end);
nullreduces every axis. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).outNDArrayThe array the result is written into and returned. It must have the result's shape (the keepdims shape with
keepdims); its dtype may differ — the loop runs in the promotion of (out,a), and the result is cast into it unsafely (a float64 maximum lands in a bool out asTrue). Footgun: a narrowing out is lossy DURING the reduction too, as in NumPy — each output's first element (or the initial value) is stored in out's dtype before the rest folds in, and the running value round-trips through it at every buffer fill (np.max(int16 [300, 100], out=int8)is 100). Footgun: this is the THIRD positional parameter, as in NumPy, sonp.max(a, 1, true)passes the bool as out and raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions, so the result broadcasts against
a.initialobjectThe value every output starts from, converted into the loop dtype the way NumPy's element setter converts a Python value: a C# integer is a Python int (range-checked, never wrapped), a C#
double/floata Python float (truncated into an integer loop), a 0-d NDArray is cast. It makes an empty reduction valid (the result is the value) and is REQUIRED withwhere.nullis NumPy'sNone: no initial value.whereNDArrayA bool mask broadcast against
a: only the selected elements are reduced; an output with none selected keepsinitial. The C# literals are NumPy's Python bools:true(which converts to a 0-d array) is NumPy's defaultwhere=True, no mask at all, andfalseselects nothing (it needsinitial). Footgun: a 0-d bool ARRAY holding true is read the same way, where NumPy treatsnp.array(True)as a mask that needsinitial(withinitialboth give NumPy's result).nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype — 0-d (NumPy's read-only scalar) for a flat reduction withoutkeepdims. Anumpy.matrixoperand gets the matrix method's answer: the scalar without an axis, else a row(1, N)or a column(N, 1); with a matrixout, that out along an axis and a copy of its element without one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.max.html. There is no dtype=: NumPy's np.max has
none. A flat result is a 0-d array; read it as a C# value with a cast ((double)np.max(a)).
Exceptions
- TypeError
outis a C# scalar converted to a 0-d array (a bool, number, string, Half orcharliteral, as innp.max(a, 1, true)): NumPy's "return arrays must be of ArrayType", raised before any other argument is looked at. Also:initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(NumPy calls the matrix method, which has none of them; the first one passed, in that order, ismatrix.max() got an unexpected keyword argument 'initial'), raised before anything is computed.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out: NumPy's matrix method stores the maxima into it, then fails onout._collapse('numpy.ndarray' object has no attribute '_collapse'), so the out holds the values when this is raised.- ValueError
A read-only or misshapen
out; a mask with more axes thana;wherewithoutinitial("reduction operation 'maximum' does not have an identity, so to use a where mask one has to specify 'initial'"); an empty reduced axis withoutinitial("zero-size array to reduction operation maximum which has no identity"); an unconvertibleinitial(a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast againsta(NumPy's "remapped shapes" text).- OverflowError
initialdoes not fit an integer loop ("Python integer 1000 out of bounds for int8").- ArgumentNullException
ais null.
maximum(NDArray, NDArray, NDArray, NDArray, DType)
Element-wise maximum of array elements (NaN-PROPAGATING).
Compare two arrays and return a new array containing the element-wise maxima. If either
element being compared is a NaN the NaN is returned (both NaN → the first); for complex
NaNs a NaN in the real OR imaginary part counts, so NaNs propagate. Use
fmax(NDArray, NDArray, NDArray, NDArray, DType) to IGNORE NaNs instead.
Mirrors NumPy's ufunc signature: maximum(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray maximum(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst operand. If
x1.shape !=x2.shape they must broadcast to a common shape (the output shape).x2NDArraySecond operand. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=): it joins the broadcast without being stretched, must be same_kind-castable from the loop dtype, and is returned as-is (reference identity). A read-only/broadcast out is refused.
whereNDArrayBoolean mask (NumPy ufunc where=): only mask-true elements are computed/written; masked-off
outslots keep their prior contents. Must be a bool array (a non-bool mask raises NumPy's 'safe'-cast error).dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.
Returns
- NDArray
The element-wise maximum of
x1andx2(oroutwhen supplied). A scalar if both inputs are scalars.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.maximum.html
BREAKING: the third positional argument is now out (NumPy's order), not
dtype; pass dtype: by name. Every in-repo call form is unaffected — callers use
either a positional out or the dtype: keyword.
Exceptions
- TypeError
outcannot be same_kind-cast from the loop dtype (NumPy-verbatim text).- ArgumentException
whereis not bool, or the shapes do not broadcast (NumPy-verbatim texts).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
maximum_sctype(NPTypeCode)
Return the scalar type of highest precision of the same kind as the input — NumPy 1.x's
np.maximum_sctype(t). Kept on purpose, so code written against NumPy 1.x compiles and runs unchanged,
although NumPy 2.0 removed it (AttributeError: ). New code names the dtype it wants.np.maximum_sctype was removed in the NumPy 2.0 release. Use
a specific dtype instead. You should avoid relying on any implicit mechanism and select the largest dtype of a
kind explicitly in the code.
public static DType maximum_sctype(NPTypeCode t)
Parameters
tNPTypeCodeThe input scalar type; a DType such as
np.int32converts implicitly.
Returns
- DType
The highest precision type of the same kind.
Examples
np.maximum_sctype(NPTypeCode.Int32) // Int64
np.maximum_sctype(NPTypeCode.Single) // Double (or Decimal)
Remarks
https://numpy.org/doc/1.26/reference/generated/numpy.maximum_sctype.html
Uses NPTypeHierarchy for consistent type categorization across all typing functions.
Signed integers give int64, unsigned integers (and Char) uint64, float16 / float32 /
float64 give float64, and bool, complex128 and decimal give themselves. NumPy 1.x gave np.longdouble for a
float and np.clongdouble for a complex: the same float64 / complex128 on Windows, 16-byte extended types on
Linux, which NumSharp does not have.
may_share_memory(NDArray, NDArray, long)
Determine whether two arrays MIGHT share memory — a fast, CONSERVATIVE bounds check by default.
public static bool may_share_memory(NDArray a, NDArray b, long max_work = 0)
Parameters
aNDArrayFirst array (any layout; a
nullreference shares nothing).bNDArraySecond array, under the same rules as
a.max_worklongEffort cap on the overlap solver, mirroring NumPy's
max_work:0(the default) checks only the byte bounds — cheap and never raises;-1/-2solve the collision exactly; a positive value caps the candidate search. Values below-2are rejected.
Returns
- bool
truewhen the arrays share memory OR the query cannot be decided within the cap — afalseis therefore a GUARANTEE of no sharing, while atrueis only "possibly".
Remarks
Unlike shares_memory(NDArray, NDArray, long) this NEVER raises for the undecided
or overflow outcomes: it resolves both to a conservative true ("might share"), which is
why the default max_work: 0 is safe — a mere bounds overlap already answers "true"
without invoking the expensive exact solver. Use this as a cheap precondition (as the library
itself does before overlap-sensitive writes); reach for shares_memory only when a
precise yes/no is required. Mirrors numpy.may_share_memory(a, b, /, max_work=0)
(NumPy 2.4.2).
https://numpy.org/doc/stable/reference/generated/numpy.may_share_memory.html
Exceptions
- ValueError
max_workis less than-2.- RuntimeError
The solver reported an internal error (does not occur for valid inputs).
mean(NDArray, int, DType, NDArray, bool, NDArray)
mean(NDArray, NDAxis?, DType, NDArray, bool, NDArray) with the axis as one int: the
overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray mean(NDArray a, int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose mean is desired.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypeThe dtype the sum is computed in and the mean returned in.
nullis NumPy's default: float64 for bool and integer input, float32 for float16 (with a float16 result), the input's own dtype otherwise.outNDArrayThe array the mean is written into and returned (the result's shape). NumPy stores the SUM into it and divides it in place, both with an unsafe cast, so an integer out holds truncated values. Footgun: the FOURTH positional parameter, as in NumPy; write
keepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask broadcast against
a: each output averages its selected elements only (divided by their count, so an output with none selected is NaN in a float loop). The C#trueliteral is NumPy's default.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis withoutkeepdims.
Remarks
Exceptions
- ArgumentNullException
ais null.- AxisError
axisis out of bounds.- ValueError
A read-only or misshapen
out, or a text out's missing division. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- IncorrectShapeException
outorwheredoes not broadcast.- TypeError
A C# scalar passed as
out; NumPy's text refusals; anumpy.matrixoperand withkeepdimsorwhere(matrix.mean() got an unexpected keyword argument 'keepdims').- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
mean(NDArray, int[], DType, NDArray, bool, NDArray)
mean(NDArray, NDAxis?, DType, NDArray, bool, NDArray) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static NDArray mean(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose mean is desired.
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypeThe dtype the sum is computed in and the mean returned in.
nullis NumPy's default: float64 for bool and integer input, float32 for float16 (with a float16 result), the input's own dtype otherwise.outNDArrayThe array the mean is written into and returned (the result's shape). NumPy stores the SUM into it and divides it in place, both with an unsafe cast, so an integer out holds truncated values. Footgun: the FOURTH positional parameter, as in NumPy; write
keepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask broadcast against
a: each output averages its selected elements only (divided by their count, so an output with none selected is NaN in a float loop). The C#trueliteral is NumPy's default.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis withoutkeepdims.
Remarks
Exceptions
- ArgumentNullException
ais null.- AxisError
axisis out of bounds.- ValueError
A read-only or misshapen
out, or a text out's missing division. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- IncorrectShapeException
outorwheredoes not broadcast.- TypeError
A C# scalar passed as
out; NumPy's text refusals; anumpy.matrixoperand withkeepdimsorwhere(matrix.mean() got an unexpected keyword argument 'keepdims').- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
mean(NDArray, NDAxis?, DType, NDArray, bool, NDArray)
Compute the arithmetic mean along the specified axis — NumPy's np.mean(a, axis=None, dtype=None, out=None,
keepdims=<no value>, *, where=<no value>) (_methods._mean): the sum divided by the count of
the summed elements. This is the only overload: NumPy's whole signature, with NumPy's names, order and
defaults.
public static NDArray mean(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose mean is desired.
axisNDAxis?The axis to average over (negative counts from the end);
nullaverages every element. Unlike np.sum, a 0-d array takes no axis (np.mean normalizes it first), unlesswhereis a mask. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypeThe dtype the sum is computed in and the mean returned in.
nullis NumPy's default: float64 for bool and integer input, float32 for float16 (with a float16 result), the input's own dtype otherwise.outNDArrayThe array the mean is written into and returned (the result's shape). NumPy stores the SUM into it and divides it in place, both with an unsafe cast, so an integer out holds truncated values. Footgun: the FOURTH positional parameter, as in NumPy; write
keepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask broadcast against
a: each output averages its selected elements only (divided by their count, so an output with none selected is NaN in a float loop). The C#trueliteral is NumPy's default.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis withoutkeepdims.
Remarks
Exceptions
- ArgumentNullException
ais null.- AxisError
axisis out of bounds.- ValueError
A read-only or misshapen
out, or a text out's missing division. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- IncorrectShapeException
outorwheredoes not broadcast.- TypeError
A C# scalar passed as
out; NumPy's text refusals; anumpy.matrixoperand withkeepdimsorwhere(matrix.mean() got an unexpected keyword argument 'keepdims').- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
median(NDArray, int, NDArray, bool, bool)
median(NDArray, NDAxis?, NDArray, bool, bool) with the axis as one int: the
overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray median(NDArray a, int axis, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
aNDArrayThe data (bool computes as its 0 / 1 values; text: see the exceptions).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
keepdimsboolWhether the reduced axes are kept with length one.
Returns
- NDArray
The median (NaN for an empty slice);
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.median.html
A StringDType median exists only when the middle elements are NaN-like NAs: NumPy's
np.float64(nan), a read-only 0-d float64 here.
NumPy's _ureduce turns an integer axis into a one-element tuple, so the engine member takes
the axes as an array; a tuple is merged into one axis before the partition, and the empty tuple reduces
nothing.
A numpy.matrix operand: an integer axis gives the matrix of NumPy's _collapse rule, the
class rule of a TUPLE sees no axis (the rule NumSharp's tuple overloads had) - NumPy's own tuple answers come
from matrix semantics inside its Python code (np.median(m, axis=(0, 1)) is a 1 x 1 matrix, axis=() reduces axis 1), which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
overloads, which made np.median(a, null) ambiguous (CS0121) and had no tuple literal.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range for
a(every axis is range-checked before the repeat check).- ValueError
A tuple names an axis twice (
repeated axis); anoutthat np.median's closingmean(part[indexer], out=out)refuses in its add.reduce prologue, before anything is computed: read-only (output array is read-only), of the wrong rank (output parameter for reduction operation add has the wrong number of dimensions: Found 2 but expected 1) or with a length-1 axis where the result is longer (parity QA-31).- IncorrectShapeException
An
outwhose axes do not broadcast with the result's: the prologue's iterator text over the partition's middle slice (operands could not be broadcast together with remapped shapes [original->remapped]: (3,)->(3) (1,4)), NumPy's ValueError. (Several reduced axes beside a kept axis of length 0 give an empty result since NumPy 2.5, whose_ureducemerges them into an explicit-product length; NumPy 2.4's -1 raised a reshape ValueError.)- TypeError
Text data or a text
out: NumPy's closingmeanrefuses (its verbatim text). A NEP 55StringDTypearray is sorted first (NumPy's partition of aStringDTypeline), then its mean's divide refuses the concatenated text.- ValueError
A
StringDTypearray: a None-like NA in a line of two or more elements (the sort'sCannot compare null that is not a nan-like value), an empty reduced axis (the mean's add.reduce has no identity) or a read-onlyout.- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the axes and keepdims' out are checked. Withoverwrite_inputand no axis NumPy partitions the text itself instead: its broadcast error for an even length other than 2 (IncorrectShapeException), else the closing mean's refusal of text.- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before the text refusals.
median(NDArray, int[], NDArray, bool, bool)
median(NDArray, NDAxis?, NDArray, bool, bool) with the axes as an int[]: the
overload an int[] binds, and a bare null too (null converts to int[] better than to
NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple
(new int[0] is ()).
public static NDArray median(NDArray a, int[] axis, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
aNDArrayThe data (bool computes as its 0 / 1 values; text: see the exceptions).
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
keepdimsboolWhether the reduced axes are kept with length one.
Returns
- NDArray
The median (NaN for an empty slice);
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.median.html
A StringDType median exists only when the middle elements are NaN-like NAs: NumPy's
np.float64(nan), a read-only 0-d float64 here.
NumPy's _ureduce turns an integer axis into a one-element tuple, so the engine member takes
the axes as an array; a tuple is merged into one axis before the partition, and the empty tuple reduces
nothing.
A numpy.matrix operand: an integer axis gives the matrix of NumPy's _collapse rule, the
class rule of a TUPLE sees no axis (the rule NumSharp's tuple overloads had) - NumPy's own tuple answers come
from matrix semantics inside its Python code (np.median(m, axis=(0, 1)) is a 1 x 1 matrix, axis=() reduces axis 1), which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
overloads, which made np.median(a, null) ambiguous (CS0121) and had no tuple literal.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range for
a(every axis is range-checked before the repeat check).- ValueError
A tuple names an axis twice (
repeated axis); anoutthat np.median's closingmean(part[indexer], out=out)refuses in its add.reduce prologue, before anything is computed: read-only (output array is read-only), of the wrong rank (output parameter for reduction operation add has the wrong number of dimensions: Found 2 but expected 1) or with a length-1 axis where the result is longer (parity QA-31).- IncorrectShapeException
An
outwhose axes do not broadcast with the result's: the prologue's iterator text over the partition's middle slice (operands could not be broadcast together with remapped shapes [original->remapped]: (3,)->(3) (1,4)), NumPy's ValueError. (Several reduced axes beside a kept axis of length 0 give an empty result since NumPy 2.5, whose_ureducemerges them into an explicit-product length; NumPy 2.4's -1 raised a reshape ValueError.)- TypeError
Text data or a text
out: NumPy's closingmeanrefuses (its verbatim text). A NEP 55StringDTypearray is sorted first (NumPy's partition of aStringDTypeline), then its mean's divide refuses the concatenated text.- ValueError
A
StringDTypearray: a None-like NA in a line of two or more elements (the sort'sCannot compare null that is not a nan-like value), an empty reduced axis (the mean's add.reduce has no identity) or a read-onlyout.- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the axes and keepdims' out are checked. Withoverwrite_inputand no axis NumPy partitions the text itself instead: its broadcast error for an even length other than 2 (IncorrectShapeException), else the closing mean's refusal of text.- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before the text refusals.
median(NDArray, NDAxis?, NDArray, bool, bool)
NumPy's np.median(a, axis=None, out=None, overwrite_input=False, keepdims=False): the median along the
given axes (of the flattened data by default). For an even-sized slice the median is the mean of the two
central values, (a+b)/2; for an odd-sized slice it is the single central value. This is NOT the same
code path as np.quantile(a, 0.5) — NumPy computes np.median via mean(part[middle]), which
disagrees with the quantile _lerp at q=0.5 by up to 1 ULP on ~10 % of inputs — so
medianMean: true is REQUIRED for bit-exact parity.
public static NDArray median(NDArray a, NDAxis? axis = null, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
aNDArrayThe data (bool computes as its 0 / 1 values; text: see the exceptions).
axisNDAxis?NumPy's
axis:null(None, the default) reduces the flattened data; one axis (negative counts from the end) or a tuple ((0, 2),new[] { 0, 2 }) reduces those axes, merged into one; the empty tuple reduces nothing.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
keepdimsboolWhether the reduced axes are kept with length one.
Returns
- NDArray
The median (NaN for an empty slice);
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.median.html
A StringDType median exists only when the middle elements are NaN-like NAs: NumPy's
np.float64(nan), a read-only 0-d float64 here.
NumPy's _ureduce turns an integer axis into a one-element tuple, so the engine member takes
the axes as an array; a tuple is merged into one axis before the partition, and the empty tuple reduces
nothing.
A numpy.matrix operand: an integer axis gives the matrix of NumPy's _collapse rule, the
class rule of a TUPLE sees no axis (the rule NumSharp's tuple overloads had) - NumPy's own tuple answers come
from matrix semantics inside its Python code (np.median(m, axis=(0, 1)) is a 1 x 1 matrix, axis=() reduces axis 1), which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
overloads, which made np.median(a, null) ambiguous (CS0121) and had no tuple literal.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range for
a(every axis is range-checked before the repeat check).- ValueError
A tuple names an axis twice (
repeated axis); anoutthat np.median's closingmean(part[indexer], out=out)refuses in its add.reduce prologue, before anything is computed: read-only (output array is read-only), of the wrong rank (output parameter for reduction operation add has the wrong number of dimensions: Found 2 but expected 1) or with a length-1 axis where the result is longer (parity QA-31).- IncorrectShapeException
An
outwhose axes do not broadcast with the result's: the prologue's iterator text over the partition's middle slice (operands could not be broadcast together with remapped shapes [original->remapped]: (3,)->(3) (1,4)), NumPy's ValueError. (Several reduced axes beside a kept axis of length 0 give an empty result since NumPy 2.5, whose_ureducemerges them into an explicit-product length; NumPy 2.4's -1 raised a reshape ValueError.)- TypeError
Text data or a text
out: NumPy's closingmeanrefuses (its verbatim text). A NEP 55StringDTypearray is sorted first (NumPy's partition of aStringDTypeline), then its mean's divide refuses the concatenated text.- ValueError
A
StringDTypearray: a None-like NA in a line of two or more elements (the sort'sCannot compare null that is not a nan-like value), an empty reduced axis (the mean's add.reduce has no identity) or a read-onlyout.- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the axes and keepdims' out are checked. Withoverwrite_inputand no axis NumPy partitions the text itself instead: its broadcast error for an even length other than 2 (IncorrectShapeException), else the closing mean's refusal of text.- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before the text refusals.
meshgrid(NDArray, NDArray, NDArray, string, bool, bool)
Return coordinate matrices from three coordinate vectors — see meshgrid(NDArray[], string, bool, bool).
public static np.MeshgridResult meshgrid(NDArray x1, NDArray x2, NDArray x3, string indexing = "xy", bool sparse = false, bool copy = true)
Parameters
Returns
meshgrid(NDArray, NDArray, string, bool, bool)
Return coordinate matrices from two coordinate vectors — see meshgrid(NDArray[], string, bool, bool).
public static np.MeshgridResult meshgrid(NDArray x1, NDArray x2, string indexing = "xy", bool sparse = false, bool copy = true)
Parameters
Returns
meshgrid(NDArray[], string, bool, bool)
Return a tuple of coordinate matrices from N coordinate vectors — make N-D coordinate arrays for vectorized evaluation of N-D fields over an N-D grid.
public static np.MeshgridResult meshgrid(NDArray[] xi, string indexing = "xy", bool sparse = false, bool copy = true)
Parameters
xiNDArray[]The coordinate vectors. Each is flattened to 1-D, so a higher-rank input is read in C-order. For the two- and three-vector cases the
x1, x2[, x3]overloads let them be passed directly (np.meshgrid(x, y)); use this overload for four or more.indexingstring"xy"(Cartesian, default) or"ij"(matrix). For two inputs of length M and N the outputs are(N, M)under"xy"and(M, N)under"ij"; the two conventions swap the first two axes. Has no effect for a single input.sparseboolIf true, grid
ikeeps the open-mesh shape(1, …, Ni, …, 1)instead of the full(N1, …, Nn)— these broadcast to the same dense result. Default false.copyboolIf true (default) each grid is an independent C-contiguous array. If false the dense grids are returned as broadcast VIEWS (non-contiguous, and multiple elements may alias one memory location — copy before writing).
Returns
- np.MeshgridResult
N grids as a np.MeshgridResult (NumPy's tuple): implicit to NDArray
[], deconstructable, and indexable. Each grid keeps its input's class, as NumPy's does: anumpy.matrixinput's grid is a matrix (the matrix finalize rule folding every reshape onto two axes, so three matrix rows give three 1 x N matrices), anumpy.char.chararrayinput's a chararray, a plain input's a plain array.
Examples
var (xx, yy) = np.meshgrid(np.arange(3), np.arange(2)); // xx,yy shape (2,3), 'xy'
var (i, j) = np.meshgrid(a, b, indexing: "ij"); // shape (len a, len b)
NDArray[] g = np.meshgrid(a, b, sparse: true); // (1,M) and (N,1)
Remarks
Port of NumPy 2.x numpy.meshgrid (numpy/lib/_function_base_impl.py). Each input
is reshaped to its open-mesh axis; "xy" then swaps the placement of the first two;
unless sparse the grids are broadcast to the full shape; unless
copy is false they are then materialized. Each grid PRESERVES its input's
dtype (grids are not promoted to a common type). The companion open-mesh builder is
ix_(params object[]); the indexing-notation forms are mgrid / ogrid.
https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html
Exceptions
- ArgumentNullException
xiis null, or one of its vectors is (the parameter is then namedxi[i], after the indexing check).- ValueError
indexingis neither"xy"nor"ij"(Valid values for); a matrix grid of more than two axes longer than 1 (indexingare 'xy' and 'ij'.shape too large to be a matrix.).- IncorrectShapeException
A matrix input's 1 x N open mesh does not broadcast against the higher-rank open meshes of plain inputs (broadcast_arrays'
shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (1, 3) and arg 2 with shape (1, 1, 4)., as in NumPy).
min(NDArray, int, NDArray, bool, object, NDArray)
min(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axis as one int: the
overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray min(NDArray a, int axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates (use nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayThe array the result is written into and returned (any dtype; a narrowing one is lossy, see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the third positional parameter, so
np.min(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer: the scalar without an axis, else a row or a column; with a matrixout, that out along an axis and a copy of its element without one.
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ..., the first one passed in that order).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('minimum' in the texts). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
min(NDArray, int[], NDArray, bool, object, NDArray)
min(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static NDArray min(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates (use nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayThe array the result is written into and returned (any dtype; a narrowing one is lossy, see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the third positional parameter, so
np.min(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer: the scalar without an axis, else a row or a column; with a matrixout, that out along an axis and a copy of its element without one.
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ..., the first one passed in that order).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('minimum' in the texts). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
min(NDArray, NDAxis?, NDArray, bool, object, NDArray)
Return the minimum of an array or the minimum along an axis — NumPy's np.min(a, axis=None, out=None,
keepdims=<no value>, initial=<no value>, where=<no value>), i.e.
np.minimum.reduce(a, axis, out=out, keepdims=keepdims, initial=initial, where=where). The keywords
behave as in max(NDArray, NDAxis?, NDArray, bool, object, NDArray), with the minimum. This is the
only overload.
public static NDArray min(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data. A NaN propagates (use nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).
axisNDAxis?The axis to reduce (negative counts from the end), or
nullfor every axis. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).outNDArrayThe array the result is written into and returned (any dtype; a narrowing one is lossy, see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the third positional parameter, so
np.min(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array (0-d for a flat reduction without keepdims). Anumpy.matrixoperand gets the matrix method's answer: the scalar without an axis, else a row or a column; with a matrixout, that out along an axis and a copy of its element without one.
Remarks
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ..., the first one passed in that order).- AttributeError
A
numpy.matrixoperand with a plainout, after the values were stored ('numpy.ndarray' object has no attribute '_collapse').- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('minimum' in the texts). Also a tuple that names an axis twice (
duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
min_scalar_type(object)
For scalar value, returns the data type with the smallest size and smallest scalar kind which can hold its value. For an array of one or more dimensions (or of a non-number dtype such as bool or a string class), returns the array's own dtype unmodified, as NumPy does.
public static DType min_scalar_type(object value)
Parameters
valueobjectThe value to check: a C# scalar (NumPy's Python scalar or NumPy scalar), a C# string (a Python
str:<Uof its code points), or an NDArray - a 0-d number array is a scalar (its element decides), any other array answers its own dtype.
Returns
- DType
The minimum dtype that can represent the value; an array's dtype for an array.
Examples
np.min_scalar_type(10) // Byte (uint8)
np.min_scalar_type(-10) // SByte (int8)
np.min_scalar_type(1000) // UInt16
np.min_scalar_type(1.0) // Half (float16)
np.min_scalar_type(true) // Boolean
np.min_scalar_type(np.arange(4, dtype: np.float64)) // float64 (not a scalar: its dtype)
np.min_scalar_type(np.array(1000L)) // uint16 (a 0-d array is a scalar)
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.min_scalar_type.html
NumPy's array_min_scalar_type converts the argument to an array and runs
PyArray_MinScalarType: an array with ndim > 0 keeps its dtype, a 0-d numeric array is demoted by
the VALUE it holds (min_scalar_type_num, keyed by the element's own type).
For integers, finds the smallest integer type that can hold the value.
For floats, finds the smallest float type whose RANGE (magnitude) can hold the
value — matching NumPy, precision loss is allowed (e.g. 1e-40 reports float16).
Exceptions
- ArgumentNullException
valueis null (NumPy'sNoneis an object scalar, which NumSharp has no dtype for).
minimum(NDArray, NDArray, NDArray, NDArray, DType)
Element-wise minimum of array elements (NaN-PROPAGATING).
Compare two arrays and return a new array containing the element-wise minima. If either
element being compared is a NaN the NaN is returned (both NaN → the first); for complex
NaNs a NaN in the real OR imaginary part counts, so NaNs propagate. Use
fmin(NDArray, NDArray, NDArray, NDArray, DType) to IGNORE NaNs instead.
Mirrors NumPy's ufunc signature: minimum(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray minimum(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst operand. If
x1.shape !=x2.shape they must broadcast to a common shape (the output shape).x2NDArraySecond operand. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=): it joins the broadcast without being stretched, must be same_kind-castable from the loop dtype, and is returned as-is (reference identity). A read-only/broadcast out is refused.
whereNDArrayBoolean mask (NumPy ufunc where=): only mask-true elements are computed/written; masked-off
outslots keep their prior contents. Must be a bool array (a non-bool mask raises NumPy's 'safe'-cast error).dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.
Returns
- NDArray
The element-wise minimum of
x1andx2(oroutwhen supplied). A scalar if both inputs are scalars.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.minimum.html
BREAKING: the third positional argument is now out (NumPy's order), not
dtype; pass dtype: by name. Every in-repo call form is unaffected — callers use
either a positional out or the dtype: keyword.
Exceptions
- TypeError
outcannot be same_kind-cast from the loop dtype (NumPy-verbatim text).- ArgumentException
whereis not bool, or the shapes do not broadcast (NumPy-verbatim texts).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
mintypecode(object, string, char)
Return the character for the minimum-size type to which given types can be safely cast — NumPy's
numpy.mintypecode: the type characters of typechars that are in
typeset, then the one NumPy ranks smallest.
public static char mintypecode(object typechars, string typeset = "GDFgdf", char @default = 'd')
Parameters
typecharsobjectNumPy's "list of str or array_like", read as NumPy's
(isinstance(t, str) and t) or asarray(t).dtype.char for t in typecharsreads it:- a string: each character is a type character (
"fd"); - an NDArray: its elements along the first axis. A numeric array gives its
dtype.charonce per element (none for an empty first axis); a ONE-dimensionalU/StringDTypearray gives its elements' TEXT, because NumPy'snumpy.str_elements arestr(np.array(new[] { "d", "f" })reads like"df"; a chararray's text after itsrstrip()); anSarray gives'S'(bytes are nostr); - an NDMaskedArray: like its data, except that a masked element of a 1-D
array is NumPy's
np.ma.masked, a float64 constant, so it gives'd'; - any other sequence (a C# array, a list, a tuple), item by item: a string is itself (the
empty string is
np.asarray("")'s'U'), a char is the one-character type character it spells, an array itsdtype.char, a scalar itsnp.asarray(x).dtype.char(1.5is'd', a C#float'f'), and anything NumPy holds in an object array (null, a DType, a class, an object NumSharp has no dtype for) is'O'.
Null is NumPy's
None, which is not iterable.- a string: each character is a type character (
typesetstringThe characters the answer may be (default
'GDFgdf'). NumPy tests each type character witht in typeset, a SUBSTRING test, so a multi-character item counts when typeset contains it.defaultcharThe answer when no type character of
typecharsis intypeset.
Returns
- char
The character representing the minimum-size type that was found.
Remarks
Port of numpy/lib/_type_check_impl.py::mintypecode: the characters found in typeset,
the default when there are none, 'D' when both 'F' and 'd' are among them, else the one
listed first in 'GDFgdfQqLlIiHhBb?'. NumPy's generator is consumed lazily, so each item's type
character is computed and tested before the next item is read; only the iteration of
typechars itself fails first (iter(typechars) runs when the generator is made).
np.mintypecode("dfS"); // 'd'
np.mintypecode(np.array(new[] { 1.1, 2.0 }) + 0j); // 'D' (NumPy's docstring example)
np.mintypecode("abceh", @default: 'G'); // 'G'
Exceptions
- TypeError
typecharsis not iterable, with Python's texts:'NoneType' object is not iterable,'int' object is not iterable,iteration over a 0-d array; ortypesetis null while a type character is tested against it (argument of type 'NoneType' is not iterable).- ValueError
A matching character is not one of NumPy's sized codes
'GDFgdfQqLlIiHhBb?'('e','n','p','O', …) and the answer is not the'F'+'d'rule: NumPy picks the minimum with_typecodes_by_elsize.index, whosestr.indexraises "substring not found" for it.- NotSupportedException
NumPy's answer is a multi-character item (
new[] { "Fg" }is'Fg'in NumPy, a substring of'GDFgdf'), which a char cannot hold.
mod(NDArray, NDArray, NDArray, NDArray, DType)
Return element-wise remainder of division (the floored remainder — result has the same sign as the divisor,
Python's %). NumPy's ufunc remainder under its alias mod: errors quote the name
remainder, as NumPy's do.
Mirrors NumPy's ufunc signature: mod(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray mod(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayDividend array.
x2NDArrayDivisor array; broadcasts against
x1.outNDArrayA location into which the result is stored (NumPy ufunc out=; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): computation runs in this dtype.
Returns
- NDArray
The floored remainders, or
outitself when given.
Remarks
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.).- IncorrectTypeException
A bool or complex
dtype: remainder has integer and float loops only, so NumPy'sNo loop matching the specified signature and casting was found for ufunc remainder(parity QA-53).
mod(NDArray, float)
public static NDArray mod(NDArray x1, float x2)
Parameters
Returns
modf(NDArray, (NDArray, NDArray), NDArray, DType)
Return the fractional and integral parts of an array, element-wise — NumPy's two-output
modf ufunc. Both parts carry the sign of the input value.
public static (NDArray Fractional, NDArray Integral) modf(NDArray x, (NDArray, NDArray) @out = default, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array. Integer/bool/char promote to the narrowest float that fits the width (bool/int8/uint8 to float16, int16/uint16/char to float32, int32+ to float64); float16/float32/float64 are preserved; Complex has no loop (TypeError); Decimal is a NumSharp extension.
out(NDArray Lhs, NDArray Rhs)NumPy's
out=(o1, o2): the fractional output and the integral output, each same_kind-castable from the loop dtype and returned as-is (reference identity); either slot may be null (auto-allocated),defaultallocates both.whereNDArrayOptional boolean write mask; masked-off slots of BOTH provided outputs keep their prior contents.
dtypeDTypeOptional loop dtype override; only the float loops (Half/Single/Double/Decimal) are valid — a non-float request raises the no-loop TypeError.
Returns
- (NDArray Lhs, NDArray Rhs)
The (fractional, integral) pair. This is a scalar-shaped 0-d pair if
xis a scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.modf.html
modf(1.5) = (0.5, 1.0); modf(-2.7) = (-0.7, -2.0); modf(inf) = (+0.0, +inf);
modf(-inf) = (-0.0, -inf); modf(nan) = (nan, nan); modf(-0.0) = (-0.0, -0.0).
Fresh (auto-allocated) outputs take NumPy's ufunc output layout, the K order of the input: an
F-contiguous input yields F-contiguous outputs and a permuted one keeps its memory order, matching
NumPy (parity QA-36).
<p>NumPy's signature <code>modf(x, /, out=(None, None), *, where=True, ..., dtype=None)</code>: the outputs are ONE
tuple parameter, as <xref href="NumSharp.np.divmod(NumSharp.NDArray%2cNumSharp.NDArray%2cSystem.ValueTuple%7bNumSharp.NDArray%2cNumSharp.NDArray%7d%2cNumSharp.NDArray%2cNumSharp.DType)" data-throw-if-not-resolved="false"></xref>'s (the former <code>outFrac</code> / <code>outIntegral</code> went on
2026-11-11).</p>
Exceptions
- IncorrectTypeException
A complex input, or a non-float
dtype(no loop).
moveaxis(NDArray, NDAxis, NDAxis)
NumPy's np.moveaxis(a, source, destination): a view of a with the axes of
source moved to the positions of destination; the other axes keep their
order.
public static NDArray moveaxis(NDArray a, NDAxis source, NDAxis destination)
Parameters
aNDArrayThe array whose axes are reordered.
sourceNDAxisThe original positions of the axes to move: one axis or a tuple (
(0, 1)ornew[] { 0, 1 }), each distinct; negative positions count from the end.destinationNDAxisThe new positions, one per
sourceaxis, each distinct.
Returns
- NDArray
A view of
awith the moved axes (NumPy'sa.transpose(order)): it shares memory witha. Anumpy.matrixornumpy.char.chararrayoperand gives its class over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.moveaxis.html. NumPy's statements (each argument
through normalize_axis_tuple(..., 'source') / 'destination', the length check, the order, the
transpose) are the engine's MoveAxis(NDArray, int[], int[]).
One signature since API-parity batch 4 (2026-11-12): it replaces the four int / int[]
overloads, which had no tuple literal.
Exceptions
- ArgumentNullException
ais null, or an axis argument was converted from a nullint[](a non-nullable NDAxis has no None).- AxisError
An axis is out of range:
source: axis 3 is out of bounds for array of dimension 3(NumPy names the argument;sourceis checked whole beforedestination).- ValueError
An argument repeats an axis (
repeated axis in), the two have different lengths (sourceargument, checked after both are normalized), or asourceanddestinationarguments must have the same number of elementsnumpy.matrixoperand's result cannot be a matrix (more than two axes longer than 1:shape too large to be a matrix.).
moveaxis(NDArray, int, int)
moveaxis(NDArray, NDAxis, NDAxis) with the axis as one int: the overload a C#
integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so
every answer, error, layout and subclass result is that overload's.
public static NDArray moveaxis(NDArray a, int source, int destination)
Parameters
aNDArrayThe array whose axes are reordered.
sourceintThe axis to move (NumPy's
source; a negative value counts from the end).destinationintThe axis' new position (NumPy's
destination).
Returns
- NDArray
A view of
awith the moved axes (NumPy'sa.transpose(order)): it shares memory witha. Anumpy.matrixornumpy.char.chararrayoperand gives its class over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.moveaxis.html. NumPy's statements (each argument
through normalize_axis_tuple(..., 'source') / 'destination', the length check, the order, the
transpose) are the engine's MoveAxis(NDArray, int[], int[]).
One signature since API-parity batch 4 (2026-11-12): it replaces the four int / int[]
overloads, which had no tuple literal.
Exceptions
- ArgumentNullException
ais null, or an axis argument was converted from a nullint[](a non-nullable NDAxis has no None).- AxisError
An axis is out of range:
source: axis 3 is out of bounds for array of dimension 3(NumPy names the argument;sourceis checked whole beforedestination).- ValueError
An argument repeats an axis (
repeated axis in), the two have different lengths (sourceargument, checked after both are normalized), or asourceanddestinationarguments must have the same number of elementsnumpy.matrixoperand's result cannot be a matrix (more than two axes longer than 1:shape too large to be a matrix.).
moveaxis(NDArray, int[], int[])
moveaxis(NDArray, NDAxis, NDAxis) with the axes as an int[]: the overload an
int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form as NumPy's tuples (new int[0] is ()). NumPy's moveaxis has no
None, so a null array throws, exactly as the NDAxis form's conversion does.
public static NDArray moveaxis(NDArray a, int[] source, int[] destination)
Parameters
aNDArrayThe array whose axes are reordered.
sourceint[]The axes to move, as NumPy's tuple (NumPy's
source; not null).destinationint[]Their new positions, as NumPy's tuple (NumPy's
destination; not null).
Returns
- NDArray
A view of
awith the moved axes (NumPy'sa.transpose(order)): it shares memory witha. Anumpy.matrixornumpy.char.chararrayoperand gives its class over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.moveaxis.html. NumPy's statements (each argument
through normalize_axis_tuple(..., 'source') / 'destination', the length check, the order, the
transpose) are the engine's MoveAxis(NDArray, int[], int[]).
One signature since API-parity batch 4 (2026-11-12): it replaces the four int / int[]
overloads, which had no tuple literal.
Exceptions
- ArgumentNullException
sourceordestinationis null (moveaxis has no None).- ArgumentNullException
ais null, or an axis argument was converted from a nullint[](a non-nullable NDAxis has no None).- AxisError
An axis is out of range:
source: axis 3 is out of bounds for array of dimension 3(NumPy names the argument;sourceis checked whole beforedestination).- ValueError
An argument repeats an axis (
repeated axis in), the two have different lengths (sourceargument, checked after both are normalized), or asourceanddestinationarguments must have the same number of elementsnumpy.matrixoperand's result cannot be a matrix (more than two axes longer than 1:shape too large to be a matrix.).
multiply(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray multiply(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).
multithreading(bool, int)
Enable or disable NumSharp's multithreaded kernels and cap the worker thread count.
public static void multithreading(bool enabled, int max_threads = 8)
Parameters
enabledboolWhether kernels are allowed to use more than one thread.
max_threadsintUpper bound on worker threads (clamped to at least 1 and to the processor count). Defaults to 8.
Remarks
Multithreading is disabled by default, so the default behavior — and the exact summation order — is unchanged unless you opt in.
Currently this controls the fused 1-D dot product (dot(NDArray, NDArray, NDArray)
for vector·vector) on contiguous float / double inputs. Only large
vectors are parallelized; small and medium ones stay single-threaded because thread
fan-out would cost more than it saves. With multithreading on, the inner product is
summed per-chunk and combined, so results may differ from the single-threaded path in
the last few ULPs (the same floating-point reordering NumPy's threaded BLAS exhibits).
np.multithreading(true); // enable, up to 8 threads
np.multithreading(true, 16); // enable, up to 16 threads
np.multithreading(false); // back to single-threaded
This is a facade over TensorEngine.Threading: the thread cap is routed through
its NumSharp knob (so max_threads also writes the
process-scoped NUMSHARP_NUM_THREADS and is visible through that surface), while the
enable flag sets Enabled. Both are seeded at startup from
NUMSHARP_MULTITHREADING / NUMSHARP_NUM_THREADS as the source of truth.
nan_to_num(NDArray, bool, object, object, object)
Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the
values supplied via nan, posinf and/or
neginf.
public static NDArray nan_to_num(NDArray x, bool copy = true, object nan = null, object posinf = null, object neginf = null)
Parameters
xNDArrayInput data.
copyboolWhether to create a copy of
x(true, the default) or replace values in place (false). Withfalsethe returned array may bexitself (writes go through to shared memory).nanobjectValue(s) used to fill NaN. A real scalar (int/float/bool/char/float16) or an array_like (NDArray or a C# array) broadcast position-wise.
null(default) fills NaN with0.0. Cast same_kind into the real dtype, as NumPy'scopytocasts it: text and complex fills are refused.posinfobjectValue(s) used to fill +Inf.
null(default) fills with the largest finite value representable byx's (real) dtype.neginfobjectValue(s) used to fill -Inf.
null(default) fills with the most negative finite value representable byx's (real) dtype.
Returns
- NDArray
xwith the non-finite values replaced. Ifcopy=falsethis may bexitself. Integer/boolean/decimal inputs are returned unchanged (a copy whencopy=true) — they are not inexact and hold no NaN/Inf.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nan_to_num.html
Port of NumPy's numpy.nan_to_num (numpy/lib/_type_check_impl.py). For a complex
input the replacement is applied to the real and imaginary components separately, both using the
float64 finfo limits (matching NumPy). The common contiguous scalar-fill case runs a
single fused whole-array kernel (NanToNum(NPTypeCode, void*, void*, long, void*, void*, void*)) — one read + one
write, no intermediate allocation — instead of NumPy's isnan/isposinf/isneginf + three
copyto(where=) passes. Array-valued fills and non-contiguous in-place targets take the
faithful copyto composition.
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.).- InvalidCastException
On an inexact input, a text or complex fill (or a complex / text array fill): NumPy's
copytorefusal (Cannot cast scalar from dtype('<U1') to dtype('float64') according to the rule 'same_kind', NumPy's TypeError text), raised at the statement that meets the fill; or a scalar fill of a type that does not convert to a number.- ValueError
An array fill that does not broadcast into
x.- ArgumentNullException
xis null.
nanargmax(NDArray)
Return the index of the maximum value in the flattened array, ignoring NaNs. For an all-NaN array a ValueError is raised. Warning: the result cannot be trusted if the array contains only NaNs and -Infs (NumPy caveat).
public static long nanargmax(NDArray a)
Parameters
aNDArrayInput data.
Returns
- long
Index of the maximum value in the flattened array (NumPy intp = int64).
Remarks
Exceptions
- ValueError
All-NaN slice encountered; or a
StringDTypeline of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax'sCannot compare null that is not a nan-like value).- ValueError
A
numpy.char.chararrayoperand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.- ArgumentNullException
ais null.
nanargmax(NDArray, NDAxis?, NDArray, bool)
Return the indices of the maximum values in the specified axis, ignoring NaNs. For all-NaN slices a ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs (NumPy caveat).
public static NDArray nanargmax(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput data.
axisNDAxis?Axis along which to operate. If
null, the flattened input is used. NumPy's axis here is ONE integer: a tuple is refused with NumPy's TypeError, after the NaN mask has been reduced over it.outNDArrayIf provided, the result is inserted into this array and the SAME instance is returned (NumPy semantics): the shape must equal the result's exactly, and the dtype must be an integer family safe-castable to int64 (bool through uint32 — uint64/floats raise NumPy's verbatim cast TypeError); the int64 indices then cast UNSAFELY into it (wrap/truncate).
keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one (with
axisnullthe result has shape(1,) * a.ndim, like NumPy).
Returns
- NDArray
Array of int64 indices (or a 0-d scalar for the flattened form);
outwhen given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanargmax.html
Text of every class (S, U, NEP 55 StringDType) is np.argmax /
np.argmin of the text: NumPy's _replace_nan leaves an array that is not inexact alone, so a
StringDType NA is ordered by the argmax rules (a NaN-like NA is the greatest value, a None-like NA in a
line of two or more elements raises their ValueError), never skipped as a NaN.
Exceptions
- ValueError
All-NaN slice encountered; or a
StringDTypeline of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax'sCannot compare null that is not a nan-like value).- AxisError
Axis out of bounds (reports the original axis, like NumPy); for a tuple, an item out of bounds of an inexact input (the NaN mask's np.all reads it first).
- TypeError
A tuple
axis('tuple' object cannot be interpreted as an integer), after a repeated item (duplicate value in 'axis') or an all-NaN slice over the tuple of an inexact input has raised NumPy's ValueError first.- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ValueError
A
numpy.char.chararrayoperand withoutout: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; withoutthe indices are written.- ArgumentNullException
ais null.
nanargmax(NDArray, int?, NDArray, bool)
nanargmax(NDArray, NDAxis?, NDArray, bool) with the axis as an int?: the overload a C# integer,
an int?, a bare null and default bind (NumPy's axis here is ONE integer, so there is no
int[] form, and null / default stay None), forwarding to the NDAxis? form.
public static NDArray nanargmax(NDArray a, int? axis, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput data.
axisint?The axis, or
nullfor the flattened array.outNDArrayThe output array, or null (see the NDAxis? form).
keepdimsboolKeep the reduced axis with length one.
Returns
- NDArray
The int64 indices;
outwhen given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanargmax.html
Text of every class (S, U, NEP 55 StringDType) is np.argmax /
np.argmin of the text: NumPy's _replace_nan leaves an array that is not inexact alone, so a
StringDType NA is ordered by the argmax rules (a NaN-like NA is the greatest value, a None-like NA in a
line of two or more elements raises their ValueError), never skipped as a NaN.
Exceptions
- ValueError
All-NaN slice encountered; or a
StringDTypeline of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax'sCannot compare null that is not a nan-like value).- AxisError
Axis out of bounds (reports the original axis, like NumPy); for a tuple, an item out of bounds of an inexact input (the NaN mask's np.all reads it first).
- TypeError
A tuple
axis('tuple' object cannot be interpreted as an integer), after a repeated item (duplicate value in 'axis') or an all-NaN slice over the tuple of an inexact input has raised NumPy's ValueError first.- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ValueError
A
numpy.char.chararrayoperand withoutout: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; withoutthe indices are written.- ArgumentNullException
ais null.
nanargmin(NDArray)
Return the index of the minimum value in the flattened array, ignoring NaNs. For an all-NaN array a ValueError is raised. Warning: the result cannot be trusted if the array contains only NaNs and Infs (NumPy caveat).
public static long nanargmin(NDArray a)
Parameters
aNDArrayInput data.
Returns
- long
Index of the minimum value in the flattened array (NumPy intp = int64).
Remarks
Exceptions
- ValueError
All-NaN slice encountered; or a
StringDTypeline of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax'sCannot compare null that is not a nan-like value).- ValueError
A
numpy.char.chararrayoperand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.- ArgumentNullException
ais null.
nanargmin(NDArray, NDAxis?, NDArray, bool)
Return the indices of the minimum values in the specified axis, ignoring NaNs. For all-NaN slices a ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs (NumPy caveat).
public static NDArray nanargmin(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput data.
axisNDAxis?Axis along which to operate. If
null, the flattened input is used. NumPy's axis here is ONE integer: a tuple is refused with NumPy's TypeError, after the NaN mask has been reduced over it.outNDArrayIf provided, the result is inserted into this array and the SAME instance is returned (NumPy semantics — see nanargmax(NDArray, int?, NDArray, bool)).
keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one (with
axisnullthe result has shape(1,) * a.ndim, like NumPy).
Returns
- NDArray
Array of int64 indices (or a 0-d scalar for the flattened form);
outwhen given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanargmin.html
Text of every class (S, U, NEP 55 StringDType) is np.argmax /
np.argmin of the text: NumPy's _replace_nan leaves an array that is not inexact alone, so a
StringDType NA is ordered by the argmax rules (a NaN-like NA is the greatest value, a None-like NA in a
line of two or more elements raises their ValueError), never skipped as a NaN.
Exceptions
- ValueError
All-NaN slice encountered; or a
StringDTypeline of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax'sCannot compare null that is not a nan-like value).- AxisError
Axis out of bounds (reports the original axis, like NumPy); for a tuple, an item out of bounds of an inexact input (the NaN mask's np.all reads it first).
- TypeError
A tuple
axis('tuple' object cannot be interpreted as an integer), after a repeated item (duplicate value in 'axis') or an all-NaN slice over the tuple of an inexact input has raised NumPy's ValueError first.- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ValueError
A
numpy.char.chararrayoperand withoutout: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; withoutthe indices are written.- ArgumentNullException
ais null.
nanargmin(NDArray, int?, NDArray, bool)
nanargmin(NDArray, NDAxis?, NDArray, bool) with the axis as an int?: the overload a C# integer,
an int?, a bare null and default bind (NumPy's axis here is ONE integer, so there is no
int[] form, and null / default stay None), forwarding to the NDAxis? form.
public static NDArray nanargmin(NDArray a, int? axis, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput data.
axisint?The axis, or
nullfor the flattened array.outNDArrayThe output array, or null (see the NDAxis? form).
keepdimsboolKeep the reduced axis with length one.
Returns
- NDArray
The int64 indices;
outwhen given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanargmin.html
Text of every class (S, U, NEP 55 StringDType) is np.argmax /
np.argmin of the text: NumPy's _replace_nan leaves an array that is not inexact alone, so a
StringDType NA is ordered by the argmax rules (a NaN-like NA is the greatest value, a None-like NA in a
line of two or more elements raises their ValueError), never skipped as a NaN.
Exceptions
- ValueError
All-NaN slice encountered; or a
StringDTypeline of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax'sCannot compare null that is not a nan-like value).- AxisError
Axis out of bounds (reports the original axis, like NumPy); for a tuple, an item out of bounds of an inexact input (the NaN mask's np.all reads it first).
- TypeError
A tuple
axis('tuple' object cannot be interpreted as an integer), after a repeated item (duplicate value in 'axis') or an all-NaN slice over the tuple of an inexact input has raised NumPy's ValueError first.- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ValueError
A
numpy.char.chararrayoperand withoutout: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; withoutthe indices are written.- ArgumentNullException
ais null.
nancumprod(NDArray, int?, DType, NDArray)
Return the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) as one. The cumulative product does not change when NaNs are encountered and leading NaNs are replaced by ones. Ones are returned for slices that are all-NaN or empty.
public static NDArray nancumprod(NDArray a, int? axis = null, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayInput array.
axisint?Axis along which the cumulative product is computed. The default (None) is to compute the cumprod over the flattened array.
dtypeDTypeType of the returned array and of the accumulator in which the elements are multiplied (a Type, NPTypeCode, dtype string or DType — all convert implicitly). If not specified, it defaults to the dtype of
a, unlessahas an integer dtype with a precision less than that of the default platform integer, in which case the default platform integer is used.outNDArrayAlternate output array in which to place the result. It must have the same shape and buffer length as the expected output, but its dtype may differ (the result is cast into it with NumPy's unsafe casting) and a reference to
outis returned.
Returns
- NDArray
A new array holding the result unless
outis specified, in which case a reference tooutis returned.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nancumprod.html
Port of numpy/lib/_nanfunctions_impl.py::nancumprod: _replace_nan(a, 1) then np.cumprod.
Only float-family dtypes can contain NaN, so integer/bool/decimal inputs are equivalent to cumprod(NDArray, int?, DType, NDArray).
The whole function is the engine's TensorEngine.NanCumProd (the np-layer dtype plan, P1b and PE);
this applies the matrix rule and calls it.
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 read-onlyout; text a numeric dtype cannot parse.- AxisError
axisis out of range.- TypeError
A text operand or request NumPy's loop resolution refuses.
- IncorrectShapeException
outdoes not have the result's shape.
nancumsum(NDArray, int?, DType, NDArray)
Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros. Zeros are returned for slices that are all-NaN or empty.
public static NDArray nancumsum(NDArray a, int? axis = null, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayInput array.
axisint?Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
dtypeDTypeType of the returned array and of the accumulator in which the elements are summed (a Type, NPTypeCode, dtype string or DType — all convert implicitly). If not specified, it defaults to the dtype of
a, unlessahas an integer dtype with a precision less than that of the default platform integer, in which case the default platform integer is used.outNDArrayAlternate output array in which to place the result. It must have the same shape and buffer length as the expected output, but its dtype may differ (the result is cast into it with NumPy's unsafe casting) and a reference to
outis returned.
Returns
- NDArray
A new array holding the result unless
outis specified, in which case a reference tooutis returned. The result has the same size asa, and the same shape ifaxisis not None orais 1-D.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nancumsum.html
Port of numpy/lib/_nanfunctions_impl.py::nancumsum: _replace_nan(a, 0) then np.cumsum.
Only float-family dtypes can contain NaN, so integer/bool/decimal inputs are equivalent to cumsum(NDArray, int?, DType, NDArray).
The whole function is the engine's TensorEngine.NanCumSum (the np-layer dtype plan, P1b and PE);
this applies the matrix rule and calls it.
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 read-onlyout; text a numeric loop cannot parse.- AxisError
axisis out of range.- TypeError
A text operand or request NumPy's loop resolution refuses.
- IncorrectShapeException
outdoes not have the result's shape.
nanmax(NDArray, int, NDArray, bool, object, NDArray)
nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axis as one int:
the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nanmax(NDArray a, int axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose maximum is desired.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.nanmax(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions (for a flat reduction: shape
(1,)*a.ndim).initialobjectThe value every output starts from, or
null; required withwhere. An output whose every selected element is NaN returns it (fmax skips NaN).whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN (NumPy's "All-NaN slice encountered" RuntimeWarning is not modeled). Anumpy.matrixoperand gets NumPy's subclass route (see the remarks): the scalar without an axis, else a row or a column, an all-NaN slice as NumPy's ownnp.nan; with a matrixout, that out along an axis and the scalar without one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmax.html. Per dtype:
- float32 / float64 run NumPy's own
fmaxreduction schedule — the vector opmaxpinside each inner-loop call's vector section, the CRTfmaxfor its scalar tail — so a±0tie or an all-NaN slice can come back differently for two layouts of the same values, exactly as in NumPy. - float16 and complex128 run NumPy's sequential loops: NaN elements are skipped (complex: a NaN in either part), a tie keeps the EARLIER element, an all-NaN slice returns its first NaN verbatim; complex compares lexicographically (real part, then imaginary).
- Integer, bool and char arrays cannot hold a NaN, so this is amax(NDArray, NDAxis?, NDArray, bool, object, NDArray); decimal likewise (no NumPy analog).
A non-empty reduced axis of an otherwise empty array returns the empty result.
A numpy.matrix operand is not a base ndarray, so NumPy takes nanmax's "slow, but safe for subclasses"
branch: the NaNs of a copy become -inf, np.amax reduces it (the matrix method), and a slice that was
all NaN gets np.nan written back. Footgun: those bits are not fmax's — a ±0 tie follows
maximum (np.nanmax(np.matrix([[0.0, -0.0]])) is -0.0, where the plain array's is
0.0), an all-NaN slice is NumPy's positive quiet NaN whatever NaN it held, and a complex one is
nan+0j; a matrix out of a flat call keeps the -inf (only the returned scalar is NaN).
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.max() got an unexpected keyword argument ...: NumPy's route ends in the matrix method, which has none of them).- AttributeError
A
numpy.matrixoperand with a plainout: the method stores the maxima of the NaN-replaced copy into it (an all-NaN slice as-inf), then fails onout._collapse.- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmax' in the texts); an empty reduction without
initialraises (fmaxhas no identity; 'maximum' for anumpy.matrixoperand, whose route reduces with the method) — it does not return NaN. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
nanmax(NDArray, int[], NDArray, bool, object, NDArray)
nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static NDArray nanmax(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose maximum is desired.
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.nanmax(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions (for a flat reduction: shape
(1,)*a.ndim).initialobjectThe value every output starts from, or
null; required withwhere. An output whose every selected element is NaN returns it (fmax skips NaN).whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN (NumPy's "All-NaN slice encountered" RuntimeWarning is not modeled). Anumpy.matrixoperand gets NumPy's subclass route (see the remarks): the scalar without an axis, else a row or a column, an all-NaN slice as NumPy's ownnp.nan; with a matrixout, that out along an axis and the scalar without one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmax.html. Per dtype:
- float32 / float64 run NumPy's own
fmaxreduction schedule — the vector opmaxpinside each inner-loop call's vector section, the CRTfmaxfor its scalar tail — so a±0tie or an all-NaN slice can come back differently for two layouts of the same values, exactly as in NumPy. - float16 and complex128 run NumPy's sequential loops: NaN elements are skipped (complex: a NaN in either part), a tie keeps the EARLIER element, an all-NaN slice returns its first NaN verbatim; complex compares lexicographically (real part, then imaginary).
- Integer, bool and char arrays cannot hold a NaN, so this is amax(NDArray, NDAxis?, NDArray, bool, object, NDArray); decimal likewise (no NumPy analog).
A non-empty reduced axis of an otherwise empty array returns the empty result.
A numpy.matrix operand is not a base ndarray, so NumPy takes nanmax's "slow, but safe for subclasses"
branch: the NaNs of a copy become -inf, np.amax reduces it (the matrix method), and a slice that was
all NaN gets np.nan written back. Footgun: those bits are not fmax's — a ±0 tie follows
maximum (np.nanmax(np.matrix([[0.0, -0.0]])) is -0.0, where the plain array's is
0.0), an all-NaN slice is NumPy's positive quiet NaN whatever NaN it held, and a complex one is
nan+0j; a matrix out of a flat call keeps the -inf (only the returned scalar is NaN).
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.max() got an unexpected keyword argument ...: NumPy's route ends in the matrix method, which has none of them).- AttributeError
A
numpy.matrixoperand with a plainout: the method stores the maxima of the NaN-replaced copy into it (an all-NaN slice as-inf), then fails onout._collapse.- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmax' in the texts); an empty reduction without
initialraises (fmaxhas no identity; 'maximum' for anumpy.matrixoperand, whose route reduces with the method) — it does not return NaN. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray)
Return the maximum of an array or the maximum along an axis, ignoring NaNs — NumPy's np.nanmax(a, axis=None,
out=None, keepdims=<no value>, initial=<no value>, where=<no value>), which for an ndarray IS
np.fmax.reduce(a, axis, out=out, keepdims=keepdims, initial=initial, where=where), reproduced bit for bit:
which zero sign survives a ±0 tie and which NaN an all-NaN slice returns (payload intact, never a canonical
NaN) are the ones NumPy 2.4.2 returns for the same layout. The keywords behave as in
max(NDArray, NDAxis?, NDArray, bool, object, NDArray); the texts name 'fmax' (for every dtype, an
integer array included). This is the only overload.
public static NDArray nanmax(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose maximum is desired.
axisNDAxis?The axis to reduce (negative counts from the end), or
nullfor every axis. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.nanmax(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions (for a flat reduction: shape
(1,)*a.ndim).initialobjectThe value every output starts from, or
null; required withwhere. An output whose every selected element is NaN returns it (fmax skips NaN).whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN (NumPy's "All-NaN slice encountered" RuntimeWarning is not modeled). Anumpy.matrixoperand gets NumPy's subclass route (see the remarks): the scalar without an axis, else a row or a column, an all-NaN slice as NumPy's ownnp.nan; with a matrixout, that out along an axis and the scalar without one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmax.html. Per dtype:
- float32 / float64 run NumPy's own
fmaxreduction schedule — the vector opmaxpinside each inner-loop call's vector section, the CRTfmaxfor its scalar tail — so a±0tie or an all-NaN slice can come back differently for two layouts of the same values, exactly as in NumPy. - float16 and complex128 run NumPy's sequential loops: NaN elements are skipped (complex: a NaN in either part), a tie keeps the EARLIER element, an all-NaN slice returns its first NaN verbatim; complex compares lexicographically (real part, then imaginary).
- Integer, bool and char arrays cannot hold a NaN, so this is amax(NDArray, NDAxis?, NDArray, bool, object, NDArray); decimal likewise (no NumPy analog).
A non-empty reduced axis of an otherwise empty array returns the empty result.
A numpy.matrix operand is not a base ndarray, so NumPy takes nanmax's "slow, but safe for subclasses"
branch: the NaNs of a copy become -inf, np.amax reduces it (the matrix method), and a slice that was
all NaN gets np.nan written back. Footgun: those bits are not fmax's — a ±0 tie follows
maximum (np.nanmax(np.matrix([[0.0, -0.0]])) is -0.0, where the plain array's is
0.0), an all-NaN slice is NumPy's positive quiet NaN whatever NaN it held, and a complex one is
nan+0j; a matrix out of a flat call keeps the -inf (only the returned scalar is NaN).
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.max() got an unexpected keyword argument ...: NumPy's route ends in the matrix method, which has none of them).- AttributeError
A
numpy.matrixoperand with a plainout: the method stores the maxima of the NaN-replaced copy into it (an all-NaN slice as-inf), then fails onout._collapse.- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmax' in the texts); an empty reduction without
initialraises (fmaxhas no identity; 'maximum' for anumpy.matrixoperand, whose route reduces with the method) — it does not return NaN. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
nanmean(NDArray, int, DType, NDArray, bool, NDArray)
nanmean(NDArray, NDAxis?, DType, NDArray, bool, NDArray) with the axis as one int:
the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nanmean(NDArray a, int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayThe array whose mean is desired; any dtype and layout.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypeThe type of the sum (NumPy's
dtype=). For a float or complex input it must be inexact; null uses the input's dtype (np.mean's float64 for an integer or bool input).outNDArrayNumPy's
out=: the destination of the sum and the division (returned); for a float or complex input it must be inexact.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include (the count and the sum read it), or null for all.
Returns
- NDArray
The mean, in
dtypeor the input's dtype (float64 for an integer or bool input); a 0-d array for a flat reduction withoutkeepdims. A slice with only NaNs is NaN.
Remarks
An array that cannot hold NaN (integer, bool, char, decimal) has no NaN to ignore: the result is
np.mean's, keywords included. For a float or complex array the arithmetic is NumPy's
_nanfunctions_impl.nanmean (see TensorEngine.NanMean): the NaN-free sum in the input's
dtype (a float16 or float32 input sums in its own dtype, not in double), then the division by the int64 count,
which for complex is NumPy's complex division (an infinite part turns the other part into NaN).
https://numpy.org/doc/stable/reference/generated/numpy.nanmean.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanmean(a, axis, keepdims, dtype), so dtype is the third
argument and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- AxisError
axisis outsidea's dimensions. A 0-d float or complex array takes axis 0 and -1 as a flat reduction (NumPy's nanmean reads the axis through np.sum).- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nanmean(NDArray, int[], DType, NDArray, bool, NDArray)
nanmean(NDArray, NDAxis?, DType, NDArray, bool, NDArray) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static NDArray nanmean(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayThe array whose mean is desired; any dtype and layout.
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypeThe type of the sum (NumPy's
dtype=). For a float or complex input it must be inexact; null uses the input's dtype (np.mean's float64 for an integer or bool input).outNDArrayNumPy's
out=: the destination of the sum and the division (returned); for a float or complex input it must be inexact.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include (the count and the sum read it), or null for all.
Returns
- NDArray
The mean, in
dtypeor the input's dtype (float64 for an integer or bool input); a 0-d array for a flat reduction withoutkeepdims. A slice with only NaNs is NaN.
Remarks
An array that cannot hold NaN (integer, bool, char, decimal) has no NaN to ignore: the result is
np.mean's, keywords included. For a float or complex array the arithmetic is NumPy's
_nanfunctions_impl.nanmean (see TensorEngine.NanMean): the NaN-free sum in the input's
dtype (a float16 or float32 input sums in its own dtype, not in double), then the division by the int64 count,
which for complex is NumPy's complex division (an infinite part turns the other part into NaN).
https://numpy.org/doc/stable/reference/generated/numpy.nanmean.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanmean(a, axis, keepdims, dtype), so dtype is the third
argument and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- AxisError
axisis outsidea's dimensions. A 0-d float or complex array takes axis 0 and -1 as a flat reduction (NumPy's nanmean reads the axis through np.sum).- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nanmean(NDArray, NDAxis?, DType, NDArray, bool, NDArray)
Compute the arithmetic mean along the specified axis, ignoring NaNs: NumPy's numpy.nanmean, statement
for statement. The mean is the sum of the non-NaN elements divided by their count, per slice.
public static NDArray nanmean(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayThe array whose mean is desired; any dtype and layout.
axisNDAxis?The axis along which the means are computed (negative counts from the end); null (the default) computes the mean of the flattened array. A tuple (
(0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypeThe type of the sum (NumPy's
dtype=). For a float or complex input it must be inexact; null uses the input's dtype (np.mean's float64 for an integer or bool input).outNDArrayNumPy's
out=: the destination of the sum and the division (returned); for a float or complex input it must be inexact.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include (the count and the sum read it), or null for all.
Returns
- NDArray
The mean, in
dtypeor the input's dtype (float64 for an integer or bool input); a 0-d array for a flat reduction withoutkeepdims. A slice with only NaNs is NaN.
Remarks
An array that cannot hold NaN (integer, bool, char, decimal) has no NaN to ignore: the result is
np.mean's, keywords included. For a float or complex array the arithmetic is NumPy's
_nanfunctions_impl.nanmean (see TensorEngine.NanMean): the NaN-free sum in the input's
dtype (a float16 or float32 input sums in its own dtype, not in double), then the division by the int64 count,
which for complex is NumPy's complex division (an infinite part turns the other part into NaN).
https://numpy.org/doc/stable/reference/generated/numpy.nanmean.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanmean(a, axis, keepdims, dtype), so dtype is the third
argument and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- AxisError
axisis outsidea's dimensions. A 0-d float or complex array takes axis 0 and -1 as a flat reduction (NumPy's nanmean reads the axis through np.sum).- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nanmedian(NDArray, int, NDArray, bool, bool)
nanmedian(NDArray, NDAxis?, NDArray, bool, bool) with the axis as one int: the
overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nanmedian(NDArray a, int axis, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
aNDArrayThe data (bool computes as its 0 / 1 values; text: see the exceptions).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
keepdimsboolWhether the reduced axes are kept with length one.
Returns
- NDArray
The NaN-ignoring median;
outitself when one is given. Over a NEP 55StringDTypearray a median exists only for an all-NaN reduction: its NA object (a read-only 0-dStringDTypearray, NumPy's Python object), ornp.float64(nan)where NumPy's mean of NaN-like NAs gives it.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmedian.html
NumPy's _ureduce turns an integer axis into a one-element tuple, so the engine member takes
the axes as an array; a tuple is merged into one axis before the partition, and the empty tuple reduces
nothing.
A numpy.matrix operand: an integer axis gives the matrix of NumPy's _collapse rule, the
class rule of a TUPLE sees no axis (the rule NumSharp's tuple overloads had) - NumPy's own tuple answers come
from matrix semantics inside its Python code (NumPy's nanmedian of a matrix calls matrix.sum with keepdims and raises TypeError for every axis), which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
overloads, which made np.nanmedian(a, null) ambiguous (CS0121) and had no tuple literal.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range for
a(every axis is range-checked before the repeat check).- ValueError
A tuple names an axis twice (
repeated axis); the storeout[...] = result(np.nanmedian's, after the computation): anoutthe result does not broadcast to (could not broadcast input array from shape (4,) into shape (3,)) or a read-only one (assignment destination is read-only); for empty data, np.nanmean's add.reduce prologue texts (parity QA-31).- TypeError
Fixed-width text data that NumPy's NaN test (or, for empty data, its
nanmean) refuses (its verbatim text). AStringDTypearray: the median's mean refuses the concatenated text; along an axis shorter than 600 numpy.ma's median refuses first (Unsuitable type StringDType() for calculating minimum.);keepdimsover NumPy's Python-object result ('float' object is not subscriptable).- ValueError
A
StringDTypearray: a None-like NA in a sorted line of two or more elements (Cannot compare null that is not a nan-like value), an empty input's mean (no identity), or the store intoout(NumPy's setitem texts, e.g.cannot convert float NaN to integer).- NotSupportedException
A
StringDTypereduction along a long axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan).
nanmedian(NDArray, int[], NDArray, bool, bool)
nanmedian(NDArray, NDAxis?, NDArray, bool, bool) with the axes as an int[]: the
overload an int[] binds, and a bare null too (null converts to int[] better than to
NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple
(new int[0] is ()).
public static NDArray nanmedian(NDArray a, int[] axis, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
aNDArrayThe data (bool computes as its 0 / 1 values; text: see the exceptions).
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
keepdimsboolWhether the reduced axes are kept with length one.
Returns
- NDArray
The NaN-ignoring median;
outitself when one is given. Over a NEP 55StringDTypearray a median exists only for an all-NaN reduction: its NA object (a read-only 0-dStringDTypearray, NumPy's Python object), ornp.float64(nan)where NumPy's mean of NaN-like NAs gives it.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmedian.html
NumPy's _ureduce turns an integer axis into a one-element tuple, so the engine member takes
the axes as an array; a tuple is merged into one axis before the partition, and the empty tuple reduces
nothing.
A numpy.matrix operand: an integer axis gives the matrix of NumPy's _collapse rule, the
class rule of a TUPLE sees no axis (the rule NumSharp's tuple overloads had) - NumPy's own tuple answers come
from matrix semantics inside its Python code (NumPy's nanmedian of a matrix calls matrix.sum with keepdims and raises TypeError for every axis), which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
overloads, which made np.nanmedian(a, null) ambiguous (CS0121) and had no tuple literal.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range for
a(every axis is range-checked before the repeat check).- ValueError
A tuple names an axis twice (
repeated axis); the storeout[...] = result(np.nanmedian's, after the computation): anoutthe result does not broadcast to (could not broadcast input array from shape (4,) into shape (3,)) or a read-only one (assignment destination is read-only); for empty data, np.nanmean's add.reduce prologue texts (parity QA-31).- TypeError
Fixed-width text data that NumPy's NaN test (or, for empty data, its
nanmean) refuses (its verbatim text). AStringDTypearray: the median's mean refuses the concatenated text; along an axis shorter than 600 numpy.ma's median refuses first (Unsuitable type StringDType() for calculating minimum.);keepdimsover NumPy's Python-object result ('float' object is not subscriptable).- ValueError
A
StringDTypearray: a None-like NA in a sorted line of two or more elements (Cannot compare null that is not a nan-like value), an empty input's mean (no identity), or the store intoout(NumPy's setitem texts, e.g.cannot convert float NaN to integer).- NotSupportedException
A
StringDTypereduction along a long axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan).
nanmedian(NDArray, NDAxis?, NDArray, bool, bool)
NumPy's np.nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=False): the median along
the given axes, ignoring NaNs. Like np.median, an even-sized (NaN-free) slice reduces to the
mean of the two central values — NumPy's mean-of-middle rule, NOT np.nanquantile(a, 0.5) (they
disagree by up to 1 ULP), so medianMean: true is REQUIRED. A slice that is entirely NaN (or empty)
yields NaN, matching NumPy's "All-NaN slice" behaviour.
public static NDArray nanmedian(NDArray a, NDAxis? axis = null, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
aNDArrayThe data (bool computes as its 0 / 1 values; text: see the exceptions).
axisNDAxis?NumPy's
axis:null(None, the default) reduces the flattened data; one axis (negative counts from the end) or a tuple ((0, 2),new[] { 0, 2 }) reduces those axes, merged into one; the empty tuple reduces nothing.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
keepdimsboolWhether the reduced axes are kept with length one.
Returns
- NDArray
The NaN-ignoring median;
outitself when one is given. Over a NEP 55StringDTypearray a median exists only for an all-NaN reduction: its NA object (a read-only 0-dStringDTypearray, NumPy's Python object), ornp.float64(nan)where NumPy's mean of NaN-like NAs gives it.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmedian.html
NumPy's _ureduce turns an integer axis into a one-element tuple, so the engine member takes
the axes as an array; a tuple is merged into one axis before the partition, and the empty tuple reduces
nothing.
A numpy.matrix operand: an integer axis gives the matrix of NumPy's _collapse rule, the
class rule of a TUPLE sees no axis (the rule NumSharp's tuple overloads had) - NumPy's own tuple answers come
from matrix semantics inside its Python code (NumPy's nanmedian of a matrix calls matrix.sum with keepdims and raises TypeError for every axis), which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the int? and int[]
overloads, which made np.nanmedian(a, null) ambiguous (CS0121) and had no tuple literal.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range for
a(every axis is range-checked before the repeat check).- ValueError
A tuple names an axis twice (
repeated axis); the storeout[...] = result(np.nanmedian's, after the computation): anoutthe result does not broadcast to (could not broadcast input array from shape (4,) into shape (3,)) or a read-only one (assignment destination is read-only); for empty data, np.nanmean's add.reduce prologue texts (parity QA-31).- TypeError
Fixed-width text data that NumPy's NaN test (or, for empty data, its
nanmean) refuses (its verbatim text). AStringDTypearray: the median's mean refuses the concatenated text; along an axis shorter than 600 numpy.ma's median refuses first (Unsuitable type StringDType() for calculating minimum.);keepdimsover NumPy's Python-object result ('float' object is not subscriptable).- ValueError
A
StringDTypearray: a None-like NA in a sorted line of two or more elements (Cannot compare null that is not a nan-like value), an empty input's mean (no identity), or the store intoout(NumPy's setitem texts, e.g.cannot convert float NaN to integer).- NotSupportedException
A
StringDTypereduction along a long axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan).
nanmin(NDArray, int, NDArray, bool, object, NDArray)
nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axis as one int:
the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the
NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nanmin(NDArray a, int axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose minimum is desired.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.nanmin(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions (for a flat reduction: shape
(1,)*a.ndim).initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN. Anumpy.matrixoperand gets NumPy's subclass route, as in nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with+infandnp.amin.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html. Per dtype:
- float32 / float64 run NumPy's own
fminreduction schedule — the vector opminpinside each inner-loop call's vector section, the CRTfminfor its scalar tail (whose tie keeps-0over+0) — so a±0tie or an all-NaN slice can come back differently for two layouts of the same values, exactly as in NumPy. - float16 and complex128 run NumPy's sequential loops: NaN elements are skipped (complex: a NaN in either part), a tie keeps the EARLIER element, an all-NaN slice returns its first NaN verbatim.
- Integer, bool and char arrays cannot hold a NaN, so this is amin(NDArray, NDAxis?, NDArray, bool, object, NDArray); decimal likewise (no NumPy analog).
A non-empty reduced axis of an otherwise empty array returns the empty result.
A numpy.matrix operand takes NumPy's subclass branch (NaNs of a copy become +inf, np.amin
reduces it, an all-NaN slice gets np.nan): a ±0 tie follows minimum, not fmin
(np.nanmin(np.matrix([[-0.0, 0.0]])) is 0.0, where the plain array's is -0.0), and an all-NaN
slice is NumPy's positive quiet NaN (complex: nan+0j).
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout: the method stores the minima of the NaN-replaced copy into it (an all-NaN slice as+inf), then fails onout._collapse.- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmin' in the texts); an empty reduction without
initialraises (fminhas no identity; 'minimum' for anumpy.matrixoperand). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
nanmin(NDArray, int[], NDArray, bool, object, NDArray)
nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray) with the axes as an int[]:
the overload an int[] binds, and a bare null too (null converts to int[] better
than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's
tuple (new int[0] is ()).
public static NDArray nanmin(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose minimum is desired.
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.nanmin(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions (for a flat reduction: shape
(1,)*a.ndim).initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN. Anumpy.matrixoperand gets NumPy's subclass route, as in nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with+infandnp.amin.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html. Per dtype:
- float32 / float64 run NumPy's own
fminreduction schedule — the vector opminpinside each inner-loop call's vector section, the CRTfminfor its scalar tail (whose tie keeps-0over+0) — so a±0tie or an all-NaN slice can come back differently for two layouts of the same values, exactly as in NumPy. - float16 and complex128 run NumPy's sequential loops: NaN elements are skipped (complex: a NaN in either part), a tie keeps the EARLIER element, an all-NaN slice returns its first NaN verbatim.
- Integer, bool and char arrays cannot hold a NaN, so this is amin(NDArray, NDAxis?, NDArray, bool, object, NDArray); decimal likewise (no NumPy analog).
A non-empty reduced axis of an otherwise empty array returns the empty result.
A numpy.matrix operand takes NumPy's subclass branch (NaNs of a copy become +inf, np.amin
reduces it, an all-NaN slice gets np.nan): a ±0 tie follows minimum, not fmin
(np.nanmin(np.matrix([[-0.0, 0.0]])) is 0.0, where the plain array's is -0.0), and an all-NaN
slice is NumPy's positive quiet NaN (complex: nan+0j).
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout: the method stores the minima of the NaN-replaced copy into it (an all-NaN slice as+inf), then fails onout._collapse.- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmin' in the texts); an empty reduction without
initialraises (fminhas no identity; 'minimum' for anumpy.matrixoperand). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray)
Return the minimum of an array or the minimum along an axis, ignoring NaNs — NumPy's np.nanmin(a, axis=None,
out=None, keepdims=<no value>, initial=<no value>, where=<no value>), i.e.
np.fmin.reduce for an ndarray, reproduced bit for bit; the keywords behave as in
nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray). This is the only overload.
public static NDArray nanmin(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose minimum is desired.
axisNDAxis?The axis to reduce (negative counts from the end), or
nullfor every axis. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).outNDArrayThe array the result is written into and returned. Footgun: the third positional parameter, so
np.nanmin(a, 1, true)raises; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions (for a flat reduction: shape
(1,)*a.ndim).initialobjectThe value every output starts from, or
null; required withwhere.whereNDArrayA bool mask of the elements to reduce, or
null.
Returns
- NDArray
outitself when given; else a fresh array ofa's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN. Anumpy.matrixoperand gets NumPy's subclass route, as in nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with+infandnp.amin.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html. Per dtype:
- float32 / float64 run NumPy's own
fminreduction schedule — the vector opminpinside each inner-loop call's vector section, the CRTfminfor its scalar tail (whose tie keeps-0over+0) — so a±0tie or an all-NaN slice can come back differently for two layouts of the same values, exactly as in NumPy. - float16 and complex128 run NumPy's sequential loops: NaN elements are skipped (complex: a NaN in either part), a tie keeps the EARLIER element, an all-NaN slice returns its first NaN verbatim.
- Integer, bool and char arrays cannot hold a NaN, so this is amin(NDArray, NDAxis?, NDArray, bool, object, NDArray); decimal likewise (no NumPy analog).
A non-empty reduced axis of an otherwise empty array returns the empty result.
A numpy.matrix operand takes NumPy's subclass branch (NaNs of a copy become +inf, np.amin
reduces it, an all-NaN slice gets np.nan): a ±0 tie follows minimum, not fmin
(np.nanmin(np.matrix([[-0.0, 0.0]])) is 0.0, where the plain array's is -0.0), and an all-NaN
slice is NumPy's positive quiet NaN (complex: nan+0j).
Exceptions
- TypeError
outis a C# scalar ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; anumpy.matrixoperand withkeepdims: true,initialorwhere(matrix.min() got an unexpected keyword argument ...).- AttributeError
A
numpy.matrixoperand with a plainout: the method stores the minima of the NaN-replaced copy into it (an all-NaN slice as+inf), then fails onout._collapse.- ValueError
See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmin' in the texts); an empty reduction without
initialraises (fminhas no identity; 'minimum' for anumpy.matrixoperand). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array.- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- ArgumentNullException
ais null.
nanpercentile(NDArray, NDArray, int, NDArray, bool, string, bool, NDArray)
nanpercentile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray) with the
axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit
one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that
overload's.
public static NDArray nanpercentile(NDArray a, NDArray q, int axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result;50or50.0is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. NumPy divides q by 100 first (np.true_divide(q, 100)), so a percentile never takes the integer index.axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The percentiles of the non-NaN values: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanpercentile.html. NumPy's body is the engine's
(NanPercentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric percentile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 6 overloads (q as
double, double[], NDArray, by an int? or
int[] axis), which made np.nanpercentile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q: NumPy divides it by 100 first, anddividehas no text loop. Text data: NumPy's NaN test (isnanhas no text loop), or the add.reduce refusal ofnp.nanmeanfor empty text data.- ValueError
A percentile outside [0, 100] (
Percentiles must be in the range [0, 100]), an empty q of rank other than 1, an unknown method (checked only when some slice holds a value), a q of rank above 2 (q must be a scalar or 1d, unless every slice is all NaN), or an axis repeats.- AxisError
An axis is out of range.
- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea(its NaN-like NAs removed, the rest takingnp.quantile's rules; an all-NaN slice gives the NA object): a line of two or more elements holding a None-like NA (Cannot compare null that is not a nan-like value), or the store intoout(NumPy's setitem texts, e.g.could not convert string to float: 'b').- NotSupportedException
A NEP 55
StringDTypereduction along an axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
With
weightsof the reduced axes only, over data with a kept axis longer than 1: NumPy 2.4.2's own error (index 1 is out of bounds for axis 0 with size 1), reproduced.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan), q's rank and the method.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(NumPy divides it by 100 first, anddividehas no text loop); text data (NumPy's NaN test), after the axis checks.- ValueError
A percentile outside [0, 100], an empty q of rank other than 1, an unknown method, a q of rank above 2 (unless every slice is all NaN), or an axis repeats.
- ArgumentException
outdoes not have the result's shape.
nanpercentile(NDArray, NDArray, int[], NDArray, bool, string, bool, NDArray)
nanpercentile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray) with the
axes as an int[]: the overload an int[] binds, and a bare null too (null converts
to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray nanpercentile(NDArray a, NDArray q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result;50or50.0is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. NumPy divides q by 100 first (np.true_divide(q, 100)), so a percentile never takes the integer index.axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The percentiles of the non-NaN values: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanpercentile.html. NumPy's body is the engine's
(NanPercentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric percentile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 6 overloads (q as
double, double[], NDArray, by an int? or
int[] axis), which made np.nanpercentile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q: NumPy divides it by 100 first, anddividehas no text loop. Text data: NumPy's NaN test (isnanhas no text loop), or the add.reduce refusal ofnp.nanmeanfor empty text data.- ValueError
A percentile outside [0, 100] (
Percentiles must be in the range [0, 100]), an empty q of rank other than 1, an unknown method (checked only when some slice holds a value), a q of rank above 2 (q must be a scalar or 1d, unless every slice is all NaN), or an axis repeats.- AxisError
An axis is out of range.
- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea(its NaN-like NAs removed, the rest takingnp.quantile's rules; an all-NaN slice gives the NA object): a line of two or more elements holding a None-like NA (Cannot compare null that is not a nan-like value), or the store intoout(NumPy's setitem texts, e.g.could not convert string to float: 'b').- NotSupportedException
A NEP 55
StringDTypereduction along an axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
With
weightsof the reduced axes only, over data with a kept axis longer than 1: NumPy 2.4.2's own error (index 1 is out of bounds for axis 0 with size 1), reproduced.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan), q's rank and the method.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(NumPy divides it by 100 first, anddividehas no text loop); text data (NumPy's NaN test), after the axis checks.- ValueError
A percentile outside [0, 100], an empty q of rank other than 1, an unknown method, a q of rank above 2 (unless every slice is all NaN), or an axis repeats.
- ArgumentException
outdoes not have the result's shape.
nanpercentile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray)
NumPy's np.nanpercentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *,
weights=None): the q-th percentile(s) of the data along the given axes, ignoring NaNs (of the flattened data by
default).
public static NDArray nanpercentile(NDArray a, NDArray q, NDAxis? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result;50or50.0is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. NumPy divides q by 100 first (np.true_divide(q, 100)), so a percentile never takes the integer index.axisNDAxis?NumPy's
axis:null(None, the default) reduces the flattened data; one axis (negative counts from the end) or a tuple ((0, 2),new[] { 0, 2 }) reduces those axes, merged into one before the partition; the empty tuple reduces nothing.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The percentiles of the non-NaN values: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanpercentile.html. NumPy's body is the engine's
(NanPercentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric percentile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 6 overloads (q as
double, double[], NDArray, by an int? or
int[] axis), which made np.nanpercentile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q: NumPy divides it by 100 first, anddividehas no text loop. Text data: NumPy's NaN test (isnanhas no text loop), or the add.reduce refusal ofnp.nanmeanfor empty text data.- ValueError
A percentile outside [0, 100] (
Percentiles must be in the range [0, 100]), an empty q of rank other than 1, an unknown method (checked only when some slice holds a value), a q of rank above 2 (q must be a scalar or 1d, unless every slice is all NaN), or an axis repeats.- AxisError
An axis is out of range.
- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea(its NaN-like NAs removed, the rest takingnp.quantile's rules; an all-NaN slice gives the NA object): a line of two or more elements holding a None-like NA (Cannot compare null that is not a nan-like value), or the store intoout(NumPy's setitem texts, e.g.could not convert string to float: 'b').- NotSupportedException
A NEP 55
StringDTypereduction along an axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
With
weightsof the reduced axes only, over data with a kept axis longer than 1: NumPy 2.4.2's own error (index 1 is out of bounds for axis 0 with size 1), reproduced.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan), q's rank and the method.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(NumPy divides it by 100 first, anddividehas no text loop); text data (NumPy's NaN test), after the axis checks.- ValueError
A percentile outside [0, 100], an empty q of rank other than 1, an unknown method, a q of rank above 2 (unless every slice is all NaN), or an axis repeats.
- ArgumentException
outdoes not have the result's shape.
nanprod(NDArray, int, DType, NDArray, bool, object, NDArray)
nanprod(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) with the axis as one
int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nanprod(NDArray a, int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose product is desired. If a is not an array, a conversion is attempted.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypenp.prod's
dtype=: the type of the accumulator and the result, or null for np.prod's default (the input's dtype; int64 for a narrower integer or bool input).outNDArraynp.prod's
out=: the destination, of the expected output shape (returned), or null.keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
initialobjectnp.prod's
initial=: the starting value of the product (a Python scalar), or null.whereNDArraynp.prod's
where=: the bool mask of the elements to include, or null for all.
Returns
- NDArray
A new array containing the product, with NaN values treated as one (
outitself when given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanprod.html
Only applicable to float and double arrays.
For integer arrays, this is equivalent to np.prod (no NaN values possible).
NumPy's statements: a, mask = _replace_nan(a, 1); return np.prod(a, axis, dtype, out, keepdims, initial,
where).
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces <code>nanprod(a, axis, keepdims)</code>, so a positional <code>keepdims</code>
is written <code>keepdims: true</code> (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: <code>NDAxis</code>).</p>
Exceptions
- AxisError
axisis outsidea's dimensions.- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.prod() got an unexpected keyword argument 'where').
nanprod(NDArray, int[], DType, NDArray, bool, object, NDArray)
nanprod(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) with the axes as an
int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray nanprod(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose product is desired. If a is not an array, a conversion is attempted.
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypenp.prod's
dtype=: the type of the accumulator and the result, or null for np.prod's default (the input's dtype; int64 for a narrower integer or bool input).outNDArraynp.prod's
out=: the destination, of the expected output shape (returned), or null.keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
initialobjectnp.prod's
initial=: the starting value of the product (a Python scalar), or null.whereNDArraynp.prod's
where=: the bool mask of the elements to include, or null for all.
Returns
- NDArray
A new array containing the product, with NaN values treated as one (
outitself when given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanprod.html
Only applicable to float and double arrays.
For integer arrays, this is equivalent to np.prod (no NaN values possible).
NumPy's statements: a, mask = _replace_nan(a, 1); return np.prod(a, axis, dtype, out, keepdims, initial,
where).
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces <code>nanprod(a, axis, keepdims)</code>, so a positional <code>keepdims</code>
is written <code>keepdims: true</code> (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: <code>NDAxis</code>).</p>
Exceptions
- AxisError
axisis outsidea's dimensions.- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.prod() got an unexpected keyword argument 'where').
nanprod(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)
Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones.
public static NDArray nanprod(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose product is desired. If a is not an array, a conversion is attempted.
axisNDAxis?Axis or axes along which the product is computed. The default is to compute the product of the flattened array. A tuple (
(0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypenp.prod's
dtype=: the type of the accumulator and the result, or null for np.prod's default (the input's dtype; int64 for a narrower integer or bool input).outNDArraynp.prod's
out=: the destination, of the expected output shape (returned), or null.keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
initialobjectnp.prod's
initial=: the starting value of the product (a Python scalar), or null.whereNDArraynp.prod's
where=: the bool mask of the elements to include, or null for all.
Returns
- NDArray
A new array containing the product, with NaN values treated as one (
outitself when given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanprod.html
Only applicable to float and double arrays.
For integer arrays, this is equivalent to np.prod (no NaN values possible).
NumPy's statements: a, mask = _replace_nan(a, 1); return np.prod(a, axis, dtype, out, keepdims, initial,
where).
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces <code>nanprod(a, axis, keepdims)</code>, so a positional <code>keepdims</code>
is written <code>keepdims: true</code> (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: <code>NDAxis</code>).</p>
Exceptions
- AxisError
axisis outsidea's dimensions.- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.prod() got an unexpected keyword argument 'where').
nanquantile(NDArray, NDArray, int, NDArray, bool, string, bool, NDArray)
nanquantile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray) with the axis
as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nanquantile(NDArray a, NDArray q, int axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result;0.5or1is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. An integer q - a C# integer literal is NumPy's Python int, a 0-d int64 - makes methodlinear's virtual index(n - 1) * qan integer that NumPy TAKES instead of interpolating (the data's own dtype and element:np.nanquantile(int_array, 1)is an int64).axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The quantiles of the non-NaN values: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanquantile.html. NumPy's body is the engine's
(NanQuantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric quantile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 8 overloads (q as
double, double[], NDArray or long, by an int? or
int[] axis), which made np.nanquantile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q(NumPy's [0, 1] check: Python's'<=' not supported between instances of 'float' and 'numpy.str_'for a 1-d q of fewer than 10 elements,q.min()'sminimumrefusal otherwise). Text data: NumPy's NaN test (isnanhas no text loop), or the add.reduce refusal ofnp.nanmeanfor empty text data.- ValueError
A quantile outside [0, 1] (
Quantiles must be in the range [0, 1]), an empty q of rank other than 1 (itsq.min()), an unknown method (checked only when some slice holds a value), a q of rank above 2 (q must be a scalar or 1d, unless every slice is all NaN), or an axis repeats.- AxisError
An axis is out of range.
- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea(its NaN-like NAs removed, the rest takingnp.quantile's rules; an all-NaN slice gives the NA object): a line of two or more elements holding a None-like NA (Cannot compare null that is not a nan-like value), or the store intoout(NumPy's setitem texts, e.g.could not convert string to float: 'b').- NotSupportedException
A NEP 55
StringDTypereduction along an axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
With
weightsof the reduced axes only, over data with a kept axis longer than 1: NumPy 2.4.2's own error (index 1 is out of bounds for axis 0 with size 1), reproduced.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan), q's rank and the method.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(its [0, 1] check refuses); text data (NumPy's NaN test:isnanhas no text loop), after the axis checks.- ValueError
A quantile outside [0, 1], an empty q of rank other than 1, an unknown method, a q of rank above 2 (unless every slice is all NaN), or an axis repeats.
- ArgumentException
outdoes not have the result's shape.
nanquantile(NDArray, NDArray, int[], NDArray, bool, string, bool, NDArray)
nanquantile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray) with the axes
as an int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray nanquantile(NDArray a, NDArray q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result;0.5or1is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. An integer q - a C# integer literal is NumPy's Python int, a 0-d int64 - makes methodlinear's virtual index(n - 1) * qan integer that NumPy TAKES instead of interpolating (the data's own dtype and element:np.nanquantile(int_array, 1)is an int64).axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The quantiles of the non-NaN values: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanquantile.html. NumPy's body is the engine's
(NanQuantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric quantile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 8 overloads (q as
double, double[], NDArray or long, by an int? or
int[] axis), which made np.nanquantile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q(NumPy's [0, 1] check: Python's'<=' not supported between instances of 'float' and 'numpy.str_'for a 1-d q of fewer than 10 elements,q.min()'sminimumrefusal otherwise). Text data: NumPy's NaN test (isnanhas no text loop), or the add.reduce refusal ofnp.nanmeanfor empty text data.- ValueError
A quantile outside [0, 1] (
Quantiles must be in the range [0, 1]), an empty q of rank other than 1 (itsq.min()), an unknown method (checked only when some slice holds a value), a q of rank above 2 (q must be a scalar or 1d, unless every slice is all NaN), or an axis repeats.- AxisError
An axis is out of range.
- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea(its NaN-like NAs removed, the rest takingnp.quantile's rules; an all-NaN slice gives the NA object): a line of two or more elements holding a None-like NA (Cannot compare null that is not a nan-like value), or the store intoout(NumPy's setitem texts, e.g.could not convert string to float: 'b').- NotSupportedException
A NEP 55
StringDTypereduction along an axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
With
weightsof the reduced axes only, over data with a kept axis longer than 1: NumPy 2.4.2's own error (index 1 is out of bounds for axis 0 with size 1), reproduced.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan), q's rank and the method.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(its [0, 1] check refuses); text data (NumPy's NaN test:isnanhas no text loop), after the axis checks.- ValueError
A quantile outside [0, 1], an empty q of rank other than 1, an unknown method, a q of rank above 2 (unless every slice is all NaN), or an axis repeats.
- ArgumentException
outdoes not have the result's shape.
nanquantile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray)
NumPy's np.nanquantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *,
weights=None): the q-th quantile(s) of the data along the given axes, ignoring NaNs (of the flattened data by
default).
public static NDArray nanquantile(NDArray a, NDArray q, NDAxis? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result;0.5or1is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. An integer q - a C# integer literal is NumPy's Python int, a 0-d int64 - makes methodlinear's virtual index(n - 1) * qan integer that NumPy TAKES instead of interpolating (the data's own dtype and element:np.nanquantile(int_array, 1)is an int64).axisNDAxis?NumPy's
axis:null(None, the default) reduces the flattened data; one axis (negative counts from the end) or a tuple ((0, 2),new[] { 0, 2 }) reduces those axes, merged into one before the partition; the empty tuple reduces nothing.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The quantiles of the non-NaN values: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanquantile.html. NumPy's body is the engine's
(NanQuantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric quantile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 8 overloads (q as
double, double[], NDArray or long, by an int? or
int[] axis), which made np.nanquantile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q(NumPy's [0, 1] check: Python's'<=' not supported between instances of 'float' and 'numpy.str_'for a 1-d q of fewer than 10 elements,q.min()'sminimumrefusal otherwise). Text data: NumPy's NaN test (isnanhas no text loop), or the add.reduce refusal ofnp.nanmeanfor empty text data.- ValueError
A quantile outside [0, 1] (
Quantiles must be in the range [0, 1]), an empty q of rank other than 1 (itsq.min()), an unknown method (checked only when some slice holds a value), a q of rank above 2 (q must be a scalar or 1d, unless every slice is all NaN), or an axis repeats.- AxisError
An axis is out of range.
- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea(its NaN-like NAs removed, the rest takingnp.quantile's rules; an all-NaN slice gives the NA object): a line of two or more elements holding a None-like NA (Cannot compare null that is not a nan-like value), or the store intoout(NumPy's setitem texts, e.g.could not convert string to float: 'b').- NotSupportedException
A NEP 55
StringDTypereduction along an axis whose row result NumPy stores in an OBJECT array (aNoneNA object picked bynp.apply_along_axis): NumSharp has no object dtype.- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
With
weightsof the reduced axes only, over data with a kept axis longer than 1: NumPy 2.4.2's own error (index 1 is out of bounds for axis 0 with size 1), reproduced.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](empty data answersnp.nanmeanfirst), raised before the text refusals (isnan), q's rank and the method.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(its [0, 1] check refuses); text data (NumPy's NaN test:isnanhas no text loop), after the axis checks.- ValueError
A quantile outside [0, 1], an empty q of rank other than 1, an unknown method, a q of rank above 2 (unless every slice is all NaN), or an axis repeats.
- ArgumentException
outdoes not have the result's shape.
nanstd(NDArray, int, DType, NDArray, int, bool, NDArray, NDArray, int?)
nanstd(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) with the axis
as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nanstd(NDArray a, int axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe array whose standard deviation is desired; any dtype and layout.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypeThe type used to compute the variance (both sums run in it). For a float or complex input it must be inexact; null uses the input's dtype (np.std's float64 for an integer or bool input).
outNDArrayNumPy's
out=: the destination (returned); for a float or complex input it must be inexact.ddofintDelta degrees of freedom: the variance's divisor is
N - ddof, whereNis the number of non-NaN elements of each slice. Default 0.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include, or null for all.meanNDArrayNumPy's
mean=: the mean to use instead of computing it, shaped as withkeepdims=True, or null.correctionint?NumPy's
correction=, the Array-API name ofddof, or null; a non-zeroddofwith it raises.
Returns
- NDArray
The standard deviation, in the variance's dtype; a 0-d array for a flat reduction without
keepdims. A slice with no degrees of freedom left is NaN.
Remarks
NumPy's nanstd is sqrt(nanvar(...), out=var) for an array and
var.dtype.type(np.sqrt(var)) for a scalar; for an array that cannot hold NaN that is exactly
std(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?).
https://numpy.org/doc/stable/reference/generated/numpy.nanstd.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanstd(a, axis, keepdims, ddof, dtype), so dtype is the third
argument, ddof the fifth, and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- ValueError
A non-zero
ddofwithcorrection: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis outsidea's dimensions (a 0-d array included).- TypeError
An integer or bool input with an integer
dtypeand an array result: NumPy's "Cannot cast ufunc 'sqrt' output ..." error, as np.std raises it.- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nanstd(NDArray, int[], DType, NDArray, int, bool, NDArray, NDArray, int?)
nanstd(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) with the axes
as an int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray nanstd(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe array whose standard deviation is desired; any dtype and layout.
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypeThe type used to compute the variance (both sums run in it). For a float or complex input it must be inexact; null uses the input's dtype (np.std's float64 for an integer or bool input).
outNDArrayNumPy's
out=: the destination (returned); for a float or complex input it must be inexact.ddofintDelta degrees of freedom: the variance's divisor is
N - ddof, whereNis the number of non-NaN elements of each slice. Default 0.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include, or null for all.meanNDArrayNumPy's
mean=: the mean to use instead of computing it, shaped as withkeepdims=True, or null.correctionint?NumPy's
correction=, the Array-API name ofddof, or null; a non-zeroddofwith it raises.
Returns
- NDArray
The standard deviation, in the variance's dtype; a 0-d array for a flat reduction without
keepdims. A slice with no degrees of freedom left is NaN.
Remarks
NumPy's nanstd is sqrt(nanvar(...), out=var) for an array and
var.dtype.type(np.sqrt(var)) for a scalar; for an array that cannot hold NaN that is exactly
std(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?).
https://numpy.org/doc/stable/reference/generated/numpy.nanstd.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanstd(a, axis, keepdims, ddof, dtype), so dtype is the third
argument, ddof the fifth, and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- ValueError
A non-zero
ddofwithcorrection: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis outsidea's dimensions (a 0-d array included).- TypeError
An integer or bool input with an integer
dtypeand an array result: NumPy's "Cannot cast ufunc 'sqrt' output ..." error, as np.std raises it.- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nanstd(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)
Compute the standard deviation along the specified axis, while ignoring NaNs: NumPy's numpy.nanstd, the
square root of nanvar(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) taken as NumPy takes it.
public static NDArray nanstd(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe array whose standard deviation is desired; any dtype and layout.
axisNDAxis?The axis along which the standard deviation is computed (negative counts from the end); null (the default) computes it over the flattened array. A tuple (
(0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypeThe type used to compute the variance (both sums run in it). For a float or complex input it must be inexact; null uses the input's dtype (np.std's float64 for an integer or bool input).
outNDArrayNumPy's
out=: the destination (returned); for a float or complex input it must be inexact.ddofintDelta degrees of freedom: the variance's divisor is
N - ddof, whereNis the number of non-NaN elements of each slice. Default 0.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include, or null for all.meanNDArrayNumPy's
mean=: the mean to use instead of computing it, shaped as withkeepdims=True, or null.correctionint?NumPy's
correction=, the Array-API name ofddof, or null; a non-zeroddofwith it raises.
Returns
- NDArray
The standard deviation, in the variance's dtype; a 0-d array for a flat reduction without
keepdims. A slice with no degrees of freedom left is NaN.
Remarks
NumPy's nanstd is sqrt(nanvar(...), out=var) for an array and
var.dtype.type(np.sqrt(var)) for a scalar; for an array that cannot hold NaN that is exactly
std(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?).
https://numpy.org/doc/stable/reference/generated/numpy.nanstd.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanstd(a, axis, keepdims, ddof, dtype), so dtype is the third
argument, ddof the fifth, and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- ValueError
A non-zero
ddofwithcorrection: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis outsidea's dimensions (a 0-d array included).- TypeError
An integer or bool input with an integer
dtypeand an array result: NumPy's "Cannot cast ufunc 'sqrt' output ..." error, as np.std raises it.- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nansum(NDArray, int, DType, NDArray, bool, object, NDArray)
nansum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) with the axis as one
int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nansum(NDArray a, int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose sum is desired. If a is not an array, a conversion is attempted.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypenp.sum's
dtype=: the type of the accumulator and the result, or null for np.sum's default (the input's dtype; int64 for a narrower integer or bool input).outNDArraynp.sum's
out=: the destination, of the expected output shape (returned), or null.keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
initialobjectnp.sum's
initial=: the starting value of the sum (a Python scalar), or null.whereNDArraynp.sum's
where=: the bool mask of the elements to include, or null for all.
Returns
- NDArray
A new array containing the sum, with NaN values treated as zero (
outitself when given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nansum.html
Only applicable to float and double arrays.
For integer arrays, this is equivalent to np.sum (no NaN values possible).
NumPy's statements: a, mask = _replace_nan(a, 0); return np.sum(a, axis, dtype, out, keepdims, initial,
where).
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces <code>nansum(a, axis, keepdims)</code>, so a positional <code>keepdims</code>
is written <code>keepdims: true</code> (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: <code>NDAxis</code>).</p>
Exceptions
- AxisError
axisis outsidea's dimensions.- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nansum(NDArray, int[], DType, NDArray, bool, object, NDArray)
nansum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) with the axes as an
int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray nansum(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose sum is desired. If a is not an array, a conversion is attempted.
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypenp.sum's
dtype=: the type of the accumulator and the result, or null for np.sum's default (the input's dtype; int64 for a narrower integer or bool input).outNDArraynp.sum's
out=: the destination, of the expected output shape (returned), or null.keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
initialobjectnp.sum's
initial=: the starting value of the sum (a Python scalar), or null.whereNDArraynp.sum's
where=: the bool mask of the elements to include, or null for all.
Returns
- NDArray
A new array containing the sum, with NaN values treated as zero (
outitself when given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nansum.html
Only applicable to float and double arrays.
For integer arrays, this is equivalent to np.sum (no NaN values possible).
NumPy's statements: a, mask = _replace_nan(a, 0); return np.sum(a, axis, dtype, out, keepdims, initial,
where).
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces <code>nansum(a, axis, keepdims)</code>, so a positional <code>keepdims</code>
is written <code>keepdims: true</code> (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: <code>NDAxis</code>).</p>
Exceptions
- AxisError
axisis outsidea's dimensions.- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nansum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)
Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
public static NDArray nansum(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayArray containing numbers whose sum is desired. If a is not an array, a conversion is attempted.
axisNDAxis?Axis or axes along which the sum is computed. The default is to compute the sum of the flattened array. A tuple (
(0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypenp.sum's
dtype=: the type of the accumulator and the result, or null for np.sum's default (the input's dtype; int64 for a narrower integer or bool input).outNDArraynp.sum's
out=: the destination, of the expected output shape (returned), or null.keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
initialobjectnp.sum's
initial=: the starting value of the sum (a Python scalar), or null.whereNDArraynp.sum's
where=: the bool mask of the elements to include, or null for all.
Returns
- NDArray
A new array containing the sum, with NaN values treated as zero (
outitself when given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nansum.html
Only applicable to float and double arrays.
For integer arrays, this is equivalent to np.sum (no NaN values possible).
NumPy's statements: a, mask = _replace_nan(a, 0); return np.sum(a, axis, dtype, out, keepdims, initial,
where).
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces <code>nansum(a, axis, keepdims)</code>, so a positional <code>keepdims</code>
is written <code>keepdims: true</code> (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: <code>NDAxis</code>).</p>
Exceptions
- AxisError
axisis outsidea's dimensions.- ValueError
A tuple that names an axis twice (
duplicate value in 'axis').- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nanvar(NDArray, int, DType, NDArray, int, bool, NDArray, NDArray, int?)
nanvar(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) with the axis
as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray nanvar(NDArray a, int axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe array whose variance is desired; any dtype and layout.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypeThe type used to compute the variance (both sums run in it). For a float or complex input it must be inexact; null uses the input's dtype (np.var's float64 for an integer or bool input).
outNDArrayNumPy's
out=: the destination (returned); for a float or complex input it must be inexact.ddofintDelta degrees of freedom: the divisor is
N - ddof. Default 0.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include, or null for all.meanNDArrayNumPy's
mean=: the mean to use instead of computing it, shaped as withkeepdims=True, or null.correctionint?NumPy's
correction=, the Array-API name ofddof, or null; a non-zeroddofwith it raises.
Returns
- NDArray
The variance, in
dtypeor the input's float dtype (float64 for a complex input and for an integer or bool one); a 0-d array for a flat reduction withoutkeepdims. A slice with no degrees of freedom left (all NaN, orddofat or past its non-NaN count) is NaN.
Remarks
An array that cannot hold NaN (integer, bool, char, decimal) has no NaN to ignore: the result is
var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)'s, keywords included. For a float or complex array the
arithmetic is NumPy's _nanfunctions_impl.nanvar (see TensorEngine.NanVar), which
differs from np.var in three observable ways: the deviations are rounded into the input's dtype before they
are squared (with dtype=float64, a float32 input squares float32 deviations), a complex square is the
real part of the complex product x * conj(x), and a slice without degrees of freedom is NaN (np.var
gives +inf there).
https://numpy.org/doc/stable/reference/generated/numpy.nanvar.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanvar(a, axis, keepdims, ddof, dtype), so dtype is the third
argument, ddof the fifth, and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- ValueError
A non-zero
ddofwithcorrection: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis outsidea's dimensions (a 0-d array included).- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nanvar(NDArray, int[], DType, NDArray, int, bool, NDArray, NDArray, int?)
nanvar(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) with the axes
as an int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray nanvar(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe array whose variance is desired; any dtype and layout.
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypeThe type used to compute the variance (both sums run in it). For a float or complex input it must be inexact; null uses the input's dtype (np.var's float64 for an integer or bool input).
outNDArrayNumPy's
out=: the destination (returned); for a float or complex input it must be inexact.ddofintDelta degrees of freedom: the divisor is
N - ddof. Default 0.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include, or null for all.meanNDArrayNumPy's
mean=: the mean to use instead of computing it, shaped as withkeepdims=True, or null.correctionint?NumPy's
correction=, the Array-API name ofddof, or null; a non-zeroddofwith it raises.
Returns
- NDArray
The variance, in
dtypeor the input's float dtype (float64 for a complex input and for an integer or bool one); a 0-d array for a flat reduction withoutkeepdims. A slice with no degrees of freedom left (all NaN, orddofat or past its non-NaN count) is NaN.
Remarks
An array that cannot hold NaN (integer, bool, char, decimal) has no NaN to ignore: the result is
var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)'s, keywords included. For a float or complex array the
arithmetic is NumPy's _nanfunctions_impl.nanvar (see TensorEngine.NanVar), which
differs from np.var in three observable ways: the deviations are rounded into the input's dtype before they
are squared (with dtype=float64, a float32 input squares float32 deviations), a complex square is the
real part of the complex product x * conj(x), and a slice without degrees of freedom is NaN (np.var
gives +inf there).
https://numpy.org/doc/stable/reference/generated/numpy.nanvar.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanvar(a, axis, keepdims, ddof, dtype), so dtype is the third
argument, ddof the fifth, and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- ValueError
A non-zero
ddofwithcorrection: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis outsidea's dimensions (a 0-d array included).- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
nanvar(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)
Compute the variance along the specified axis, while ignoring NaNs: NumPy's numpy.nanvar, statement for
statement. NaNs count neither in the mean nor in the divisor N - ddof, where N is the number of
non-NaN elements of each slice.
public static NDArray nanvar(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe array whose variance is desired; any dtype and layout.
axisNDAxis?The axis along which the variance is computed (negative counts from the end); null (the default) computes the variance of the flattened array. A tuple (
(0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypeThe type used to compute the variance (both sums run in it). For a float or complex input it must be inexact; null uses the input's dtype (np.var's float64 for an integer or bool input).
outNDArrayNumPy's
out=: the destination (returned); for a float or complex input it must be inexact.ddofintDelta degrees of freedom: the divisor is
N - ddof. Default 0.keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one.
whereNDArrayNumPy's
where=: the bool mask of the elements to include, or null for all.meanNDArrayNumPy's
mean=: the mean to use instead of computing it, shaped as withkeepdims=True, or null.correctionint?NumPy's
correction=, the Array-API name ofddof, or null; a non-zeroddofwith it raises.
Returns
- NDArray
The variance, in
dtypeor the input's float dtype (float64 for a complex input and for an integer or bool one); a 0-d array for a flat reduction withoutkeepdims. A slice with no degrees of freedom left (all NaN, orddofat or past its non-NaN count) is NaN.
Remarks
An array that cannot hold NaN (integer, bool, char, decimal) has no NaN to ignore: the result is
var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)'s, keywords included. For a float or complex array the
arithmetic is NumPy's _nanfunctions_impl.nanvar (see TensorEngine.NanVar), which
differs from np.var in three observable ways: the deviations are rounded into the input's dtype before they
are squared (with dtype=float64, a float32 input squares float32 deviations), a complex square is the
real part of the complex product x * conj(x), and a slice without degrees of freedom is NaN (np.var
gives +inf there).
https://numpy.org/doc/stable/reference/generated/numpy.nanvar.html
One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces nanvar(a, axis, keepdims, ddof, dtype), so dtype is the third
argument, ddof the fifth, and a positional keepdims
is written keepdims: true (a bool in the dtype slot does not compile). A tuple axis waits for the
owner's axis type (OD1, decided: NDAxis).
Exceptions
- TypeError
A float or complex
awith a non-inexactdtype: "If a is inexact, then dtype must be inexact"; or with a non-inexactout: "If a is inexact, then out must be inexact".- ValueError
A non-zero
ddofwithcorrection: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis outsidea's dimensions (a 0-d array included).- TypeError
A
numpy.matrixoperand withkeepdims: true,initial=orwhere=: NumPy calls the matrix method, which has no such keyword (matrix.sum() got an unexpected keyword argument 'where').
ndarray(Shape, DType, object, long, long[], char?)
Constructs an array — NumPy's low-level numpy.ndarray(shape, dtype=float, buffer=None, offset=0,
strides=None, order=None). Without a buffer it allocates an UNINITIALIZED array, like
empty(Shape, DType, char, string); with a buffer it lays the array over the buffer's BYTES without
copying them, so writes through the result change the buffer.
public static NDArray ndarray(Shape shape, DType dtype = null, object buffer = null, long offset = 0, long[] strides = null, char? order = null)
Parameters
shapeShapeThe dimensions. Only Dimensions is read: the strides come from
stridesororder. With a buffer, the one-dimensional shape-1takes every whole element afteroffset.default(Shape)is NumPy'sNoneand is refused.dtypeDTypeThe element type; null is float64 (NumPy's default). With a buffer, the buffer's bytes are read as this type, whatever the buffer's own element type.
bufferobjectThe memory to use, or null to allocate. A C- or F-contiguous NDArray, its data (np.MemoryView), an IArraySlice, a C# array of any rank whose elements hold no references (pinned while the result lives), an ArraySegment<T> or Memory<T> of bytes, a ReadOnlyMemory<T> of bytes (read-only, NumPy's
bytes), or a Half, char or decimal value (a read-only copy of its bytes, as a NumPy scalar exports). A larger buffer than needed is fine: the array uses a part of it.offsetlongThe byte offset of the first element into
buffer. Ignored without a buffer, as in NumPy. It need not be a multiple of the element size (the result is then notALIGNED).strideslong[]The BYTE stride of every axis (NumPy's unit, as strides reports), or null for the strides of
order. Checked against the buffer, or against the array's own size without one. A stride of 0 repeats elements and keeps the array writeable.orderchar?'C'or'F'for the row-major or column-major strides;null(NumPy'sNone, the default) is'C','A'and'K'mean'C'here, and lowercase is accepted. Ignored whenstridesis given.
Returns
- NDArray
Without a buffer: a new array that owns its uninitialized memory (an empty one has all-zero strides, as NumPy allocates it). With a buffer: a view of the buffer that does not own its data, whose
baseis the buffer's owner (an array) or auint8array over the whole buffer, writeable when the buffer is, andALIGNEDas NumPy computes it from the data pointer and the strides.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html. The checks run in NumPy's order
(array_new in numpy/_core/src/multiarray/arrayobject.c): the buffer, the order, the strides'
length, the strides against the buffer, the shape -1 or the too-small check, then the dimensions.
The shape and dtype are converted by C# before the call, so a bad dtype string fails first even when the
shape is also bad (NumPy reports the shape).
Safer than NumPy. NumPy's own checks let four inputs through that read outside the buffer: a negative
offset, the shape -1 with a negative stride, an offset near 2^63 (its arithmetic wraps), and strides
over an empty buffer. After NumPy's checks pass, NumSharp checks the exact byte range and refuses those, with
the strides error when strides were given, else the offset error of frombuffer(byte[], DType, long, long)
for a negative offset, else the too-small error.
Lifetime. The result keeps the buffer's memory alive: a NumSharp array buffer may be disposed while the result lives, and a C# array stays pinned until the last array over it is disposed or collected. Pinning a large managed array for a long time fragments the managed heap, so dispose the result when done.
Divergences (pinned by [Misaligned] tests): a non-native dtype ('>i4', '>U2')
with a buffer DECODES the bytes into a new native array instead of viewing them, and without a buffer
allocates the native dtype (NumSharp has no big-endian storage); complex64 does not exist; a
multi-character order string cannot be expressed; a view of an unaligned result reports ALIGNED
again; an unsized string dtype is refused (NumPy builds a zero-width S0/U0 array, and for the
shape (-1,) over a buffer it divides by the zero item size and crashes the process).
Strings. A sized S/U dtype reads the bytes as fixed-width elements, exactly as NumPy
does: np.ndarray((4,), 'S3', buffer=b'abcdefghijkl') is [b'abc', b'def', b'ghi', b'jkl'], and a
U dtype reads native UCS-4 code points (a code point above U+10FFFF is stored, and NumPy's
SystemError is raised only when that element is read). A string array buffer viewed with another
string width or class ('<U1' over a '<U2' array) is an alias of its bytes, never its
elements.
StringDType. Without a buffer the array's 16-byte cells are zeroed (every element '', NumPy's
NPY_NEEDS_INIT). With a buffer, a StringDType dtype over a StringDType array is NumPy's
view of its cells (offset and strides in bytes, whole cells), sharing the array's allocator, with the
requested descriptor's NA object and coercion. NumPy also lays any other dtype over a StringDType
array's raw cells, and a StringDType array over any bytes; NumSharp refuses both, because a cell of a
long text is a reference into its allocator (a writable numeric view could corrupt it, and raw bytes have no
allocator). np.frombuffer(a.tobytes(), dtype) reads the same cells as a copy.
Exceptions
- TypeError
shapeisdefault(Shape)(Use () not None as shape arguments);bufferis not a buffer (a bytes-like object is required, not 'list'); or the buffer is too small withoutstrides(buffer is too small for requested array).- ValueError
orderis invalid;strideshas the wrong length or does not fit the buffer (strides is incompatible with shape of requested array and size of buffer); a dimension is negative or the byte count overflows; an NDArray buffer is not contiguous (ndarray is not contiguous); or a negativeoffsetputs elements before the buffer.- BufferError
A np.MemoryView buffer over a non-contiguous array.
- NotSupportedException
A stride that addresses elements is not a multiple of the element size (NumSharp stores strides in whole elements),
dtypehas no storage yet (datetime64), ordtypeis an UNSIZED string ('S','U',np.str_): NumPy builds a zero-widthS0/U0array here, which NumSharp's string buffers cannot hold. With a buffer andStringDTypeon either side: another dtype over aStringDTypearray's cells, aStringDTypedtype over any other buffer, or an offset that splits a cell (NumPy lays the array anyway; see the remarks).
ndenumerate(NDArray)
Multidimensional index iterator — returns an iterator yielding pairs of array coordinates and values.
public static np.NDEnumerate ndenumerate(NDArray arr)
Parameters
arrNDArrayInput array. Anything implicitly convertible to NDArray works (
new[,] {{1, 2}, {3, 4}}, a scalar, …), matching NumPy'snp.asarray(arr)coercion of array_like input.
Returns
Remarks
ndenumerate<T>(NDArray)
Typed form of ndenumerate(NDArray) — yields T
instead of a boxed object. NumSharp extension (NumPy has no typed variant,
because Python has no unboxed generics); prefer it in hot loops, where the boxing
of the untyped form dominates the walk.
public static np.NDEnumerate<T> ndenumerate<T>(NDArray arr) where T : unmanaged
Parameters
arrNDArray
Returns
- np.NDEnumerate<T>
Type Parameters
TMust be the array's element type — no conversion is performed.
ndim(NDArray)
Return the number of dimensions of an array (NumPy's np.ndim, the module function beside the
ndim property).
public static int ndim(NDArray a)
Parameters
aNDArrayInput array (NumPy's keyword
a). A C# scalar converts to a 0-d array and a C# array to an array of its rank, sonp.ndim(5)is 0 as in NumPy.
Returns
- int
The number of dimensions in
a; a scalar is zero-dimensional.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ndim.html
NumPy's statements: a.ndim, or asarray(a).ndim for an object without the attribute (the
implicit conversions to NDArray are that asarray here). No collision with the
ndim members of NDArray or of the iterator / memory-view types nested in np: those
are instance members of other classes, and inside a nested type its own member wins the name lookup.
Exceptions
- ArgumentNullException
ais null (NumSharp has no object dtype for NumPy'snp.ndim(None), which is 0; size(NDArray, NDAxis?) refuses null the same way).
ndindex(int[])
int[] overload — long[] is the house shape type, but an existing
int[] does not convert to it by array covariance, so it gets its own entry.
Deliberately NOT params: individual int arguments already widen into
the params long[] form, and a second params overload would make the
zero-argument call np.ndindex() ambiguous.
public static np.NDIndex ndindex(int[] shape)
Parameters
shapeint[]
Returns
ndindex(params long[])
An N-dimensional iterator object to index arrays.
Given the shape of an array, an np.NDIndex instance iterates over the N-dimensional index of the array. At each iteration an index array is returned; the last dimension is iterated over first.
public static np.NDIndex ndindex(params long[] shape)
Parameters
shapelong[]The size of each dimension, passed as individual parameters (
np.ndindex(3, 2, 1)) or as a single array (np.ndindex(arr.shape)). Both spellings bind to this oneparamsoverload, so NumPy's "ints, or a single tuple of ints" rule holds for free.
Returns
Remarks
nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long)
Efficient multi-dimensional iterator object to iterate over arrays.
public static np.NDIterator nditer(NDArray op, string[] flags = null, string[] op_flags = null, DType[] op_dtypes = null, char order = 'K', string casting = "safe", int[][] op_axes = null, long[] itershape = null, long buffersize = 0)
Parameters
opNDArrayThe array to iterate over.
flagsstring[]Flags controlling iterator behaviour:
buffered,c_index,f_index,multi_index,common_dtype,copy_if_overlap,delay_bufalloc,external_loop,grow_inner(a.k.a.growinner),ranged,refs_ok,reduce_ok,zerosize_ok.op_flagsstring[]Per-operand flags:
readonly(default),readwrite,writeonly,allocate,no_broadcast,contig,aligned,nbo,copy,updateifcopy,no_subtype,arraymask,writemasked,overlap_assume_elementwise,virtual.op_dtypesDType[]The required data type(s) of the operands — one per operand, null for "the operand's own". An unsized string request (
"U","S") is adapted to its operand ('U'over an int64 array is<U21). A request other than the operand's dtype is a CAST: it must satisfycastingin the read direction (and the write-back direction for a written operand), and it needsbuffered, acopy/updateifcopyoperand flag, or a read-only 0-d operand (copied automatically) — else NumPy'sTypeError. A list whose length is not the operand count is NumPy'sTypeErrortoo.ordercharIteration order:
'C','F','A'or'K'(default).castingstringCasting rule when making a copy or buffering:
"no","equiv","safe"(default),"same_kind","unsafe".op_axesint[][]Per-operand list of axes, mapping iterator dimensions to operand dimensions (-1 = newaxis).
itershapelong[]The desired shape of the iterator; a negative entry is deduced from the operands, and its length must equal the
op_axesentries' (withoutop_axesit sets the rank).buffersizelongBuffer size to use when buffering is enabled; 0 selects the default.
Returns
- np.NDIterator
The iterator (dispose it: close() resolves its write-backs).
Remarks
Fixed-width strings (S, U) iterate like any dtype: each step yields 0-d <U3 views (1-D
chunks under external_loop), a buffered op_dtypes request widens, truncates or converts between
S and U (ASCII only, NumPy's Unicode errors otherwise), and a readwrite view writes through.
Text and numbers convert both ways with NumPy's rules (a number's str(); a text parsed by int() /
float(), NumPy's ValueError when it does not parse). A NEP 55 StringDType operand (with
refs_ok) is buffered and cast like any other: each buffer has its own string allocator, a transfer
duplicates every string or runs the StringDType cast of the pair (NA values follow the cast's NA rules),
and the views read and write the strings of the memory they are on.
https://numpy.org/doc/stable/reference/generated/numpy.nditer.html
Exceptions
- ValueError
NumPy's argument and flag errors (verbatim texts), or a text that does not parse as the number a copy or the first buffer fill reads it into (NumPy's
int()/float()texts).- TypeError
A
StringDTypeoperand, or aStringDTyperequest over another operand, withoutrefs_ok(checked per operand, before the iteration shape, as NumPy checks it; an output the iterator allocates is not checked); a refused cast, or a cast operand neither copied nor buffered.- OverflowError
A text read into an integer dtype by a copy or the first buffer fill holds a number outside that dtype (NumPy's OverflowError).
- MemoryError
A NEP 55
StringDTypecopy or buffer transfer cannot allocate a string (NumPy'sMemoryErrortexts).
nditer(NDArray[], string[], string[][], DType[], char, string, int[][], long[], long)
Multi-operand form — NumPy's np.nditer([a, b, …]). A null entry in
op is an output slot to be ALLOCATED by the iterator (NumPy's
None), which then defaults to writeonly, allocate.
public static np.NDIterator nditer(NDArray[] op, string[] flags = null, string[][] op_flags = null, DType[] op_dtypes = null, char order = 'K', string casting = "safe", int[][] op_axes = null, long[] itershape = null, long buffersize = 0)
Parameters
opNDArray[]The operands to iterate over together (they broadcast against each other); a null entry is an output the iterator allocates.
flagsstring[]Flags controlling iterator behaviour:
buffered,c_index,f_index,multi_index,common_dtype,copy_if_overlap,delay_bufalloc,external_loop,grow_inner(a.k.a.growinner),ranged,refs_ok,reduce_ok,zerosize_ok.op_flagsstring[][]One flag list per operand. A SINGLE inner list is broadcast to every operand — NumPy's "flat list of strings applies to all operands" convenience.
op_dtypesDType[]The required data type(s) of the operands — one per operand, null for "the operand's own". An unsized string request (
"U","S") is adapted to its operand ('U'over an int64 array is<U21). A request other than the operand's dtype is a CAST: it must satisfycastingin the read direction (and the write-back direction for a written operand), and it needsbuffered, acopy/updateifcopyoperand flag, or a read-only 0-d operand (copied automatically) — else NumPy'sTypeError. A list whose length is not the operand count is NumPy'sTypeErrortoo.ordercharIteration order:
'C','F','A'or'K'(default).castingstringCasting rule when making a copy or buffering:
"no","equiv","safe"(default),"same_kind","unsafe".op_axesint[][]Per-operand list of axes, mapping iterator dimensions to operand dimensions (-1 = newaxis).
itershapelong[]The desired shape of the iterator; a negative entry is deduced from the operands, and its length must equal the
op_axesentries' (withoutop_axesit sets the rank).buffersizelongBuffer size to use when buffering is enabled; 0 selects the default.
Returns
- np.NDIterator
The iterator (dispose it: close() resolves its write-backs).
Remarks
Fixed-width strings (S, U) iterate like any dtype: each step yields 0-d <U3 views (1-D
chunks under external_loop), a buffered op_dtypes request widens, truncates or converts between
S and U (ASCII only, NumPy's Unicode errors otherwise), and a readwrite view writes through.
Text and numbers convert both ways with NumPy's rules (a number's str(); a text parsed by int() /
float(), NumPy's ValueError when it does not parse). A NEP 55 StringDType operand (with
refs_ok) is buffered and cast like any other: each buffer has its own string allocator, a transfer
duplicates every string or runs the StringDType cast of the pair (NA values follow the cast's NA rules),
and the views read and write the strings of the memory they are on.
https://numpy.org/doc/stable/reference/generated/numpy.nditer.html
Exceptions
- ValueError
NumPy's argument and flag errors (verbatim texts), or a text that does not parse as the number a copy or the first buffer fill reads it into (NumPy's
int()/float()texts).- TypeError
A
StringDTypeoperand, or aStringDTyperequest over another operand, withoutrefs_ok(checked per operand, before the iteration shape, as NumPy checks it; an output the iterator allocates is not checked); a refused cast, or a cast operand neither copied nor buffered.- OverflowError
A text read into an integer dtype by a copy or the first buffer fill holds a number outside that dtype (NumPy's OverflowError).
- MemoryError
A NEP 55
StringDTypecopy or buffer transfer cannot allocate a string (NumPy'sMemoryErrortexts).
nditer_chunks<T>(NDArray, bool, char)
Typed CHUNK iteration — hands out a Span<T> per inner loop rather than
one element at a time, so the body can be vectorized or passed to
TensorPrimitives. The typed analogue of NumPy's external_loop, except
that a Span<T> is directly consumable by .NET's vector APIs where
NumPy's chunk is another ndarray.
foreach (Span<double> chunk in np.nditer_chunks<double>(a, writeable: true))
TensorPrimitives.Multiply(chunk, 2.0, chunk);
A C-contiguous array arrives as a SINGLE chunk covering the whole array — and so do F-contiguous, transposed and reversed views, which the iterator coalesces.
public static np.NDChunkIter<T> nditer_chunks<T>(NDArray op, bool writeable = false, char order = 'K') where T : unmanaged
Parameters
opNDArrayThe array to iterate over.
writeableboolOpen the operand
readwriteso assignments through therefreach the array. Broadcast views are read-only and are rejected, with NumPy's message.ordercharIteration order:
'K'(default, memory order — matches NumPy'snp.nditer),'C','F'or'A'. See np.NDRefIter<T> for why the default is NOT logical C-order.
Returns
- np.NDChunkIter<T>
Type Parameters
TMust be EXACTLY the array's element type — no conversion or casting is performed, because a
refcannot convert. A mismatch throws rather than reinterpreting the bytes.
Remarks
NumSharp extension: NumPy has no typed iteration, because Python has no unboxed
generics. The traversal is NumSharp's NDIterRef — the same engine
np.nditer drives — so every memory layout behaves identically; all that is
gone is the per-element NDArray view, which is what made the boxed
form slow.
Empty arrays iterate zero times, where the boxed np.nditer raises
"Iteration of zero-sized operands is not enabled" unless given NumPy's
zerosize_ok flag. Deliberate: throwing would force every caller to guard a
foreach with if (a.size > 0), which is not how C# collections
behave, and this is an extension rather than a parity surface.
nditer<T>(NDArray, bool, char)
Typed, allocation-free element iteration — the unboxed counterpart of
nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long).
Yields ref T straight into the operand's memory, so reading costs a
dereference and writing goes through to the array.
// read
foreach (ref double x in np.nditer<double>(a))
total += x;
// write in place
foreach (ref double x in np.nditer<double>(a, writeable: true))
x *= 2;
public static np.NDRefIter<T> nditer<T>(NDArray op, bool writeable = false, char order = 'K') where T : unmanaged
Parameters
opNDArrayThe array to iterate over.
writeableboolOpen the operand
readwriteso assignments through therefreach the array. Broadcast views are read-only and are rejected, with NumPy's message.ordercharIteration order:
'K'(default, memory order — matches NumPy'snp.nditer),'C','F'or'A'. See np.NDRefIter<T> for why the default is NOT logical C-order.
Returns
Type Parameters
TMust be EXACTLY the array's element type — no conversion or casting is performed, because a
refcannot convert. A mismatch throws rather than reinterpreting the bytes.
Remarks
NumSharp extension: NumPy has no typed iteration, because Python has no unboxed
generics. The traversal is NumSharp's NDIterRef — the same engine
np.nditer drives — so every memory layout behaves identically; all that is
gone is the per-element NDArray view, which is what made the boxed
form slow.
Empty arrays iterate zero times, where the boxed np.nditer raises
"Iteration of zero-sized operands is not enabled" unless given NumPy's
zerosize_ok flag. Deliberate: throwing would force every caller to guard a
foreach with if (a.size > 0), which is not how C# collections
behave, and this is an extension rather than a parity surface.
negative(NDArray, NDArray, NDArray, DType)
Numerical negative, element-wise.
Mirrors NumPy's ufunc signature: negative(x, /, out=None, *, where=True, dtype=None).
public static NDArray negative(NDArray nd, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
ndNDArrayoutNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop, so negative(bool, dtype: float64) is legal while plain negative(bool) raises (NumPy parity).
Returns
Remarks
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.).
nested_iters(NDArray, int[][], string[], string[][], DType[], char, string, long)
Create nditers for use in nested loops (NumPy's np.nested_iters). Returns one
np.NDIterator per entry in axes, outermost first, all
iterating the SAME operand buffer over different axis subsets. Advancing an outer
iterator re-bases every inner iterator to its new position — so a
foreach (var _ in i) foreach (var _ in j) ... walks the array in nested loops.
public static np.NDIterator[] nested_iters(NDArray op, int[][] axes, string[] flags = null, string[][] op_flags = null, DType[] op_dtypes = null, char order = 'K', string casting = "safe", long buffersize = 0)
Parameters
opNDArrayThe array to iterate over.
axesint[][]One integer list per nesting level; each is used as the
op_axesfor that level's iterator. Must have at least 2 entries, and no axis may appear in more than one entry.flagsstring[]Global iterator flags (see nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long)).
op_flagsstring[][]Per-operand flags.
op_dtypesDType[]Per-operand iteration dtypes.
ordercharIteration order ('C'/'F'/'A'/'K').
castingstringCasting rule.
buffersizelongBuffer size (applied to the innermost level only, as in NumPy).
Returns
- NDIterator[]
One iterator per level of
axes, outermost first.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nested_iters.html
Parity: the levels are built as NumPy's NpyIter_NestedIters builds them — only the innermost level
is buffered (and keeps external_loop); with buffering, a requested dtype moves to that level
(the outer levels iterate the operand as it is); copies and allocated outputs are made by the first
level and shared by the rest. The value streams and multi-indices match NumPy 2.4.2, fixed-width strings
included (buffered width and class conversions on the inner level).
Exceptions
- ValueError
In NumPy's order: a flag, order or casting value its converters refuse (they run while the arguments are parsed, before anything else);
axesthat is null, has fewer than two entries, a null entry, a negative axis or an axis used twice; no operand (Must provide at least one operand); then the iterator construction's own errors.
nested_iters(NDArray[], int[][], string[], string[][], DType[], char, string, long)
Create nditers for use in nested loops (NumPy's np.nested_iters). Returns one
np.NDIterator per entry in axes, outermost first, all
iterating the SAME operand buffer over different axis subsets. Advancing an outer
iterator re-bases every inner iterator to its new position — so a
foreach (var _ in i) foreach (var _ in j) ... walks the array in nested loops.
public static np.NDIterator[] nested_iters(NDArray[] op, int[][] axes, string[] flags = null, string[][] op_flags = null, DType[] op_dtypes = null, char order = 'K', string casting = "safe", long buffersize = 0)
Parameters
opNDArray[]The array to iterate over.
axesint[][]One integer list per nesting level; each is used as the
op_axesfor that level's iterator. Must have at least 2 entries, and no axis may appear in more than one entry.flagsstring[]Global iterator flags (see nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long)).
op_flagsstring[][]Per-operand flags.
op_dtypesDType[]Per-operand iteration dtypes.
ordercharIteration order ('C'/'F'/'A'/'K').
castingstringCasting rule.
buffersizelongBuffer size (applied to the innermost level only, as in NumPy).
Returns
- NDIterator[]
One iterator per level of
axes, outermost first.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nested_iters.html
Parity: the levels are built as NumPy's NpyIter_NestedIters builds them — only the innermost level
is buffered (and keeps external_loop); with buffering, a requested dtype moves to that level
(the outer levels iterate the operand as it is); copies and allocated outputs are made by the first
level and shared by the rest. The value streams and multi-indices match NumPy 2.4.2, fixed-width strings
included (buffered width and class conversions on the inner level).
Exceptions
- ValueError
In NumPy's order: a flag, order or casting value its converters refuse (they run while the arguments are parsed, before anything else);
axesthat is null, has fewer than two entries, a null entry, a negative axis or an axis used twice; no operand (Must provide at least one operand); then the iterator construction's own errors.
nextafter(NDArray, NDArray, NDArray, NDArray, DType)
Return the next floating-point value after x1 towards x2, element-wise.
Mirrors NumPy's ufunc signature: nextafter(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray nextafter(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayValues to find the next representable value of.
x2NDArrayThe direction where to look for the next representable value of x1. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only).
Returns
- NDArray
The next representable values of x1 in the direction of x2. This is a scalar if both x1 and x2 are scalars.
Remarks
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.).
nonzero(NDArray)
Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension.The values in a are always tested and returned in row-major, C-style order. To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element.
public static NDArray<long>[] nonzero(NDArray a)
Parameters
aNDArrayInput array.
Returns
Remarks
not_equal(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 != x2) element-wise.
Mirrors NumPy's ufunc signature: not_equal(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the != operator for the typed wrapper).
public static NDArray not_equal(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
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.).- ValueError
A short
numpy.char.chararrayinput (0-d, or 1-d with at mostnp.getbufsize()elements) that NumPy's trivial loop copies into a loop dtype that is not string data — bool for the logical ufuncs, StringDType beside a StringDType operand — without awheremask: the finalize error (Can only create a chararray from string data.).
not_equal(NDArray, object)
Return (x1 != x2) element-wise with scalar.
public static NDArray<bool> not_equal(NDArray x1, object x2)
Parameters
Returns
not_equal(object, NDArray)
Return (x1 != x2) element-wise with scalar on left.
public static NDArray<bool> not_equal(object x1, NDArray x2)
Parameters
Returns
ones(Shape, DType, char, string)
Return a new array of given shape and type, filled with ones — NumPy's one signature,
np.ones(shape, dtype=None, order='C', *, device=None).
public static NDArray ones(Shape shape, DType dtype = null, char order = 'C', string device = null)
Parameters
shapeShapeThe dimensions: an int (
2), a tuple ((2, 3)), anint[]/long[]or a Shape (all convert implicitly). Only the dimensions are read: the layout comes fromorder, as NumPy's shape is a tuple of ints — a Shape taken from a transposed view gives a C-ordered array unlessordersays'F'.dtypeDTypeThe desired dtype — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType (uint8) all convert implicitly. Null (NumPy's None) is float64.orderchar'C'(row-major, the default) or'F'(column-major), in either case. NumPy's'A'and'K'mean nothing without a source array and are refused.devicestringNull or
"cpu"(the Array-API device; NumPy has no other).
Returns
- NDArray
A new, owned, writeable array of ones: the Python int 1 as the dtype's
setitemconverts it (True, 1+0j, ...), and the text'1'in every element of a string dtype (an unsized'U'/'S'request is ONE character, NumPy's allocation rule).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ones.html — NumPy's a = empty(shape, dtype, order,
device=device); multiarray.copyto(a, 1, casting='unsafe'): CreationLayout(Shape, char, string) is empty's argument
handling, ones(Shape, DType) the allocation and the fill.
One signature since API-parity batch 8 (2026-11-12): the int / int[] / long[] /
(int[], DType) / Shape-only overloads, the (Shape, DType dtype, string device) form whose
dtype was required and the (Shape, char order, DType) form with the order before the dtype all went, as
did the generic ones<T> form (write the dtype: np.ones(shape, np.float64)). A positional char
after the shape no longer compiles: NumPy reads np.ones(s, 'F')'s 'F' as the DTYPE (complex64), so
write order: 'F'.
Exceptions
- ValueError
In NumPy's order:
orderis not one of C, F, A, K (order must be one of 'C', 'F', 'A', or 'K' (got 'X'));deviceis not"cpu"(Device not understood. Only "cpu" is allowed, but received: gpu);orderis A or K (only 'C' or 'F' order is permitted); a negative dimension (negative dimensions are not allowed) or a byte count past the allocation limit.- NotSupportedException
dtypenames a class NumSharp has no storage for.
ones_like(NDArray, DType, char, Shape?, string)
Return an array of ones with the same shape and type as a given array: NumPy's
ones_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None).
public static NDArray ones_like(NDArray a, DType dtype = null, char order = 'K', Shape? shape = null, string device = null)
Parameters
aNDArrayThe shape and data-type of
adefine these same attributes of the returned array.dtypeDTypeOverrides the data type of the result, or null for
a's.ordercharMemory layout:
'C','F','A'(F whenais F-contiguous and not C-contiguous, else C) or'K'(the default:a's axis order, kept also for ashapeof the same rank), in either case.shapeShape?Overrides the shape of the result (an int, an int[] or a tuple converts to Shape), or null for
a's. With'K'and a different rank the result is C-ordered, as NumPy's.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity; NumPy's is keyword-only).
Returns
- NDArray
A new, owned, writeable array of ones (the text
'1'for a string dtype) in the requested layout. Anumpy.char.chararrayoperand gives a chararray (NumPy allocates the result as the subclass).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ones_like.html
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces the former <code>(a, dtype, device)</code> / <code>(a, dtype, order, device)</code> pair,
so <code>order</code> no longer needs a <code>dtype</code> before it and <code>shape</code> takes None; a positional
<code>device</code> is written <code>device: "cpu"</code>. <code>subok</code> stays out (the parity plan's
exclusion).</p>
Exceptions
- ValueError
orderis not one of C, F, A, K in either case (order must be one of 'C', 'F', 'A', or 'K' (got 'Z')), reported before the device, as NumPy's empty_like converts its arguments in order;deviceis neither null nor"cpu"(NumPy'sDevice not understood. Only "cpu" is allowed, but received: ...); a negative dimension inshape(negative dimensions are not allowed); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- ValueError
A
numpy.char.chararrayoperand with a dtype that is not string data: NumPy's finalize error (Can only create a chararray from string data.), before anything is filled.- NullReferenceException
ais null (its layout is read after the order and device checks).
outer(NDArray, NDArray, NDArray)
Compute the outer product of two vectors. Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product[R60] is:
public static NDArray outer(NDArray a, NDArray b, NDArray @out = null)
Parameters
aNDArrayFirst input vector. Input is flattened if not already 1-dimensional.
bNDArraySecond input vector. Input is flattened if not already 1-dimensional.
outNDArrayA location into which the result is stored. Its shape must be
(a.size, b.size). Returned as-is when given. NumPy computesouteras a singlemultiply, sooutfollows the ufunc rules exactly — it joins the broadcast (a shape mismatch is the ufunc broadcast error) and accepts a same_kind cast from the product dtype.
Returns
- NDArray
out[i, j] = a[i] * b[j]
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.outer.html
NumPy's statement multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out) is
Outer(NDArray, NDArray, NDArray), on a's engine, called with plain views of subclass
operands (a numpy.matrix operand is computed as a plain array).
Exceptions
- NullReferenceException
aorbis null.- TypeError
Operands the multiply has no loop for (text with numbers, two texts).
- ValueError
A read-only
out.- TypeError
An
outthe product does not reach under same_kind.- ArgumentException
An
outthe products do not broadcast into.
packbits(NDArray, int?, string)
Packs the elements of a binary-valued array into bits in a uint8 array. Each element
contributes one bit (1 iff the element is nonzero); the axis is shortened to
ceil(len/8) and zero-padded to a full trailing byte.
public static NDArray packbits(NDArray a, int? axis = null, string bitorder = "big")
Parameters
aNDArrayInput array. Must be a boolean or integer dtype (float/complex/decimal raise); read in logical order for any memory layout.
axisint?Axis to pack along.
null(NumPyNone) packs the C-order flattened array and returns a 1-D result.bitorderstring"big"(default) puts the first element in the most-significant bit ([.,.,.,.,.,.,1,1] => 3);"little"reverses it. Matched to NumPy's prefix rule: a value beginning with"little"is little, one beginning with"big"is big;nullis treated as"big".
Returns
- NDArray
A uint8 array with the packed bits — same ndim as
a(exceptaxis=null⇒ 1-D), F-contiguous iffais.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.packbits.html
<p>The body is
<xref href="NumSharp.TensorEngine.Packbits(NumSharp.NDArray%2cSystem.Nullable%7bSystem.Int32%7d%2cSystem.String)" data-throw-if-not-resolved="false"></xref> (the np-layer dtype plan); this facade keeps the <code>numpy.matrix</code>
rule.</p>
Exceptions
- ArgumentNullException
ais null.- ValueError
bitorderis neither a "big" nor "little" prefix.- TypeError
ais not a boolean/integer dtype.- AxisError
axisis out of bounds fora's rank.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
pad(NDArray, IDictionary<int, object>, PadFunc, object)
Pad an array by a per-axis dict with a callable mode: the dict is read as in the string-mode dict overload,
then mode fills each 1-D vector's pad area.
public static NDArray pad(NDArray array, IDictionary<int, object> pad_width, np.PadFunc mode, object kwargs = null)
Parameters
arrayNDArrayThe array to pad.
pad_widthIDictionary<int, object>The per-axis widths, read in the dictionary's order (a later key for the same axis wins).
modenp.PadFuncThe callable that writes each vector's pad area in place.
kwargsobjectPassed to
modeunchanged.
Returns
- NDArray
The padded array.
Exceptions
- AssertionError
A value that is neither an integer nor a 2-tuple of integers.
- IndexError
A key outside
[-ndim, ndim)("list assignment index out of range").- TypeError
The widths are no integer table (a 0-d array's empty dict, every axis given bools, a width outside int64).
- ValueError
A negative width.
pad(NDArray, IDictionary<int, object>, string, object, object, object, string)
Pad an array by a per-axis dict (NumPy 2.3+): each key names an axis (negative counts from the end), each
value pads it by an integer on both sides or by a (before, after) tuple; an axis without a key is not
padded.
public static NDArray pad(NDArray array, IDictionary<int, object> pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArrayThe array to pad.
pad_widthIDictionary<int, object>The per-axis widths, read in the dictionary's order (a later key for the same axis wins).
modestringThe pad mode, as for the other overloads.
constant_valuesobjectThe fill of
'constant'.end_valuesobjectThe ends of
'linear_ramp'.stat_lengthobjectThe window of the statistic modes.
reflect_typestring'even'or'odd'for'reflect'/'symmetric'.
Returns
- NDArray
The padded array.
Remarks
Exceptions
- AssertionError
A value that is neither an integer nor a 2-tuple of integers (NumPy's
typing.assert_never; a typed C# array is an ndarray, which NumPy refuses too).- IndexError
A key outside
[-ndim, ndim)("list assignment index out of range", NumPy's list assignment - not an AxisError). Every key of a 0-d array is one.- TypeError
The widths are no integer table: a 0-d array's empty dict, every axis given bools, or a width outside int64.
- ValueError
A negative width (checked after every key, as NumPy's
_as_pairsdoes).
pad(NDArray, int, PadFunc, object)
public static NDArray pad(NDArray array, int pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, int, string, object, object, object, string)
Pad an array. Scalar pad_width applies (pad_width, pad_width)
to every axis.
public static NDArray pad(NDArray array, int pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_widthintmodestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
Remarks
pad(NDArray, int[,], PadFunc, object)
public static NDArray pad(NDArray array, int[,] pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, int[,], string, object, object, object, string)
public static NDArray pad(NDArray array, int[,] pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_widthint[,]modestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
pad(NDArray, int[], PadFunc, object)
public static NDArray pad(NDArray array, int[] pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, int[], string, object, object, object, string)
public static NDArray pad(NDArray array, int[] pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_widthint[]modestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
pad(NDArray, (int before, int after), PadFunc, object)
public static NDArray pad(NDArray array, (int before, int after) pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, (int before, int after), string, object, object, object, string)
public static NDArray pad(NDArray array, (int before, int after) pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_width(int AxisA, int AxisB)modestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
partition(NDArray, NDArray, int?, string, string)
Return a partitioned copy with the kth indices given as an ARRAY — NumPy's array-kth form, which is what makes its kth-dtype rejections reachable: a bool kth raises "Booleans unacceptable as partition index", a non-integer kth "Partition index must be integer" (TypeError), a >1-D kth "object too deep for desired array" (checked BEFORE the axis, like NumPy). Integer kth values cast to intp with NumPy's modular wrap (uint64 past 2^63 goes negative; 2^64-1 is a legal -1). 0-d and any layout accepted.
public static NDArray partition(NDArray a, NDArray kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
Returns
Remarks
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.).- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the argument checks.- ArgumentNullException
ais null.
partition(NDArray, int, int?, string, string)
Return a partitioned copy of an array: the element at index kth
lands in its final sorted position, everything smaller lies before it and everything
equal or greater behind it — the order WITHIN the two sides is undefined
(NumPy np.partition).
public static NDArray partition(NDArray a, int kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayArray to be partitioned.
kthintElement index to partition by; negative wraps from the end.
axisint?Axis to partition along. -1 (default) = last axis; null flattens first.
kindstringSelection algorithm — only 'introselect' exists, exactly like NumPy; anything else raises NumPy's verbatim ValueError.
orderstringStructured-dtype field order — NumSharp has no structured dtypes, so any non-null value raises NumPy's "Cannot specify order when the array has no fields."
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.partition.html
Validation follows NumPy's probed order: kind → order → axis → kth ("kth(=N) out of
bounds (M)" reports the post-wrap value; an EMPTY array skips the kth bounds check).
NaN floats partition to the end (original bit patterns preserved); complex uses NumPy's
lexicographic real-then-imag ordering. The result is a fresh C-contiguous copy (house
np.sort convention — NumPy's copy(order='K') keeps F-order for F-inputs; values identical).
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.).- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the argument checks.- ArgumentNullException
ais null.
partition(NDArray, int[], int?, string, string)
Return a partitioned copy of an array, partitioning around EVERY index in
kth at once (each lands in its final sorted position; the ranges
between them are mutually ordered). NumPy np.partition with a kth sequence.
public static NDArray partition(NDArray a, int[] kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayArray to be partitioned.
kthint[]Element indices to partition by; negatives wrap. NumSharp reads an empty array as NumPy's
np.array([], dtype=intp)— a valid no-op returning a plain copy (Python's bare[]is float64 and raises TypeError; a typed int[] is never ambiguous).axisint?Axis to partition along. -1 (default) = last axis; null flattens first.
kindstringSelection algorithm — only 'introselect' exists.
orderstringMust stay null (no structured dtypes).
Returns
Remarks
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.).- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the argument checks.- ArgumentNullException
ais null.
percentile(NDArray, NDArray, int, NDArray, bool, string, bool, NDArray)
percentile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray) with the axis
as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray percentile(NDArray a, NDArray q, int axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result;50or50.0is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. NumPy divides q by 100 first (np.true_divide(q, 100)), so a percentile never takes the integer index.axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The percentiles: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.percentile.html. NumPy's body is the engine's
(Percentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric percentile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 6 overloads (q as
double, double[], NDArray, by an int? or
int[] axis), which made np.percentile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q: NumPy divides it by 100 first, anddividehas no text loop (ufunc 'divide' not supported for the input types, …).- ArgumentException
A numeric percentile's q of rank above 1 (NumPy's ValueError text).
- ValueError
A percentile outside [0, 100]; over text data a q of rank above 2 (
q must be a scalar or 1d, after the axis) or an empty q of two dimensions (itsq.min()range check).- IndexError
Text data with an empty reduced axis (NumPy's take:
cannot do a non-empty take from an empty axes., or an index out of bounds).- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea: a line of two or more elements holding a None-like NA (the sort'sCannot compare null that is not a nan-like value), or the unsafe write-back into a numericoutthat cannot parse a string (could not convert string to float: 'a').- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the checks that come first (q, the axes, the method, keepdims' out).- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before q's rank, the method and the data's refusals.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(NumPy divides it by 100 first, anddividehas no text loop); over text data an interpolating method, anoutthat does not cast safely to the data, or keepdims over a 0-d result.- ArgumentException
A numeric percentile's q of rank above 1, an unknown method, or an
outof another shape (numeric data; NumPy's ValueError texts).- ValueError
A percentile outside [0, 100]; an axis repeats; over text data a q of rank above 2, an empty q of two dimensions, or an
outof another shape.- AxisError
An axis is out of range for
a.- IndexError
Text data with an empty reduced axis (NumPy's take, or the interpolating methods' neighbour lookup).
percentile(NDArray, NDArray, int[], NDArray, bool, string, bool, NDArray)
percentile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray) with the axes
as an int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray percentile(NDArray a, NDArray q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result;50or50.0is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. NumPy divides q by 100 first (np.true_divide(q, 100)), so a percentile never takes the integer index.axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The percentiles: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.percentile.html. NumPy's body is the engine's
(Percentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric percentile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 6 overloads (q as
double, double[], NDArray, by an int? or
int[] axis), which made np.percentile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q: NumPy divides it by 100 first, anddividehas no text loop (ufunc 'divide' not supported for the input types, …).- ArgumentException
A numeric percentile's q of rank above 1 (NumPy's ValueError text).
- ValueError
A percentile outside [0, 100]; over text data a q of rank above 2 (
q must be a scalar or 1d, after the axis) or an empty q of two dimensions (itsq.min()range check).- IndexError
Text data with an empty reduced axis (NumPy's take:
cannot do a non-empty take from an empty axes., or an index out of bounds).- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea: a line of two or more elements holding a None-like NA (the sort'sCannot compare null that is not a nan-like value), or the unsafe write-back into a numericoutthat cannot parse a string (could not convert string to float: 'a').- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the checks that come first (q, the axes, the method, keepdims' out).- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before q's rank, the method and the data's refusals.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(NumPy divides it by 100 first, anddividehas no text loop); over text data an interpolating method, anoutthat does not cast safely to the data, or keepdims over a 0-d result.- ArgumentException
A numeric percentile's q of rank above 1, an unknown method, or an
outof another shape (numeric data; NumPy's ValueError texts).- ValueError
A percentile outside [0, 100]; an axis repeats; over text data a q of rank above 2, an empty q of two dimensions, or an
outof another shape.- AxisError
An axis is out of range for
a.- IndexError
Text data with an empty reduced axis (NumPy's take, or the interpolating methods' neighbour lookup).
percentile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray)
NumPy's np.percentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *,
weights=None): the q-th percentile(s) of the data along the given axes (of the flattened data by
default).
public static NDArray percentile(NDArray a, NDArray q, NDAxis? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result;50or50.0is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. NumPy divides q by 100 first (np.true_divide(q, 100)), so a percentile never takes the integer index.axisNDAxis?NumPy's
axis:null(None, the default) reduces the flattened data; one axis (negative counts from the end) or a tuple ((0, 2),new[] { 0, 2 }) reduces those axes, merged into one before the partition; the empty tuple reduces nothing.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The percentiles: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.percentile.html. NumPy's body is the engine's
(Percentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric percentile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 6 overloads (q as
double, double[], NDArray, by an int? or
int[] axis), which made np.percentile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q: NumPy divides it by 100 first, anddividehas no text loop (ufunc 'divide' not supported for the input types, …).- ArgumentException
A numeric percentile's q of rank above 1 (NumPy's ValueError text).
- ValueError
A percentile outside [0, 100]; over text data a q of rank above 2 (
q must be a scalar or 1d, after the axis) or an empty q of two dimensions (itsq.min()range check).- IndexError
Text data with an empty reduced axis (NumPy's take:
cannot do a non-empty take from an empty axes., or an index out of bounds).- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea: a line of two or more elements holding a None-like NA (the sort'sCannot compare null that is not a nan-like value), or the unsafe write-back into a numericoutthat cannot parse a string (could not convert string to float: 'a').- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the checks that come first (q, the axes, the method, keepdims' out).- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before q's rank, the method and the data's refusals.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(NumPy divides it by 100 first, anddividehas no text loop); over text data an interpolating method, anoutthat does not cast safely to the data, or keepdims over a 0-d result.- ArgumentException
A numeric percentile's q of rank above 1, an unknown method, or an
outof another shape (numeric data; NumPy's ValueError texts).- ValueError
A percentile outside [0, 100]; an axis repeats; over text data a q of rank above 2, an empty q of two dimensions, or an
outof another shape.- AxisError
An axis is out of range for
a.- IndexError
Text data with an empty reduced axis (NumPy's take, or the interpolating methods' neighbour lookup).
permute_dims(NDArray, int[])
Permute the axes (dimensions) of an array.
Array API standard alias of transpose(NDArray, int[]).
public static NDArray permute_dims(NDArray a, int[] axes = null)
Parameters
aNDArrayInput array.
axesint[]If specified, it must be a permutation of
[0, 1, ..., N-1]whereNis the number of axes ofa. Negative indices can also be used. The i-th axis of the returned array will correspond to the axis numberedaxes[i]of the input. If not specified, defaults to reversing the order of the axes.
Returns
- NDArray
awith its axes permuted. A view is returned whenever possible. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
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.).
piecewise(NDArray, NDArray, object[], params object[])
piecewise(NDArray, NDArray[], object[], params object[]) with a single bare
condition array instead of a list — NumPy's undocumented promotion. A 2-D+ array
is split along axis 0 into one condition per row (a pre-stacked
[c0, c1]); a 1-D array is treated as ONE whole condition when
x is not 0-d, or split element-by-element when x IS
0-d (matching NumPy's condlist[0] inspection exactly).
public static NDArray piecewise(NDArray x, NDArray condlist, object[] funclist, params object[] args)
Parameters
Returns
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.).
piecewise(NDArray, NDArray[], object[], params object[])
Evaluate a piecewise-defined function. Wherever condlist[i] is true,
the output takes funclist[i] applied to (or, for a scalar entry, equal
to) x. When several conditions overlap the LAST true one wins
(a forward overwrite — the opposite of select(NDArray[], object[], object)'s first-wins). Positions no
condition covers keep the value 0, unless one extra function is supplied as the default.
public static NDArray piecewise(NDArray x, NDArray[] condlist, object[] funclist, params object[] args)
Parameters
xNDArrayThe input domain. The result has
x's shape AND dtype (zeros_like(NDArray, DType, char, Shape?, string)), so a float-valued function stored into an integerxtruncates toward zero, exactly as NumPy'sy[cond] = …does.condlistNDArray[]The boolean conditions, one per function (a non-bool array is read by nonzero, matching NumPy's
asarray(condlist, dtype=bool)). Each condition should havex's shape.funclistobject[]One entry per condition, or one extra as the default. Each entry is either a callable — a Func<T, TResult> called as
f(x[cond]), or a Func<T1, T2, TResult> (Func<NDArray, object[], NDArray>) called asf(x[cond], args)— or a constant: a C# scalar (a weak python scalar: a float truncates into an integer target, an out-of-range integer raises, a complex into a non-complex target raises) or an NDArray (broadcast / placed into the selected slots, unsafe-cast tox's dtype). Iffunclist.Length == condlist.Length + 1the extra entry is the default, used where every condition is false.argsobject[]Extra positional arguments forwarded to every
Func<NDArray, object[], NDArray>entry (NumPy's*args). A plainFunc<NDArray, NDArray>entry ignores them.
Returns
- NDArray
A fresh array of
x's shape and dtype.
Remarks
Exceptions
- ValueError
funclist.Lengthis neithercondlist.Lengthnorcondlist.Length + 1.- IndexError
condlistis empty (NumPy accesses condlist[0]).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
piecewise(NDArray, bool, object[], params object[])
piecewise(NDArray, NDArray[], object[], params object[]) with a single scalar
boolean condition — NumPy's isscalar(condlist) branch. The one function is applied
to all of x when condlist is true, and nowhere when
it is false.
public static NDArray piecewise(NDArray x, bool condlist, object[] funclist, params object[] args)
Parameters
Returns
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.).
place(NDArray, NDArray, NDArray)
Change elements of arr based on a boolean mask.
Where mask is true (walked in C-order), the
next value from vals (cycling) is written into
arr. In-place.
public static void place(NDArray arr, NDArray mask, NDArray vals)
Parameters
arrNDArrayTarget array (modified in place).
maskNDArrayBoolean mask. Must have the same total size as
arr— NumPy allows shape mismatch as long as element counts match.valsNDArrayValues to write, converted to
arr's dtype and cycled to fill the True positions. An ARRAY of values must convert under NumPy's'safe'rule (a 0-d value — NumSharp's stand-in for a Python scalar — is converted unconditionally). Must be non-empty when at least one mask entry is True.nullis Python'sNone: one value, converted intoarr's dtype after the mask's size check (NoneForStore(DType): NaN,nan+nanj,False,'None'; int()'s TypeError for an integer array, even under an all-false mask).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.place.html
Order (NumPy's arr_place). The target's writeability; the mask's conversion to bool and its
size; the values' conversion (PyArray_FromAny(vals, arr.dtype, CARRAY): the 'safe' rule for an array,
every value converted — so a non-ASCII byte value raises even under an all-false mask); then the empty-values
check and the loop. A NUMBER formatted into a text array cannot fail, so it is refused only where it is
written; a TEXT mask is refused where its truth is read (the empty-values check, or the loop).
Scoped by [NDScoped]: the contiguous scratch of a non-contiguous target and the
bool/dtype-converted copies of mask and vals are released on
return, exceptions included. A mask or values array used as-is is the caller's (built before the scope
opened), so the scope never disposes it.
Exceptions
- ArgumentNullException
arrormaskis null.- TypeError
valsis null (None) andarris an integer (ordecimal) array.- ValueError
arris read-only (checked first, as NumPy does), ormask's size differs fromarr's (place: mask and data must be the same size), orvalsis empty while some mask entry is True (Cannot insert from an empty array!).- InvalidCastException
An array
valsdoes not cast 'safely' toarr's dtype (NumPy's TypeError:Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe') — even whenarris empty.- UnicodeEncodeError
Text values that are not ASCII into an
Sarray.- UnicodeDecodeError
Byte values that are not ASCII into a
Uarray.- ValueError
A text value that does not parse into a numeric array (NumPy's
int()/float()/complex()texts); numbers into a text array are written as theirstr().- SystemError
A
Umask holds a unit above U+10FFFF: NumPy's string-to-bool cast of the mask raises it, before the size check. (A text mask is otherwise read by its truth values: a non-empty string is True.)
place(NDArray, NDArray, Array)
place(NDArray, NDArray, NDArray) with the values given as a C# array — NumPy's Python LIST of
values: np.place(a, mask, ['P', 'QQ', 'RRRR']) is np.place(a, mask, new[] { "P", "QQ", "RRRR" }).
public static void place(NDArray arr, NDArray mask, Array vals)
Parameters
arrNDArrayTarget array (modified in place).
maskNDArrayBoolean mask of
arr's size.valsArrayThe values, cycled over the True positions. NumPy converts a list STRAIGHT INTO
arr's dtype (PyArray_FromAny(list, arr.dtype), asnp.array(vals, dtype=arr.dtype)does), so there is no'safe'rule: every item is stored by the dtype's setitem —'RRRR'into a<U3array truncates to'RRR',1.9into an int array truncates to 1,[1, 2.5]into a<U3array is['1', '2.5']— where an ndarray of the same values raises the cast TypeError; a Python int the array cannot hold raises ([1000]into int8). The conversion happens after the mask's checks.
Remarks
C# binds a typed array argument (double[], string[]) here rather than to the
NDArray overload: an identity/reference conversion beats NumSharp's implicit
Array → NDArray conversion. Pass np.array(...) to get NumPy's ndarray semantics. A bare
null binds here too, and is Python's None exactly as in the NDArray overload.
The list is converted by the body (PlaceCore(NDArray, NDArray, object)), where NumPy converts it: after
the target's writeability and the mask's size, so a wrong-size mask is reported before a ragged list.
Exceptions
- ArgumentNullException
arrormaskis null.- TypeError
valsis null (None), or holds None, andarris an integer (ordecimal) array.- ValueError
The checks of place(NDArray, NDArray, NDArray); a ragged list (NumPy's inhomogeneous-shape text), a NaN into an integer array, a text value that does not parse into a numeric array.
- OverflowError
A Python int outside an integer array's range (
Python integer 1000 out of bounds for int8).- UnicodeEncodeError
Text values that are not ASCII into an
Sarray.- UnicodeDecodeError
Byte values that are not ASCII into a
Uarray.
poly(NDArray)
Find the coefficients of a polynomial with the given sequence of roots (leading coefficient 1). A square 2-D array is treated as a matrix, returning the coefficients of its characteristic polynomial (via eigvals(NDArray)).
public static NDArray poly(NDArray seq_of_zeros)
Parameters
seq_of_zerosNDArrayA 1-D sequence of roots, or a square 2-D array.
Returns
- NDArray
1-D coefficients highest degree first,
c[0] == 1.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.poly.html
An empty input returns the 0-d scalar 1.0 (NumPy's Python float 1.0).
The engine member Poly(NDArray) is poly's body alone (NumPy's implementation under the dispatcher): it takes a 0-d input as one root.
Exceptions
- ValueError
An input that is neither 1-D nor a non-empty square 2-D array (
input must be 1d or non-empty square 2d array.).- TypeError
A square text matrix: its eigenvalues' finiteness check (
isfinitehas no text loop).- ValueError
A 1-D text root that does not parse as a float (NumPy casts the roots to their mintypecode, 'd' for text:
could not convert string to float: np.str_('x')).- NotSupportedException
A square matrix and no LAPACK backend installed (the eigenvalues).
- TypeError
A 0-d
seq_of_zeros, or null (NumPy's None): NumPy'sarray_function_dispatchiterates what poly's dispatcher returns, the argument itself, and neither is iterable (dispatcher for array_function did not return an iterable), before poly's body runs.
polyadd(NDArray, NDArray)
Find the sum of two polynomials. The shorter input is zero-extended on the high-degree side.
public static NDArray polyadd(NDArray a1, NDArray a2)
Parameters
Returns
Remarks
polyder(NDArray, int)
Return the derivative of the specified order of a polynomial.
public static NDArray polyder(NDArray p, int m = 1)
Parameters
pNDArrayPolynomial coefficients, highest degree first. NumPy measures them with
len(): a 2-D p is differentiated along its first axis, each row a coefficient (np.polyder(np.ones((3, 2)))is[[2, 1], [2, 1]]).mintOrder of differentiation (default 1); 0 returns
pas an array.
Returns
- NDArray
A new polynomial representing the derivative.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.polyder.html
The statements are Polyder(NDArray, int), on p's engine (the default one
for null, so the order check still comes first), with plain views of subclass operands.
Exceptions
- ValueError
A negative
m, checked first.- NotSupportedException
pis null (NumPy's object array of None).- IncorrectShapeException
An N-D
pwhose rows do not broadcast with the ramp at some order, the discardedm == 0product included, as NumPy's recursion computes it.- TypeError
A 0-d
pat every order (len() of unsized object); text coefficients the multiply has no loop for.- ArgumentNullException
pis null.
polydiv(NDArray, NDArray)
Returns the quotient and remainder of polynomial division u / v.
public static (NDArray q, NDArray r) polydiv(NDArray u, NDArray v)
Parameters
Returns
- (NDArray Lhs, NDArray Rhs)
(q, r)— quotient and remainder coefficients, floating (or complex) dtype.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.polydiv.html
A poly1d input does NOT force a poly1d return here (a C# tuple slot is a fixed
type); the poly1d / operator performs that wrapping instead.
polyfit(NDArray, NDArray, int, double?, bool, NDArray, object)
Least squares polynomial fit — fit a polynomial p[0]*x**deg + ... + p[deg] of degree
deg to points (x, y), minimising the squared error.
public static PolyfitResult polyfit(NDArray x, NDArray y, int deg, double? rcond = null, bool full = false, NDArray w = null, object cov = null)
Parameters
xNDArrayx-coordinates, shape
(M,).yNDArrayy-coordinates, shape
(M,)or(M, K)(one dataset per column).degintDegree of the fitting polynomial.
rconddouble?Relative condition number; default
len(x) * eps.fullboolWhen true, the returned PolyfitResult also carries the SVD diagnostics.
wNDArrayOptional weights, shape
(M,).covobjectnull/false(default),true, or the string"unscaled"— when truthy the result also carries the covariance matrix (only meaningful whenfullis false).
Returns
- PolyfitResult
A PolyfitResult that converts implicitly to the coefficient array; deconstruct it for the
fullfive-tuple or thecovtwo-tuple. It carries exactly the arrays NumPy's return holds: the SVD diagnostics (residuals/rank/singular_values) only whenfullis true, the covariance only whencovis truthy — every other slot isnull.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html
The lstsq diagnostics a non-full call does not return are released with the method's other
temporaries. They used to ride along in the result regardless of full, so the
ordinary spelling NDArray c = np.polyfit(x, y, deg) — which keeps only the coefficients —
stranded the residual and singular-value buffers (2 pooled arrays per call) until a GC.
The statements are Polyfit(NDArray, NDArray, int, double?, bool, NDArray, object), on x's engine (the default one
for null), with plain views of subclass operands.
Exceptions
- ValueError
A negative
deg, or a scaled covariance with no more points than coefficients.- TypeError
NumPy's shape refusals (x not 1-D or empty, y not 1-D / 2-D, lengths that differ, w not 1-D or of another length), text the float conversion refuses, or a float16 / decimal x numpy.linalg refuses.
- NotSupportedException
xoryis null.- OpenBlasMissingBackendException
No LAPACK backend is installed (lstsq needs one).
- LinAlgError
lstsq's SVD does not converge, or the covariance's inverse meets a singular matrix.
- IncorrectShapeException
Weights that do not broadcast against a 2-D y's columns.
- ArgumentNullException
xis null.
polyint(NDArray, int, NDArray)
Return an antiderivative (indefinite integral) of a polynomial.
public static NDArray polyint(NDArray p, int m = 1, NDArray k = null)
Parameters
pNDArrayPolynomial to integrate (coefficients, highest degree first).
mintOrder of the antiderivative (default 1).
kNDArrayIntegration constants, highest-order term first.
null(default) means all zero. Form == 1a single scalar may be given.
Returns
- NDArray
The antiderivative — always floating (or complex) because of the term-wise division.
Remarks
Exceptions
- ValueError
A negative
m, or fewer integration constants thanm.- TypeError
With
mabove 0: a 0-dp(len() of unsized object), or text, whose division by the exponents has no loop.
polyint(NDArray, int, double)
Convenience overload — polyint with a single scalar integration constant.
public static NDArray polyint(NDArray p, int m, double k)
Parameters
Returns
polymul(NDArray, NDArray)
Find the product of two polynomials — the (full-mode) convolution of their coefficients.
Leading zeros of each input are dropped first (NumPy wraps each in poly1d).
public static NDArray polymul(NDArray a1, NDArray a2)
Parameters
a1NDArrayThe first polynomial's coefficients, highest degree first.
a2NDArrayThe second polynomial's coefficients.
Returns
- NDArray
The product's coefficients.
Remarks
Exceptions
- ValueError
An input of rank above 1 (
Polynomial must be 1d only., the first input's first); with a text input otherwise,function not available for this data type(np.convolve's refusal).
polysub(NDArray, NDArray)
Difference (subtraction) of two polynomials, a1 - a2.
public static NDArray polysub(NDArray a1, NDArray a2)
Parameters
Returns
Remarks
polyval(NDArray, NDArray)
Evaluate a polynomial at specific values.
If p has length N the value returned is
p[0]x*(N-1) + p[1]x*(N-2) + ... + p[N-2]*x + p[N-1], computed with Horner's scheme.
public static NDArray polyval(NDArray p, NDArray x)
Parameters
pNDArray1-D array of polynomial coefficients, highest degree first.
xNDArrayA number, or an array of numbers, at which to evaluate
p.
Returns
- NDArray
The evaluated values, of dtype
result_type(p, x)and the shape ofx. With no coefficient,zeros_like(x)— a chararray for anumpy.char.chararrayx.
Remarks
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.); anumpy.char.chararrayxwith a coefficient (Can only multiply by integers: NumPy's firsty * xis the chararray's repetition operator).- TypeError
A 0-d
p(iteration over a 0-d array), or text that has no multiply / add loop.
polyval(poly1d, poly1d)
Evaluate a polynomial p at another polynomial (composition).
public static poly1d polyval(poly1d p, poly1d x)
Parameters
Returns
Remarks
positive(NDArray, NDArray, NDArray, DType)
Numerical positive, element-wise (identity: returns +x, a copy).
Mirrors NumPy's ufunc signature: positive(x, /, out=None, *, where=True, dtype=None).
public static NDArray positive(NDArray nd, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
ndNDArrayoutNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): positive(i32, dtype: float64) widens; bool loop requests raise NumPy's did-not-contain-a-loop TypeError (positive has no bool loop, but positive(bool, dtype: float64) is legal).
Returns
Remarks
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.).
pow(NDArray, NDArray, NDArray, NDArray, DType)
First array elements raised to powers from second array, element-wise (NumPy's np.pow,
the Array-API name NumPy 2.0 added: np.pow is np.power, the
same ufunc object, so this forwards to power(NDArray, NDArray, NDArray, NDArray, DType) and
answers bit for bit as it does).
public static NDArray pow(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayThe bases.
x2NDArrayThe exponents; broadcast against
x1.outNDArrayA location into which the result is stored (NumPy ufunc
out=);nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed / written (NumPy ufunc
where=);nullis NumPy'swhere=True.dtypeDTypeThe loop dtype (NumPy ufunc
dtype=): the computation runs in this dtype.
Returns
- NDArray
The result of power(NDArray, NDArray, NDArray, NDArray, DType):
outitself when it was given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.pow.html
<p>One signature, the ufunc form of the original's. A C# literal operand converts to a 0-d array marked as
the Python scalar it stands for, so NEP 50's weak-scalar promotion holds without the original's
<code>object</code> overload (<code>np.pow(int32_array, 2)</code> stays int32, as NumPy's).</p>
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.).
power(NDArray, NDArray, NDArray, NDArray, DType)
First array elements raised to powers from second array, element-wise.
Mirrors NumPy's ufunc signature: power(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray power(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayThe bases.
x2NDArrayThe exponents (array).
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs in this dtype (power(2, -1, dtype: float64) = 0.5; inputs must be same_kind-castable to it).
Returns
- NDArray
The bases in x1 raised to the exponents in x2 (
outitself when given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.power.html
<p>One signature, NumPy's ufunc form (2026-11-11): the former overload that took the second operand as an
<code>object</code> read a boxed number as a STRONG array (parity QA-QB30); a C# literal converts to a 0-d array
marked as the Python scalar it stands for, so NEP 50's weak-scalar rule holds without it, and a value held in
an <code>object</code> variable goes through <xref href="NumSharp.np.asanyarray(System.Object%40%2cNumSharp.DType%2cSystem.Nullable%7bSystem.Char%7d%2cSystem.String%2cSystem.Nullable%7bSystem.Boolean%7d)" data-throw-if-not-resolved="false"></xref>.</p>
<p>The former two-argument and <code>in</code> overloads called the same engine method with no out / where /
dtype, so <code>np.power(a, b)</code> computes exactly as before through this one.</p>
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.).
printoptions(int?, int?, int?, int?, bool?, string, string, char?, string)
Context manager for setting print options (NumPy's np.printoptions). Restores the
previous options when disposed.
public static IDisposable printoptions(int? precision = null, int? threshold = null, int? edgeitems = null, int? linewidth = null, bool? suppress = null, string nanstr = null, string infstr = null, char? sign = null, string floatmode = null)
Parameters
precisionint?thresholdint?edgeitemsint?linewidthint?suppressbool?nanstrstringinfstrstringsignchar?floatmodestring
Returns
Examples
using (np.printoptions(precision: 2, suppress: true)) { Console.WriteLine(arr); }
Remarks
prod(NDArray, int, DType, NDArray, bool, object, NDArray)
prod(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) with the axis as one
int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray prod(NDArray a, int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data (any numeric dtype; text has no multiply loop and is refused).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypeThe accumulator and result dtype: every element is cast to it before it is multiplied.
nullis NumPy's default: int64 for bool and the signed integers narrower than 64 bits, uint64 for the unsigned ones, the input's own dtype otherwise — or, without,promote_types(out, a)(no small-integer widening).outNDArrayThe array the product is written into and returned (the result's shape, any dtype: the values are cast in unsafely). Footgun: the FOURTH positional parameter, as in NumPy, so write
keepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every product starts from instead of 1, converted into the loop dtype as NumPy's element setter converts a Python value (a C# integer range-checked, a
doubletruncated into an integer loop, a 0-d array cast). An empty product is the initial value.nullis the identity 1.whereNDArrayA bool mask broadcast against
a: only the selected elements are multiplied in; an output with none selected is the start value. The C#trueliteral is NumPy's default.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.prod.html. A float product is NumPy's sequential
multiply loop on every route (a NaN keeps the payload of the first NaN met in a reduce run), bit for bit:
a contiguous product at NumPy's own speed (a dependent multiply per element), an axis product of a C-ordered
array eight rows at a time or row by row with vectors; initial or
where run NumPy's reduction iterator.
Exceptions
- ArgumentNullException
ais null.- TypeError
A C# scalar passed as
out; a complexinitialfor a real loop; text (NumPy's refusal); anumpy.matrixoperand withkeepdims,initialorwhere(matrix.prod() got an unexpected keyword argument 'keepdims').- ValueError
A read-only or misshapen
out; a mask with more axes thana; an unconvertibleinitial. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
prod(NDArray, int[], DType, NDArray, bool, object, NDArray)
prod(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) with the axes as an
int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray prod(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data (any numeric dtype; text has no multiply loop and is refused).
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypeThe accumulator and result dtype: every element is cast to it before it is multiplied.
nullis NumPy's default: int64 for bool and the signed integers narrower than 64 bits, uint64 for the unsigned ones, the input's own dtype otherwise — or, without,promote_types(out, a)(no small-integer widening).outNDArrayThe array the product is written into and returned (the result's shape, any dtype: the values are cast in unsafely). Footgun: the FOURTH positional parameter, as in NumPy, so write
keepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every product starts from instead of 1, converted into the loop dtype as NumPy's element setter converts a Python value (a C# integer range-checked, a
doubletruncated into an integer loop, a 0-d array cast). An empty product is the initial value.nullis the identity 1.whereNDArrayA bool mask broadcast against
a: only the selected elements are multiplied in; an output with none selected is the start value. The C#trueliteral is NumPy's default.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.prod.html. A float product is NumPy's sequential
multiply loop on every route (a NaN keeps the payload of the first NaN met in a reduce run), bit for bit:
a contiguous product at NumPy's own speed (a dependent multiply per element), an axis product of a C-ordered
array eight rows at a time or row by row with vectors; initial or
where run NumPy's reduction iterator.
Exceptions
- ArgumentNullException
ais null.- TypeError
A C# scalar passed as
out; a complexinitialfor a real loop; text (NumPy's refusal); anumpy.matrixoperand withkeepdims,initialorwhere(matrix.prod() got an unexpected keyword argument 'keepdims').- ValueError
A read-only or misshapen
out; a mask with more axes thana; an unconvertibleinitial. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
prod(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)
Return the product of array elements over a given axis — NumPy's np.prod(a, axis=None, dtype=None,
out=None, keepdims=<no value>, initial=<no value>, where=<no value>), i.e.
np.multiply.reduce(a, axis, dtype, out, keepdims=keepdims, initial=initial, where=where). This is the only
overload: NumPy's whole signature, with NumPy's names, order and defaults (np-layer dtype plan P10, D10).
public static NDArray prod(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayInput data (any numeric dtype; text has no multiply loop and is refused).
axisNDAxis?The axis to multiply over (negative counts from the end);
nullmultiplies every element. A 0-d array accepts 0 and -1 as every axis (ufunc.reduce's rule). A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypeThe accumulator and result dtype: every element is cast to it before it is multiplied.
nullis NumPy's default: int64 for bool and the signed integers narrower than 64 bits, uint64 for the unsigned ones, the input's own dtype otherwise — or, without,promote_types(out, a)(no small-integer widening).outNDArrayThe array the product is written into and returned (the result's shape, any dtype: the values are cast in unsafely). Footgun: the FOURTH positional parameter, as in NumPy, so write
keepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions.
initialobjectThe value every product starts from instead of 1, converted into the loop dtype as NumPy's element setter converts a Python value (a C# integer range-checked, a
doubletruncated into an integer loop, a 0-d array cast). An empty product is the initial value.nullis the identity 1.whereNDArrayA bool mask broadcast against
a: only the selected elements are multiplied in; an output with none selected is the start value. The C#trueliteral is NumPy's default.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.prod.html. A float product is NumPy's sequential
multiply loop on every route (a NaN keeps the payload of the first NaN met in a reduce run), bit for bit:
a contiguous product at NumPy's own speed (a dependent multiply per element), an axis product of a C-ordered
array eight rows at a time or row by row with vectors; initial or
where run NumPy's reduction iterator.
Exceptions
- ArgumentNullException
ais null.- TypeError
A C# scalar passed as
out; a complexinitialfor a real loop; text (NumPy's refusal); anumpy.matrixoperand withkeepdims,initialorwhere(matrix.prod() got an unexpected keyword argument 'keepdims').- ValueError
A read-only or misshapen
out; a mask with more axes thana; an unconvertibleinitial. Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast.- OverflowError
initialdoes not fit an integer loop.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
promote_types(DType, DType)
Returns the data type with the smallest size and smallest scalar kind to which
both type1 and type2 can be safely cast — NumPy's np.promote_types(type1, type2)
(PyArray_PromoteTypes, NEP 42): the common DType CLASS of the two operands decides, a
non-parametric class returns its default descriptor and a parametric one (datetime64 / timedelta64)
returns the common_instance — the unit GCD (promote_types('M8[s]', 'm8[ms]') is M8[ms],
promote_types('m8[10s]', 'm8[15s]') is m8[5s]).
public static DType promote_types(DType type1, DType type2)
Parameters
Returns
- DType
The promoted descriptor.
Examples
np.promote_types(DType.Int32, DType.Single) // float64
np.promote_types("M8[s]", "m8[ms]") // datetime64[ms]
np.promote_types("i1", "u1") // int16
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.promote_types.html
Unlike result_type, promote_types only considers types (not values),
and always returns the smallest safe type. A non-native byte order is dropped (promote_types('>i4', '>i4')
is the native int32), exactly as in NumPy.
One signature, NumPy's (2026-11-11): an NPTypeCode, a CLR Type and a dtype
string convert to DType, so the former NPTypeCode / Type / generic <T1, T2> overloads
are gone (promote_types<int, long>() is promote_types(typeof(int), typeof(long))); every
NPTypeCode pair answers as the frozen table did (a 15 x 15 differential).
Exceptions
- DTypePromotionError
No common dtype exists (
promote_types('M8[s]', 'f8')) — NumPy's verbatim text.- TypeError
Incompatible non-linear datetime units (
promote_types('m8[Y]', 'm8[D]')) — verbatim; or a null type (NumPy'sNone): "did not understand one of the types".
ptp(NDArray, int, NDArray, bool)
ptp(NDArray, NDAxis?, NDArray, bool) with the axis as one int: the overload a C#
integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so
every answer, error, layout and subclass result is that overload's.
public static NDArray ptp(NDArray a, int axis, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayThe array (numbers or StringDType; fixed-width text is refused as NumPy refuses it).
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayAn optional output of the result's shape; the result is written into it and it is returned.
keepdimsboolWhether the reduced axes stay with length one.
Returns
- NDArray
outitself when given; otherwise the range, a fresh array (read-only when 0-d: NumPy's scalar); anumpy.matrixoperand gives a matrix.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ptp.html — NumPy's whole function
(_methods._ptp: subtract(maximum.reduce(a, axis, out, keepdims), minimum.reduce(a, axis, keepdims),
out)) is the engine's Ptp(NDArray, int?, NDArray, bool) for None or one axis and
Ptp(NDArray, int[], NDArray, bool) for a tuple (the np-layer dtype plan, P1b and
PE).
<p>One signature since API-parity batch 4 (2026-11-12): it replaces the <code>int?</code> and <code>int[]</code>
overloads, which made <code>np.ptp(a, null)</code> ambiguous (CS0121) and had no tuple literal.</p>
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range (a 0-d input has no axis for a tuple to name).
- TypeError
Fixed-width text, or a text out (NumPy's maximum.reduce refuses the loop).
- ValueError
An
outthat _ptp'smaximum.reduce(a, axis, out=out)refuses in its prologue, before anything is computed: of the wrong rank (output parameter for reduction operation maximum has the wrong number of dimensions: Found 2 but expected 1) or with a length-1 axis where the result is longer (parity QA-31); a tuple that names an axis twice (duplicate value in 'axis'); a read-only out; an empty reduction (no identity); anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- IncorrectShapeException
An
outwhose axes do not broadcast with the result's (operands could not be broadcast together with remapped shapes [original->remapped]: (3,)->(3) (3,4)), NumPy's ValueError under the house type of a broadcast failure.
ptp(NDArray, int[], NDArray, bool)
ptp(NDArray, NDAxis?, NDArray, bool) with the axes as an int[]: the overload an
int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new
int[0] is ()).
public static NDArray ptp(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayThe array (numbers or StringDType; fixed-width text is refused as NumPy refuses it).
axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayAn optional output of the result's shape; the result is written into it and it is returned.
keepdimsboolWhether the reduced axes stay with length one.
Returns
- NDArray
outitself when given; otherwise the range, a fresh array (read-only when 0-d: NumPy's scalar); anumpy.matrixoperand gives a matrix.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ptp.html — NumPy's whole function
(_methods._ptp: subtract(maximum.reduce(a, axis, out, keepdims), minimum.reduce(a, axis, keepdims),
out)) is the engine's Ptp(NDArray, int?, NDArray, bool) for None or one axis and
Ptp(NDArray, int[], NDArray, bool) for a tuple (the np-layer dtype plan, P1b and
PE).
<p>One signature since API-parity batch 4 (2026-11-12): it replaces the <code>int?</code> and <code>int[]</code>
overloads, which made <code>np.ptp(a, null)</code> ambiguous (CS0121) and had no tuple literal.</p>
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range (a 0-d input has no axis for a tuple to name).
- TypeError
Fixed-width text, or a text out (NumPy's maximum.reduce refuses the loop).
- ValueError
An
outthat _ptp'smaximum.reduce(a, axis, out=out)refuses in its prologue, before anything is computed: of the wrong rank (output parameter for reduction operation maximum has the wrong number of dimensions: Found 2 but expected 1) or with a length-1 axis where the result is longer (parity QA-31); a tuple that names an axis twice (duplicate value in 'axis'); a read-only out; an empty reduction (no identity); anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- IncorrectShapeException
An
outwhose axes do not broadcast with the result's (operands could not be broadcast together with remapped shapes [original->remapped]: (3,)->(3) (3,4)), NumPy's ValueError under the house type of a broadcast failure.
ptp(NDArray, NDAxis?, NDArray, bool)
NumPy's np.ptp(a, axis=None, out=None, keepdims=False): the range of values (maximum - minimum) along
the given axes, every axis by default. Equivalent to np.amax(a, axis) - np.amin(a, axis); the dtype is
preserved, so unsigned/signed integer overflow wraps the same way NumPy does
(e.g. ptp(uint8[0,255]) == 255, ptp(int8[-128,127]) == -1).
public static NDArray ptp(NDArray a, NDAxis? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayThe array (numbers or StringDType; fixed-width text is refused as NumPy refuses it).
axisNDAxis?NumPy's
axis:null(None, the default) reduces every axis; one axis (negative counts from the end; a 0-d array accepts 0 and -1) or a tuple ((0, 2),new[] { 0, 2 }) reduces those axes, and the empty tuple reduces none (the result isa - a).outNDArrayAn optional output of the result's shape; the result is written into it and it is returned.
keepdimsboolWhether the reduced axes stay with length one.
Returns
- NDArray
outitself when given; otherwise the range, a fresh array (read-only when 0-d: NumPy's scalar); anumpy.matrixoperand gives a matrix.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ptp.html — NumPy's whole function
(_methods._ptp: subtract(maximum.reduce(a, axis, out, keepdims), minimum.reduce(a, axis, keepdims),
out)) is the engine's Ptp(NDArray, int?, NDArray, bool) for None or one axis and
Ptp(NDArray, int[], NDArray, bool) for a tuple (the np-layer dtype plan, P1b and
PE).
<p>One signature since API-parity batch 4 (2026-11-12): it replaces the <code>int?</code> and <code>int[]</code>
overloads, which made <code>np.ptp(a, null)</code> ambiguous (CS0121) and had no tuple literal.</p>
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range (a 0-d input has no axis for a tuple to name).
- TypeError
Fixed-width text, or a text out (NumPy's maximum.reduce refuses the loop).
- ValueError
An
outthat _ptp'smaximum.reduce(a, axis, out=out)refuses in its prologue, before anything is computed: of the wrong rank (output parameter for reduction operation maximum has the wrong number of dimensions: Found 2 but expected 1) or with a length-1 axis where the result is longer (parity QA-31); a tuple that names an axis twice (duplicate value in 'axis'); a read-only out; an empty reduction (no identity); anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- IncorrectShapeException
An
outwhose axes do not broadcast with the result's (operands could not be broadcast together with remapped shapes [original->remapped]: (3,)->(3) (3,4)), NumPy's ValueError under the house type of a broadcast failure.
put(NDArray, NDArray, NDArray, string)
Replace elements of a with given values, at the
specified flat indices. In-place — modifies a.
Equivalent to a.flat[ind] = v with cyclic
broadcasting of v.
public static void put(NDArray a, NDArray ind, NDArray v, string mode = "raise")
Parameters
aNDArrayTarget array (modified in place).
indNDArrayNumPy's
ind: the flat indices, an integer array or a C# integer (a 0-d index), cast to int64 internally, in C order whatever its layout. Indexing is into the C-order flattening ofa.vNDArrayNumPy's
v: the values to write, read in C order. Cast toa's dtype (NumPy's FORCECAST); a C# literal is packed as the Python scalar it stands for (range-checked, never wrapped). Cycles modulo its size — shorter thanindis fine; an empty array writes nothing (NumPy's no-op).nullis Python'sNone, converted intoa's dtype (NoneForStore(DType): NaN,nan+nanj,False,'None', aStringDTypeNA object; int()'s TypeError for an integer array — raised before the indices' bounds and even for an empty index array, as NumPy converts first).modestringBoundary mode:
"raise"(default),"wrap", or"clip";nullis NumPy'sNone(raise).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.put.html
The work is PutTo(NDArray, NDArray, object, string), NumPy's PyArray_PutTo: see there for the check order, the copy
NumPy makes when the target overlaps the values or the indices, and which writes survive an out-of-bounds
index.
Scoped by [NDScoped]: the contiguous scratch of a non-contiguous or overlapping target and
the int64 and dtype-converted copies are released on return, exceptions included. The caller's arrays were
built before the scope opened, so the scope never disposes them.
One overload, NumPy's signature put(a, ind, v, mode='raise') keyword for keyword (2026-11-11).
A scalar index and value need no overload of their own: a C# literal converts to a 0-d array marked as the
Python scalar it stands for, so np.put(a, 1, 1000) raises NumPy's OverflowError for an int8 target
exactly as NumPy's Python int does. The former (long index, object value) overload made that very
call ambiguous (CS0121: the literal index preferred long, the literal value NDArray), so only
cast arguments ever reached it; a value held in an object variable goes through
asanyarray(in object, DType, char?, string, bool?).
Exceptions
- ArgumentNullException
aorindis null.- TypeError
vis null (None) andais an integer (ordecimal) array.- ValueError
A bad
mode(NumPy'sclipmode_parsertexts, see ClipmodeConverter(string)) — reported first, as NumPy parses it with the arguments —, then a read-onlya(put: output array is read-only).- TypeError
The index dtype cannot be cast to int64 under the
saferule (float, complex, uint64), an empty index array included.- IndexError
ais empty whileindis not (cannot replace elements of an empty array), or an index is out of bounds undermode="raise"(index 9 is out of bounds for axis 0 with size 4).- OverflowError
A C# literal value out of
a's integer range (NumPy's OverflowError: "Python integer 1000 out of bounds for int8"), checked after the indices.- ValueError
A float NaN literal into an integer array ("cannot convert float NaN to integer").
- OverflowError
A float infinity literal into an integer array ("cannot convert float infinity to integer").
- TypeError
A complex literal into a real array (Python's
float()/int()text).
put_along_axis(NDArray, NDArray, NDArray, int?)
Put values into the destination array by matching 1-D index and data slices — the
setter twin of take_along_axis(NDArray, NDArray, int?). Iterates over
matching 1-D slices oriented along axis in the index and data
arrays and uses the former to place values into the latter.
In-place: arr is modified and nothing is returned. Functions
returning an index along an axis, like argsort and argmax/argmin
with keepdims, produce suitable indices.
public static void put_along_axis(NDArray arr, NDArray indices, NDArray values, int? axis)
Parameters
arrNDArrayDestination array
(Ni..., M, Nk...), modified in place. Must be writeable.indicesNDArrayInteger index array
(Ni..., J, Nk...). Must match the dimension count ofarr; the non-axis dimensionsNi/Nkneed only broadcast againstarr.Jneed not equalM.valuesNDArrayValues to write, cast to
arr's dtype (assignment cast: floats truncate toward zero). Broadcast — NOT cycled — to the indexing result shape(Ni..., J, Nk...): right-aligned, with extra leading size-1 dimensions stripped. Where several index positions collapse onto onearrelement (a size-1arrdimension, or duplicate indices in a slice), the last write in C-order wins.nullis Python'sNone, converted intoarr's dtype (NaN,nan+nanj,False,'None', aStringDTypeNA object; int()'s TypeError for an integer array, before the indices' bounds are checked).axisint?The axis to place 1-D slices along (no default — required, as in NumPy). When
nullthe destination is treated as its C-order flattening: a C-contiguousarris written back through that flat view (matching NumPy'snp.array(arr.flat), which aliases contiguous storage), while a non-contiguousarrraises read-only — NumPy'snp.array(arr.flat)yields a read-only copy there, so the assignment fails (probed 2.4.2).indicesmust then be 1-D.
Remarks
Exceptions
- ArgumentNullException
arrorindicesis null.- TypeError
valuesis null (None) andarris an integer (ordecimal) array.- ValueError
axisisnullandindicesis not 1-D; the dimension counts ofarrandindicesdiffer; orvaluescannot broadcast to the indexing result shape.- IndexError
indicesis not an integer array; a non-axis dimension ofindicesconflicts witharr; or an index is out of bounds for the axis (after a single negative wrap). On out-of-bounds NOTHING is written — every index is validated before the first store (NumPy's atomicity).- AxisError
axisis out of range forarr's rank.- ValueError
arr(or the non-contiguousaxis=nullflat copy) is read-only — NumPy's "assignment destination is read-only".
putmask(NDArray, NDArray, NDArray)
Change elements of a based on a boolean mask and
input values. Where mask is true (walked in
C-order), writes a.flat[i] = values.flat[i % values.size].
In-place.
public static void putmask(NDArray a, NDArray mask, NDArray values)
Parameters
aNDArrayTarget array (modified in place).
maskNDArrayBoolean mask. Must have the same total size as
a— NumPy allows shape mismatch as long as element counts match. Non-bool masks are cast to bool (!= 0; NaN/inf → true).valuesNDArrayValues to write, cast to
a's dtype. Cycled by position: the value written at flat indexiisvalues.flat[i % values.size](the cursor advances on every element, unlike place(NDArray, NDArray, NDArray) which advances only on True positions). An emptyvaluesis a no-op — NumPy returns without touchinga(unlike place(NDArray, NDArray, NDArray), which raises).nullis Python'sNone: one value, converted intoa's dtype after the mask's size check (NoneForStore(DType): NaN,nan+nanj,False,'None', aStringDTypeNA object; int()'s TypeError for an integer array, even under an all-false mask).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.putmask.html
Differs from place(NDArray, NDArray, NDArray) in two probed ways (NumPy 2.4.2):
the values cursor advances by position (every element) rather than per
True, and an empty values is a silent no-op rather
than a ValueError.
Scoped by [NDScoped]: the scratch copy (a non-contiguous target, or one that may overlap
values/mask) and the bool/dtype-converted copies of
mask and values are released on return, exceptions included. A
mask or values array used as-is is the caller's (built before the scope opened), so the scope never
disposes it.
Exceptions
- ArgumentNullException
aormaskis null.- TypeError
valuesis null (None) andais an integer (ordecimal) array.- ValueError
ais read-only (checked first, as NumPy does), ormask's size differs froma's (putmask: mask and data must be the same size).- InvalidCastException
An array
valuesdoes not cast 'safely' toa's dtype (NumPy's TypeError:Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'safe') — even when it is empty. A 0-d value (NumSharp's stand-in for a Python scalar) is converted unconditionally.- UnicodeEncodeError
Text values that are not ASCII into an
Sarray.- UnicodeDecodeError
Byte values that are not ASCII into a
Uarray.- ValueError
A text value that does not parse into a numeric array (NumPy's
int()/float()/complex()texts); numbers into a text array are written as theirstr().- SystemError
A
Umask holds a unit above U+10FFFF: NumPy's string-to-bool cast of the mask raises it, before the size check. (A text mask is otherwise read by its truth values: a non-empty string is True.)
putmask(NDArray, NDArray, Array)
putmask(NDArray, NDArray, NDArray) with the values given as a C# array — NumPy's Python LIST of
values: np.putmask(a, mask, [1.9, 2.9]) is np.putmask(a, mask, new[] { 1.9, 2.9 }).
public static void putmask(NDArray a, NDArray mask, Array values)
Parameters
aNDArrayTarget array (modified in place).
maskNDArrayBoolean mask of
a's size.valuesArrayThe values, cycled by position. NumPy converts a list STRAIGHT INTO
a's dtype (PyArray_FromAny(list, a.dtype)), so there is no'safe'rule: every item is stored by the dtype's setitem —[1.9, 2.9]into an int32 array truncates,[1, 2.5]into a<U3array is['1', '2.5']— wherenp.array([1.9, 2.9])raises the cast TypeError; a Python int the array cannot hold raises ([1000]into int8). The conversion happens after the mask's checks.
Remarks
C# binds a typed array argument here rather than to the NDArray overload (a reference
conversion beats NumSharp's implicit Array → NDArray one): pass np.array(...) for NumPy's ndarray
semantics. A bare null binds here too (Array is the better conversion target), and is Python's
None exactly as in the NDArray overload. The list is converted by the body
(PutMaskCore(NDArray, NDArray, object)), where NumPy converts it: after the target's writeability and the
mask's size, so a wrong-size mask is reported before a ragged list.
Exceptions
- ArgumentNullException
aormaskis null.- TypeError
valuesis null (None), or holds None, andais an integer (ordecimal) array.- ValueError
The checks of putmask(NDArray, NDArray, NDArray); a ragged list (NumPy's inhomogeneous-shape text), a NaN into an integer array, a text value that does not parse into a numeric array.
- OverflowError
A Python int outside an integer array's range (
Python integer 1000 out of bounds for int8).- UnicodeEncodeError
Text values that are not ASCII into an
Sarray.- UnicodeDecodeError
Byte values that are not ASCII into a
Uarray.
quantile(NDArray, NDArray, int, NDArray, bool, string, bool, NDArray)
quantile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray) with the axis as
one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray quantile(NDArray a, NDArray q, int axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result;0.5or1is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. An integer q - a C# integer literal is NumPy's Python int, a 0-d int64 - makes methodlinear's virtual index(n - 1) * qan integer that NumPy TAKES instead of interpolating (the data's own dtype and element:np.quantile(int_array, 1)is an int64).axisintThe axis (NumPy's
axis=k; a negative value counts from the end).outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The quantiles: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.quantile.html. NumPy's body is the engine's
(Quantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric quantile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 8 overloads (q as
double, double[], NDArray or long, by an int? or
int[] axis), which made np.quantile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q(NumPy's [0, 1] check: Python's'<=' not supported between instances of 'float' and 'numpy.str_'for a 1-d q of fewer than 10 elements,q.min()'sminimumrefusal otherwise; an empty one reaches the string repeat's refusal).- ArgumentException
A numeric quantile's q of rank above 1, or a quantile outside [0, 1] (NumPy's ValueError texts).
- ValueError
Over text data: a q of rank above 2 (
q must be a scalar or 1d, after the axis), or an empty q of two dimensions (itsq.min()range check).- IndexError
Text data with an empty reduced axis (NumPy's take:
cannot do a non-empty take from an empty axes., or an index out of bounds).- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea: a line of two or more elements holding a None-like NA (the sort'sCannot compare null that is not a nan-like value), or the unsafe write-back into a numericoutthat cannot parse a string (could not convert string to float: 'a').- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the checks that come first (q, the axes, the method, keepdims' out).- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before q's rank, the method and the data's refusals.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(its [0, 1] check refuses); over text data an interpolating method (NumPy subtracts the text), anoutthat does not cast safely to the data, or keepdims over a 0-d result.- ArgumentException
A numeric quantile's q of rank above 1, a quantile outside [0, 1], an unknown method, or an
outof another shape (numeric data; NumPy's ValueError texts).- ValueError
An axis repeats; over text data a q of rank above 2, an empty q of two dimensions, or an
outof another shape.- AxisError
An axis is out of range for
a.- IndexError
Text data with an empty reduced axis (NumPy's take, or the interpolating methods' neighbour lookup).
quantile(NDArray, NDArray, int[], NDArray, bool, string, bool, NDArray)
quantile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray) with the axes as
an int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray quantile(NDArray a, NDArray q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result;0.5or1is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. An integer q - a C# integer literal is NumPy's Python int, a 0-d int64 - makes methodlinear's virtual index(n - 1) * qan integer that NumPy TAKES instead of interpolating (the data's own dtype and element:np.quantile(int_array, 1)is an int64).axisint[]The axes as NumPy's tuple, or
nullfor None.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The quantiles: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.quantile.html. NumPy's body is the engine's
(Quantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric quantile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 8 overloads (q as
double, double[], NDArray or long, by an int? or
int[] axis), which made np.quantile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q(NumPy's [0, 1] check: Python's'<=' not supported between instances of 'float' and 'numpy.str_'for a 1-d q of fewer than 10 elements,q.min()'sminimumrefusal otherwise; an empty one reaches the string repeat's refusal).- ArgumentException
A numeric quantile's q of rank above 1, or a quantile outside [0, 1] (NumPy's ValueError texts).
- ValueError
Over text data: a q of rank above 2 (
q must be a scalar or 1d, after the axis), or an empty q of two dimensions (itsq.min()range check).- IndexError
Text data with an empty reduced axis (NumPy's take:
cannot do a non-empty take from an empty axes., or an index out of bounds).- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea: a line of two or more elements holding a None-like NA (the sort'sCannot compare null that is not a nan-like value), or the unsafe write-back into a numericoutthat cannot parse a string (could not convert string to float: 'a').- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the checks that come first (q, the axes, the method, keepdims' out).- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before q's rank, the method and the data's refusals.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(its [0, 1] check refuses); over text data an interpolating method (NumPy subtracts the text), anoutthat does not cast safely to the data, or keepdims over a 0-d result.- ArgumentException
A numeric quantile's q of rank above 1, a quantile outside [0, 1], an unknown method, or an
outof another shape (numeric data; NumPy's ValueError texts).- ValueError
An axis repeats; over text data a q of rank above 2, an empty q of two dimensions, or an
outof another shape.- AxisError
An axis is out of range for
a.- IndexError
Text data with an empty reduced axis (NumPy's take, or the interpolating methods' neighbour lookup).
quantile(NDArray, NDArray, NDAxis?, NDArray, bool, string, bool, NDArray)
NumPy's np.quantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *,
weights=None): the q-th quantile(s) of the data along the given axes (of the flattened data by
default).
public static NDArray quantile(NDArray a, NDArray q, NDAxis? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data (any real dtype; text —
S,U, NEP 55StringDType— takes NumPy's take path or its refusal, see the exceptions).qNDArrayNumPy's array_like
qas one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result;0.5or1is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), adouble[]to a 1-d q (one result per element, q's axis first), and an NDArray is taken as it is (0-d or 1-d; up to 2-d over text data), a STRONG q for the result dtype. An integer q - a C# integer literal is NumPy's Python int, a 0-d int64 - makes methodlinear's virtual index(n - 1) * qan integer that NumPy TAKES instead of interpolating (the data's own dtype and element:np.quantile(int_array, 1)is an int64).axisNDAxis?NumPy's
axis:null(None, the default) reduces the flattened data; one axis (negative counts from the end) or a tuple ((0, 2),new[] { 0, 2 }) reduces those axes, merged into one before the partition; the empty tuple reduces nothing.outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
methodstringThe estimation method (
linearby default; NumPy's thirteen names).keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=(keyword-only there), only with methodinverted_cdf: one weight per element ofa(its shape, or the reduced axes' shape); null (the default) weighs every element equally. A weighted call takes NumPy's weighted branch: the data sorted, the weights' cumulative sum normalized, and each q searched in it; the result has the data's dtype.
Returns
- NDArray
The quantiles: one per element of q (q's axes first; a scalar result for a 0-d q), with the axes reduced;
outitself when one is given.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.quantile.html. NumPy's body is the engine's
(Quantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)): the complex check, q's checks, the weighted branch, the text routes
and the numeric quantile, in NumPy's order; _ureduce turns an integer axis into a one-element tuple, so
the engine member takes the axes as an array.
A numpy.matrix operand: an integer axis gives the class rule's matrix, the class rule of a TUPLE
sees no axis (the rule NumSharp's tuple overloads had: the scalar of a full reduction, a row otherwise) -
NumPy's own answers come from matrix semantics inside its Python code, which NumSharp does not reproduce.
One signature since API-parity batch 4 (2026-11-12): it replaces the 8 overloads (q as
double, double[], NDArray or long, by an int? or
int[] axis), which made np.quantile(a, q, null) ambiguous (CS0121) and had no tuple literal. Every
former q spelling converts, and the engine reads a converted C# number as the number it was (its
QuantileQ): each call keeps the answer it had.
Exceptions
- ArgumentNullException
ais null.- ArgumentNullException
qis null.- TypeError
A text
q(NumPy's [0, 1] check: Python's'<=' not supported between instances of 'float' and 'numpy.str_'for a 1-d q of fewer than 10 elements,q.min()'sminimumrefusal otherwise; an empty one reaches the string repeat's refusal).- ArgumentException
A numeric quantile's q of rank above 1, or a quantile outside [0, 1] (NumPy's ValueError texts).
- ValueError
Over text data: a q of rank above 2 (
q must be a scalar or 1d, after the axis), or an empty q of two dimensions (itsq.min()range check).- IndexError
Text data with an empty reduced axis (NumPy's take:
cannot do a non-empty take from an empty axes., or an index out of bounds).- TypeError
ais complex: "a must be an array of real numbers", NumPy's first statement (before q is read).- TypeError
A NEP 55
StringDTypea: an interpolating method (NumPy's_lerpsubtracts the two neighbours:unsupported operand type(s) for -: 'str' and 'str', or nosubtractloop for a non-scalar result), anoutthat does not cast safely to the data (the take path) or receive_lerp's float64, or keepdims over NumPy's Python-object result (string indices must be integers, not 'tuple','float' object is not subscriptable).- ValueError
A NEP 55
StringDTypea: a line of two or more elements holding a None-like NA (the sort'sCannot compare null that is not a nan-like value), or the unsafe write-back into a numericoutthat cannot parse a string (could not convert string to float: 'a').- TypeError
A
numpy.char.chararrayoperand: NumPy'sa.partition(kth, axis=...)is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the checks that come first (q, the axes, the method, keepdims' out).- ValueError
With
weights: another method (Only method 'inverted_cdf' supports weights. Got: linear.), weights of a wrong shape, a negative weight, weights that sum to NaN, inf or zero, or a repeated axis (repeated axis in).axisargument- TypeError
With
weights: weights of another shape without an axis, or text weights (the comparison's refusal).- IndexError
keepdimswith anoutNumPy cannot index:_ureduce'sout[(Ellipsis,) + index_out](too few dimensions, or a reduced axis of length 0), raised for every dtype before q's rank, the method and the data's refusals.- TypeError
ais complex ("a must be an array of real numbers", NumPy's first statement); a textq(its [0, 1] check refuses); over text data an interpolating method (NumPy subtracts the text), anoutthat does not cast safely to the data, or keepdims over a 0-d result.- ArgumentException
A numeric quantile's q of rank above 1, a quantile outside [0, 1], an unknown method, or an
outof another shape (numeric data; NumPy's ValueError texts).- ValueError
An axis repeats; over text data a q of rank above 2, an empty q of two dimensions, or an
outof another shape.- AxisError
An axis is out of range for
a.- IndexError
Text data with an empty reduced axis (NumPy's take, or the interpolating methods' neighbour lookup).
rad2deg(NDArray, NDArray, NDArray, DType)
Convert angles from radians to degrees.
public static NDArray rad2deg(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngle in radians.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The corresponding angle in degrees. This is a scalar if x is a scalar.
Remarks
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.).
radians(NDArray, NDArray, NDArray, DType)
Convert angles from degrees to radians. Alias for deg2rad.
public static NDArray radians(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngles in degrees.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The corresponding angle in radians. This is a scalar if x is a scalar.
Remarks
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.).- ArgumentNullException
xis null.
ravel(NDArray, char)
Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned — a
VIEW whenever the requested reading order walks the input's memory front to back, otherwise a copy
(NumPy's PyArray_Ravel, numpy/_core/src/multiarray/shape.c).
public static NDArray ravel(NDArray a, char order = 'C')
Parameters
aNDArrayInput array.
ordercharThe order in which to read the elements. 'C' - row-major, 'F' - column-major, 'A' - 'F' if a is F-contiguous (and not C-contiguous) else 'C', 'K' - the order the elements occur in memory: C / F for a C- / F-contiguous array, a view when the array is dense in some other axis order (a transpose of a contiguous array), else a copy read in NpyIter's KEEPORDER axis order (each axis in increasing index — a negative stride is NOT reversed, a broadcast axis abstains).
Returns
- NDArray
The 1-D result: a view that shares
a's memory (and its writeability), or a fresh copy. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ravel.html
<p>One signature, NumPy's <code>ravel(a, order='C')</code>: the one-argument overload went with API-parity batch
3 (2026-11-11), so <code>np.ravel(a)</code> binds here with the default 'C'.</p>
Exceptions
- ArgumentException
An order code other than C, F, A or K.
ravel_multi_index(NDArray[], Shape, string, char)
Converts a tuple of coordinate arrays into an array of flat indices, applying boundary modes per axis —
NumPy's arr_ravel_multi_index (numpy/_core/src/multiarray/compiled_base.c), statement for
statement. Inverse of unravel_index(NDArray, Shape, char).
public static NDArray<long> ravel_multi_index(NDArray[] multi_index, Shape dims, string mode = "raise", char order = 'C')
Parameters
multi_indexNDArray[]The coordinate arrays, one per dimension of
dims: integer or bool, any layout; they broadcast against each other, and the broadcast shape is the result's shape. A null entry is NumPy'sNone, which is refused (TypeError).dimsShapeThe shape of the array the coordinates index (
a.shape,a.Shape, anint[], a tuple). An empty shape (NumPy's()) takes no coordinate array and gives the flat index 0.modestringBoundary mode for every axis:
"raise"(default — an out-of-range coordinate raises),"wrap"(modulo with sign correction) or"clip"(saturate).orderchar'C'(row-major, default) or'F'(column-major), in either case: the stride ordering used to fold coordinates into a flat index.
Returns
- NDArray<long>
The int64 flat indices, in the coordinates' broadcast shape, laid out as NumPy's iterator allocates them (KEEPORDER over the coordinate arrays: F-ordered coordinates give an F-ordered result, a transposed set the same permutation, mixed or broadcast ones C order). Coordinates that are all 0-d give NumPy's scalar: a fresh read-only 0-d array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.ravel_multi_index.html
BREAKING (NumPy parity): the result used to be C-ordered for any coordinate layout, and an
'A' / 'K' order and a dims product overflow were refused only after the coordinates were
read. A lowercase order letter is accepted, an empty dims is legal, a zero dimension in
wrap or clip mode raises NumPy's ValueError (it used to divide by zero), and the errors are
ValueError (an ArgumentException).
Deliberate divergence: NumPy refuses more than 63 dimensions (too many dimensions passed to
ravel_multi_index, its fixed iterator operand limit); NumSharp has no dimension cap.
The body is RavelMultiIndex(NDArray[], long[], object, char) (the np-layer dtype plan): this facade computes a
numpy.matrix operand as a plain array and calls the first coordinate array's engine.
dims is a Shape since API-parity batch 13 (parity QA-56): it was an
int[], which neither a.shape nor a.Shape converted to.
Exceptions
- ArgumentNullException
multi_indexis null.- ValueError
In NumPy's order: an order letter that is not C / F / A / K (
order must be one of 'C', 'F', 'A', or 'K' (got 'X')); a badmode(NumPy'sclipmode_parsertexts, see ClipmodeConverter(string)); an'A'or'K'order (only 'C' or 'F' order is permitted); a dims product that overflows int64 (invalid dims: array size defined by dims is larger than the maximum possible size.); a coordinate count that differs fromdims' length (parameter multi_index must be a sequence of length N); a zero dimension while there is a coordinate to fold (cannot unravel if shape has zero entries (is empty)., whatever the mode); and (moderaise) a coordinate out of range (invalid entry in coordinates array).- TypeError
A coordinate array that is neither integer nor bool, or a null entry (NumPy's
None):only int indices permitted, checked in order after the count.- IncorrectShapeException
The coordinate arrays do not broadcast together (NumPy's
ValueErrortext from its iterator, every coordinate shape listed:operands could not be broadcast together with shapes (2,) (3,)).- NotSupportedException
Runtime code generation is unavailable (the IL kernel cannot be emitted).
ravel_multi_index(NDArray[], Shape, string[], char)
Per-axis mode overload. mode length must match
dims length.
public static NDArray<long> ravel_multi_index(NDArray[] multi_index, Shape dims, string[] mode, char order = 'C')
Parameters
multi_indexNDArray[]The coordinate arrays, one per dimension (integer or bool; a null entry is NumPy's
None, refused).dimsShapeShape of the array the indices are unravelling into.
modestring[]One boundary mode per dimension (NumPy's
modetuple, under NumPy's keyword name; namedmodesbefore API-parity batch 7 — so a baremode: null, which both forms now accept, is a compile-time ambiguity: write(string[])nullor(string)null, both NumPy's None);nullis NumPy'sNone, which raises on every dimension.orderchar'C'(default) or'F', in either case.
Returns
- NDArray<long>
The flat indices, laid out as ravel_multi_index(NDArray[], Shape, string, char) lays them out.
Remarks
The body is RavelMultiIndex(NDArray[], long[], object, char), as for the single-mode overload.
Exceptions
- ArgumentNullException
multi_indexis null.- ValueError
In NumPy's order: a bad order letter; a mode count that differs from the dimensions (
list of clipmodes has wrong length (1 instead of 2)) or a bad mode (ClipmodeConverter(string)); an'A'/'K'order; a dims product overflow; a coordinate count that differs fromdims' length; a zero dimension with a coordinate to fold; (moderaise) a coordinate out of range.- TypeError
A coordinate array that is neither integer nor bool, or a null entry (NumPy's
None):only int indices permitted.- IncorrectShapeException
The coordinate arrays do not broadcast together (NumPy's iterator text).
- NotSupportedException
The IL kernel cannot be emitted.
ravel_multi_index(long[], Shape, string, char)
Scalar convenience overload — folds a single coordinate tuple into a flat index. Equivalent to wrapping each coord in a 0-d NDArray but returns a long directly.
public static long ravel_multi_index(long[] multi_index, Shape dims, string mode = "raise", char order = 'C')
Parameters
multi_indexlong[]One coordinate per dimension (NumPy's keyword name; named
coordsbefore API-parity batch 7).dimsShapeThe shape the coordinates index (
a.shape,a.Shape, anint[]); an empty shape takes no coordinate and gives 0.modestring"raise"(default),"wrap"or"clip", for every axis.orderchar'C'(default) or'F', in either case.
Returns
- long
The flat index.
Exceptions
- ArgumentNullException
multi_indexis null.- ValueError
In NumPy's order: a bad order letter; a bad mode; an
'A'/'K'order; a dims product overflow; a coordinate count that differs fromdims' length (parameter multi_index must be a sequence of length N); a zero dimension (cannot unravel if shape has zero entries (is empty).); (moderaise) a coordinate out of range (invalid entry in coordinates array).
real(NDArray)
Return the real part of the complex argument, element-wise.
One of the four basic complex-number accessors (with imag(NDArray), angle(NDArray, bool)
and conjugate(NDArray, NDArray, NDArray, DType)) — the standard post-FFT spectrum component extractors: for
A = np.fft.fft(a), A.real / np.real(A) is the real component.
public static NDArray real(NDArray val)
Parameters
valNDArrayInput array.
Returns
- NDArray
For a COMPLEX input: a float64 VIEW onto the real lane — it SHARES memory with
valand is writeable, sonp.real(z)[i] = xwrites through toz[i]'s real part (reproducing NumPy'sz.real; complex128 -> float64). For a REAL / integer / boolean input: NumPy returns the array itself (the real part of a real number is the number), so the input is returned unchanged with its dtype preserved.
Remarks
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.).
real_if_close(NDArray, double)
If the input is complex with EVERY imaginary part close to zero, return the (float64) real
parts; otherwise return the input unchanged. "Close to zero" is tol multiples of the
machine epsilon of the complex type (float64 eps here) when tol > 1,
and the plain absolute value of tol when tol <= 1.
public static NDArray real_if_close(NDArray a, double tol = 100)
Parameters
aNDArrayInput array. A real / integer / boolean array is returned UNCHANGED (the same instance) — the collapse only applies to complex input; NumPy does the same (its
asanyarray(a)is already satisfied by the NDArray parameter, and scalars / C# arrays convert implicitly at the call site).toldoubleTolerance for the imaginary part. When > 1 it is interpreted in machine epsilons (
tol * eps); when <= 1 it is used as an absolute tolerance directly. FOOTGUN matching NumPy: withtol <= 0NOTHING collapses (a magnitude|imag| >= 0is never strictly< 0), even for an exactly-zero imaginary part. The default100resolves to100 * 2.22e-16 ≈ 2.22e-14.
Returns
- NDArray
For a COMPLEX input whose imaginary parts are all strictly within
tolof zero: a float64 VIEW onto the real lane (shares memory witha, exactly like real(NDArray) / NumPy'sa.real). An EMPTY complex array always collapses (an emptyallis vacuously true), yielding an empty float64 view. Otherwise (a real/int/bool input, or a complex input with any imaginary part >=tol, NaN or infinite):aitself, unchanged.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.real_if_close.html
Port of NumPy 2.4.2 numpy/lib/_type_check_impl.py::real_if_close, whose body is
if all(absolute(a.imag) < tol): a = a.real. The whole-array decision
(AllImagWithinTol(NDArray, double)) fuses NumPy's absolute temp, the
boolean < temp and the all reduce into ONE early-exit streaming pass over
the imaginary lane (no intermediate allocation), so it beats the three-pass NumPy sequence
on every layout. NaN / ±inf imaginary parts prevent the collapse (the comparison with
tol is false), and the comparison is STRICT, so an imaginary part exactly equal to
tol also prevents it — all probed against NumPy 2.4.2. The collapse
companion real(NDArray) keeps the real lane's writeability, so — like NumPy's
a.real — writing through the returned view writes through to a.
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.).- ArgumentNullException
ais null.
reciprocal(NDArray, NDArray, NDArray, DType)
Return the reciprocal of the argument, element-wise. Calculates 1/x.
public static NDArray reciprocal(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
Return array containing 1/x for each element in x. This is a scalar if x is a scalar.
Remarks
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.).
remainder(NDArray, NDArray, NDArray, NDArray, DType)
Return element-wise remainder of division (the floored remainder — result has the same
sign as the divisor, Python's %). In NumPy remainder IS mod (the same
ufunc), so this is a straight alias of mod(NDArray, NDArray, NDArray, NDArray, DType).
The complement fmod(NDArray, NDArray, NDArray, NDArray, DType) uses the
dividend's sign instead.
public static NDArray remainder(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayDividend array.
x2NDArrayDivisor array; broadcasts against
x1.outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=).
Returns
- NDArray
The floored remainders, or
outitself when given.
Remarks
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.).- IncorrectTypeException
A bool or complex
dtype: remainder has integer and float loops only, so NumPy'sNo loop matching the specified signature and casting was found for ufunc remainder(parity QA-53).
remainder(NDArray, float)
public static NDArray remainder(NDArray x1, float x2)
Parameters
Returns
repeat(NDArray, NDArray, int?)
Repeat elements of an array with per-element repeat counts. Mirrors NumPy
np.repeat(a, repeats, axis): scalar / size-1 repeats broadcasts to
every element along the (flattened or selected) axis; otherwise the length must match.
public static NDArray repeat(NDArray a, NDArray repeats, int? axis = null)
Parameters
aNDArrayInput array.
repeatsNDArrayRepeat counts. Either a 0-d/size-1 array (broadcast) or a 1-D array of length equal to
a.size(axis=None) ora.shape[axis].axisint?Axis along which to repeat.
nullflattens the input.
Returns
- NDArray
A new array with elements repeated according to
repeats. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.repeat.html
NumPy converts the repeats with PyArray_ContiguousFromAny(repeats, NPY_INTP, 0, 1) before it reads the axis:
the rank (at most 1) first, then the 'safe' cast — so a 2-D repeats is the rank's ValueError whatever its dtype,
and both precede an out-of-range axis. (A 2-D repeats used to be flattened.)
One signature, NumPy's repeat(a, repeats, axis=None): the int / long count
overloads went with API-parity batch 3 (2026-11-11). A C# integer converts to a 0-d array, which broadcasts
over every element through the same tiling kernel, so np.repeat(a, 3) keeps its answer. The scalar form
repeat<T>(T, NDArray) stays beside it (the owner's call).
Exceptions
- ArgumentNullException
aorrepeatsis null.- ValueError
repeatshas more than one dimension (object too deep for desired array, checked first).- TypeError
repeatsdoes not cast 'safely' to int64 — uint64, a float, complex, decimal or text (Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe';Cannot cast scalar …for a 0-d repeats).- AxisError
axisis out of range.- ValueError
A negative entry of a per-element count array (NumPy's
repeats may not contain negative values.).- ArgumentException
The repeats' length does not match, or one broadcast count is negative (NumPy's text for that one is
negative dimensions are not allowed: pinned).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
repeat<T>(T, NDArray)
Repeat a C# scalar value: NumPy's np.repeat(scalar, repeats), whose 0-d operand ravels to one
element, as a 1-D array of T's dtype.
public static NDArray repeat<T>(T a, NDArray repeats) where T : unmanaged
Parameters
aTThe value to repeat.
repeatsNDArrayThe count: a 0-d integer array (a C# integer converts to one) fills the result directly; anything else - a size-1 array, a float count - takes repeat(NDArray, NDArray, int?)'s route with
aas a 0-d array, NumPy's checks and texts included.
Returns
- NDArray
A new 1-D array of
arepeated.
Type Parameters
TThe scalar's type; its dtype is the result's (a C#
intgives int32).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.repeat.html
<p>NumSharp's scalar form, kept by the owner beside NumPy's one signature (API-parity batch 3): it
replaces the former <code>repeat<T>(T, int)</code> / <code>repeat<T>(T, long)</code> pair, so a C# value
needs no 0-d wrapper for the common count.</p>
Exceptions
- ArgumentNullException
repeatsis null.- ArgumentException
A negative count (NumPy raises ValueError; pinned as an [OpenBugs] case with the array route's same text).
- ValueError
Counts that do not broadcast to one element, or a repeats of more than one dimension.
- TypeError
A repeats that does not cast 'safely' to int64.
require(NDArray, DType, IEnumerable, NDArray)
Return an ndarray of the provided type that satisfies requirements — NumPy's
np.require(a, dtype=None, requirements=None, *, like=None), one signature.
public static NDArray require(NDArray a, DType dtype = null, IEnumerable requirements = null, NDArray like = null)
Parameters
aNDArrayThe object to be converted to a type-and-requirement-satisfying array.
dtypeDTypeThe required data-type.
nullpreserves the current dtype.requirementsIEnumerableNumPy's
requirements: what NumPy iterates, so a STRING is read character by character ("F"is the Fortran flag,"CW"is C plus WRITEABLE, and"F_CONTIGUOUS"is NOT one name — its''raises NumPy'sKeyError: ''), while astring[], aList<string>or any other sequence of names is read name by name. Each name is one of (any case, NumPy's aliases):- 'F_CONTIGUOUS' / 'F' / 'FORTRAN' — ensure a Fortran-contiguous array
- 'C_CONTIGUOUS' / 'C' / 'CONTIGUOUS' — ensure a C-contiguous array
- 'ALIGNED' / 'A' — ensure a data-type aligned array
- 'WRITEABLE' / 'W' — ensure a writable array
- 'OWNDATA' / 'O' — ensure an array that owns its own data
- 'ENSUREARRAY' / 'E' — ensure a base-class array (a
numpy.matrixor chararray operand gives a plain array)
null, an empty string and an empty collection are NumPy's "no requirement" (asanyarray). A C# tuple is not a sequence here: pass an array.likeNDArrayReference array for NumPy's array-function dispatch — accepted for signature parity but has no observable effect in NumSharp (no array-function dispatch).
Returns
- NDArray
Array with the specified requirements and dtype if given. A copy is made only when needed. A
numpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
Port of NumPy 2.x numpy.require: with no requirements this is exactly asanyarray(a, dtype);
otherwise the set {POSSIBLE_FLAGS[x.upper()] for x in requirements}, an order ('A' by default, or
'C' / 'F' when requested), asarray(NDArray, DType, char?, bool?, NDArray, string), then ONE
copy (in the resolved order) if any of the remaining ALIGNED / WRITEABLE / OWNDATA flags is not already
satisfied: ALIGNED (false after setflags(align=False) or over a caller's buffer at a misaligning byte
offset), WRITEABLE (false for broadcast views) and OWNDATA (false for views).
API-parity batch 10: one signature. The string and string[] overloads became this
IEnumerable parameter, which is what NumPy reads (it iterates requirements); an unknown
name raises NumPy's KeyError instead of the former ValueError("Cannot understand requirement
'x'").
https://numpy.org/doc/stable/reference/generated/numpy.require.html
Exceptions
- ArgumentNullException
ais null.- KeyError
A name that is no flag, with NumPy's text: the upper-cased name, quoted (
'BOGUS','_'), raised at that name — before any later name is looked at.- AttributeError
An item that is not a string (or a character): NumPy's
x.upper()fails with'int' object has no attribute 'upper'('NoneType'for a null item).- ValueError
Both 'C' and 'F' order are requested (
Cannot specify both "C" and "F" order), or anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).
reshape(NDArray, Shape, char, bool?)
Gives a new shape to an array without changing its data — NumPy's one signature,
np.reshape(a, /, shape, order='C', *, copy=None), which (as NumPy's _wrapfunc does) calls the
array's own reshape(Shape, char, bool?).
public static NDArray reshape(NDArray a, Shape shape, char order = 'C', bool? copy = null)
Parameters
aNDArrayArray to be reshaped.
shapeShapeThe new shape. One parameter takes every spelling: an
int(a 1-D result of that length), a tuple ((2, 3)), anint[]/long[]or a Shape — Shape's implicit conversions. One dimension may be -1: it is inferred from the size and the other dimensions.ordercharThe index order the elements are read in and placed in:
'C'(the default, row-major),'F'(column-major), or'A'('F'whenais Fortran-contiguous and not C-contiguous, else'C').'K'is NumPy's ValueError; either case is accepted.copybool?null (the default): a view when the reshape can be one, otherwise a copy; true: always a copy, sharing no memory with
a(even for the same shape); false: never a copy — NumPy'sValueError("Unable to avoid creating a copy while reshaping.")when no view can express the reshape (a transposed array to 1-D in C order).
Returns
- NDArray
The reshaped array: a view of
awhenever possible (and always forcopy: false), otherwise a view over an internal copy (owndata False either way, as in NumPy). Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would; anumpy.matrixoperand gives a matrix.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.reshape.html
API-parity batch 7 made this NumPy's ONE signature: it replaced four overloads (int[],
long[], Shape and ref Shape, every one without order or copy) whose
shapes all reach shape through its conversions, and the first parameter took NumPy's name
(a; it was nd).
Exceptions
- NullReferenceException
ais null.- ValueError
order 'K' is not permitted for reshaping; two -1 dimensions; thecopy: falserefusal; anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- IncorrectShapeException
The size does not match, with NumPy's text (
cannot reshape array of size 6 into shape (4,2); NumPy raises it as a ValueError) — checked before the copy mode.- ArgumentException
An order letter outside NumPy's vocabulary.
resize(NDArray, Shape)
Return a new array with the specified shape.
If the new array is larger than the original array, then the new array is filled
with repeated copies of a (iterating over a
in C-order, cycling back from the start). Note that this behavior is different from
resize(params long[]) which fills with zeros instead.
NumPy's np.resize takes new_shape as a single argument (an int or a
sequence) — the multi-argument form np.resize(a, 2, 3) is a NumPy TypeError,
so it is not offered here. Pass the shape as an int, a value tuple, an array, or a
Shape; all resolve through Shape's implicit conversions:
np.resize(a, 6), np.resize(a, (2, 3)), np.resize(a, new[]{2, 3}),
np.resize(a, new Shape(2, 3)).
public static NDArray resize(NDArray a, Shape new_shape)
Parameters
aNDArrayArray to be resized.
new_shapeShapeShape of resized array (int / tuple / array / Shape).
Returns
- NDArray
The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order. Result is C-contiguous; dtype matches
a. Like NumPy's (a reshape of a slice of the concatenated copies) it is a VIEW of a fresh buffer —flags.owndatais false, so an in-placendarray.resizeof it is refused — except for an empty source or result, which is NumPy's owningnp.zeros_like(a, shape=new_shape). For anumpy.char.chararrayoperand that zero-filled result is a chararray (zeros_likekeeps the subclass); every other result is a plain array (NumPy'snp.concatenatedrops it).
Remarks
Exceptions
- ArgumentNullException
If
ais null.- ArgumentException
If any element of
new_shapeis negative.
result_type(params DType[])
Returns the type that results from applying the NumPy type promotion rules to the given descriptors (all strong).
public static DType result_type(params DType[] dtypes)
Parameters
dtypesDType[]One or more descriptors; a null one is NumPy's
None, the float64 descriptor.
Returns
- DType
The result descriptor.
Exceptions
- ValueError
No descriptor is given: NumPy's "at least one array or dtype is required".
- DTypePromotionError
No common dtype exists.
result_type(NDArray, NDArray)
Returns the type that results from applying the NumPy type promotion rules to the two arrays. Convenience overload to avoid params array allocation.
public static DType result_type(NDArray arr1, NDArray arr2)
Parameters
arr1NDArrayFirst array; null is NumPy's
None, the float64 descriptor.arr2NDArraySecond array; null is NumPy's
None, the float64 descriptor.
Returns
- DType
The result descriptor, its class included (see result_type(params NDArray[])).
Exceptions
- DTypePromotionError
No common dtype exists.
result_type(params NDArray[])
Returns the type that results from applying the NumPy type promotion rules to the arguments. Every array — 0-d included — is a full (strong) participant, as in NumPy 2.x.
public static DType result_type(params NDArray[] arrays)
Parameters
arraysNDArray[]One or more NDArray objects; a null one is NumPy's
None, the float64 descriptor.
Returns
- DType
The result descriptor — its CLASS included: an array of a C-type class contributes that class (
np.result_type(np.zeros(3, np.longdouble))islongdouble), and NumPy's promotion can name one for two canonical classes (Windows'np.result_type(int16_array, uint16_array)is the C int class'i', equal to int32).
Exceptions
- ValueError
No array is given: NumPy's "at least one array or dtype is required".
- DTypePromotionError
No common dtype exists.
result_type(NPTypeCode, NPTypeCode)
Returns the type that results from applying the NumPy type promotion rules to the two type codes. Convenience overload to avoid params array allocation.
public static DType result_type(NPTypeCode type1, NPTypeCode type2)
Parameters
type1NPTypeCodeFirst type code.
type2NPTypeCodeSecond type code.
Returns
- DType
The result type from combining the inputs.
result_type(params NPTypeCode[])
Returns the type that results from applying the NumPy type promotion rules to the arguments.
public static DType result_type(params NPTypeCode[] types)
Parameters
typesNPTypeCode[]One or more NPTypeCode values.
Returns
- DType
The result type from combining the inputs.
Exceptions
- ValueError
No type is given: NumPy's "at least one array or dtype is required".
result_type(params object[])
Returns the type that results from applying the NumPy type promotion rules
to the arguments — NumPy's np.result_type(*arrays_and_dtypes) (PyArray_ResultType) under
NEP 50.
public static DType result_type(params object[] arrays_and_dtypes)
Parameters
arrays_and_dtypesobject[]Arrays and/or dtype arguments: any mix of NDArray, DType, DTypeMeta (a bare class), NPTypeCode, Type, dtype string, and C# scalars. A null operand is NumPy's
None: the strong float64 descriptor (np.result_type(None, np.int8)is float64).
Returns
- DType
The result descriptor.
Examples
np.result_type(NPTypeCode.Int32, NPTypeCode.Int64) // int64
np.result_type(a, 5) // a.dtype (weak int)
np.result_type(a, 5.0) // float64 for an integer a
np.result_type("M8[s]", "m8[ms]") // datetime64[ms]
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
NEP 50 in C#. Every NDArray — 0-d included — contributes its dtype fully ("strong"), as do
DType, NPTypeCode, Type, dtype strings, bool, char,
Half and decimal values. A C# integer literal (int, long, …), a float/double
or a Complex is WEAK — the analog of a Python int/float/complex — and only contributes its
category: result_type(int8_array, 300) is int8 (no value-based inspection), result_type(int8_array,
1.5) is float64, result_type(float32_array, 1e300) is float32; a lone literal falls back to
int64 / float64 / complex128.
The descriptor arguments are promoted before the arrays and scalars, as NumPy's array_result_type does: the
result does not depend on it, a refusal's text does (np.result_type(text_array, np.float64) names
Float64DType as the DType that "could not be promoted by" StringDType).
The reduction over three or more operands is NumPy's order-independent PyArray_PromoteDTypeSequence
(result_type(i1, i1, f8, i1) is float64 in every order). Parametric operands resolve their
common_instance (result_type("M8[s]", "m8[ms]", "m8[us]") is datetime64[us]).
Exceptions
- ValueError
at least one array or dtype is required(no operands).- DTypePromotionError
No common dtype exists — NumPy's verbatim text, listing every operand class.
result_type(params string[])
Returns the type that results from applying the NumPy type promotion rules
to the given dtype strings (np.result_type("i1", "f8")). Exists so that a string argument binds the
dtype grammar rather than NumSharp's string→NDArray (character array) conversion.
public static DType result_type(params string[] dtypes)
Parameters
dtypesstring[]One or more dtype strings; a null one is NumPy's
None, the float64 descriptor.
Returns
- DType
The result descriptor.
Exceptions
- ValueError
No string is given: NumPy's "at least one array or dtype is required".
- TypeError
A string NumPy cannot parse either (NumPy's
data type 'x' not understood).- NotSupportedException
A string naming a dtype NumSharp has no class for.
- DTypePromotionError
No common dtype exists.
result_type(Type, Type)
Returns the type that results from applying the NumPy type promotion rules to the two CLR types. Convenience overload to avoid params array allocation.
public static DType result_type(Type type1, Type type2)
Parameters
type1TypeFirst CLR type; null is NumPy's
None, the float64 descriptor.type2TypeSecond CLR type; null is NumPy's
None, the float64 descriptor.
Returns
- DType
The result type from combining the inputs.
Exceptions
- ArgumentException
A type that is no NumSharp element type (its code is Empty).
- DTypePromotionError
No common dtype exists.
right_shift(NDArray, NDArray, NDArray, NDArray, DType)
Shift the bits of an integer to the right.
Mirrors NumPy's ufunc signature: right_shift(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray right_shift(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayValue operand (integer/bool/char only; bool promotes to int8).
x2NDArrayShift-count operand (integer/bool/char only).
outNDArrayA location into which the result is stored; must be same_kind-castable from the promoted loop dtype. Returned as-is.
whereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeOptional loop dtype override; must be an integer/char loop — a float/complex/decimal request raises NumPy's no-loop TypeError.
Returns
- NDArray
Array with bits shifted right (or
outwhen provided).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.right_shift.html
One signature, NumPy's ufunc form (2026-11-11): the former overload that took the shift count as an
object read a boxed number as a STRONG array; a C# literal converts to a 0-d array marked as the
Python scalar it stands for (NEP 50's weak scalar), and a value held in an object variable goes
through asanyarray(in object, DType, char?, string, bool?).
Bits are shifted to the right by removing x2 bits from the right of x1. For unsigned integers, this is logical shift (zeros filled from left). For signed integers, this is arithmetic shift (sign bit extended). This operation is equivalent to floor division by 2**x2.
Example: np.right_shift(20, 2) = 5 # 0b10100 -> 0b101
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.).
rint(NDArray, NDArray, NDArray, DType)
Round elements of the array to the nearest integer, element-wise (round half to even). The result is a float (rint has no integer loop): integer/bool inputs promote to the float tier (bool/int8/uint8 -> float16, int16/uint16 -> float32, int32/int64/... -> float64), floats and complex are preserved. The real and imaginary parts of complex numbers are rounded separately.
public static NDArray rint(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArrayA location into which the result is stored (same_kind cast from the loop dtype).
whereNDArrayBoolean mask; compute only where true, leaving other
outslots unchanged.dtypeDTypeLoop dtype override (must be a float/complex loop).
Returns
- NDArray
An array of the same shape as x, containing the rounded values. This is a scalar if x is a scalar.
Remarks
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.).
roll(NDArray, NDArray, int)
roll(NDArray, NDArray, NDAxis?) with the axis as one int: the overload a C# integer
binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every
answer, error, layout and subclass result is that overload's.
public static NDArray roll(NDArray a, NDArray shift, int axis)
Parameters
aNDArrayInput array.
shiftNDArrayThe number of places by which elements are shifted: a C# integer (it converts to a 0-d array), or an array of one dimension (
new[] { 1, 2 }) broadcast against the axes - one shift for every axis, or one per axis. Each element is read as Python'sint()reads it (a float truncated, a bool 0 / 1), and repeated axes add up their shifts.axisintThe axis (NumPy's
axis=k; a negative value counts from the end).
Returns
- NDArray
Output array, with the same shape as
a:a's memory order along axes, C order for the flattened roll. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
NumPy's algorithm (NDArray's internal roll): empty_like plus one slice copy per combination of
the rolled axes' body and tail. One signature, NumPy's: the int / long shift overloads went with
API-parity batch 5, as both convert to the array shift. https://numpy.org/doc/stable/reference/generated/numpy.roll.html
Exceptions
- ArgumentNullException
aorshiftis null.- AxisError
An axis is out of range for
a's rank.- IncorrectShapeException
shiftdoes not broadcast against the axes (NumPy's ValueErrorshape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (3,) and arg 1 with shape (2,).).- ValueError
shiftand the axes broadcast to two dimensions or more ('shift' and 'axis' should be scalars or 1D sequences); a NaN shift; a text shift that is no int literal; a 0-dawith the empty tuple (NumPy'snot enough values to unpack (expected 2, got 0)); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- OverflowError
An infinite shift.
roll(NDArray, NDArray, int[])
roll(NDArray, NDArray, NDAxis?) with the axes as an int[]: the overload an
int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new
int[0] is ()).
public static NDArray roll(NDArray a, NDArray shift, int[] axis)
Parameters
aNDArrayInput array.
shiftNDArrayThe number of places by which elements are shifted: a C# integer (it converts to a 0-d array), or an array of one dimension (
new[] { 1, 2 }) broadcast against the axes - one shift for every axis, or one per axis. Each element is read as Python'sint()reads it (a float truncated, a bool 0 / 1), and repeated axes add up their shifts.axisint[]The axes as NumPy's tuple, or
nullfor None.
Returns
- NDArray
Output array, with the same shape as
a:a's memory order along axes, C order for the flattened roll. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
NumPy's algorithm (NDArray's internal roll): empty_like plus one slice copy per combination of
the rolled axes' body and tail. One signature, NumPy's: the int / long shift overloads went with
API-parity batch 5, as both convert to the array shift. https://numpy.org/doc/stable/reference/generated/numpy.roll.html
Exceptions
- ArgumentNullException
aorshiftis null.- AxisError
An axis is out of range for
a's rank.- IncorrectShapeException
shiftdoes not broadcast against the axes (NumPy's ValueErrorshape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (3,) and arg 1 with shape (2,).).- ValueError
shiftand the axes broadcast to two dimensions or more ('shift' and 'axis' should be scalars or 1D sequences); a NaN shift; a text shift that is no int literal; a 0-dawith the empty tuple (NumPy'snot enough values to unpack (expected 2, got 0)); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- OverflowError
An infinite shift.
roll(NDArray, NDArray, NDAxis?)
NumPy's np.roll(a, shift, axis=None): roll array elements along the given axis or axes. Elements that
roll beyond the last position are re-introduced at the first.
public static NDArray roll(NDArray a, NDArray shift, NDAxis? axis = null)
Parameters
aNDArrayInput array.
shiftNDArrayThe number of places by which elements are shifted: a C# integer (it converts to a 0-d array), or an array of one dimension (
new[] { 1, 2 }) broadcast against the axes - one shift for every axis, or one per axis. Each element is read as Python'sint()reads it (a float truncated, a bool 0 / 1), and repeated axes add up their shifts.axisNDAxis?The axis, or the axes (
(0, 1)), along which elements are shifted.null(the default) rolls the flattened array, after which the original shape is restored.
Returns
- NDArray
Output array, with the same shape as
a:a's memory order along axes, C order for the flattened roll. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
NumPy's algorithm (NDArray's internal roll): empty_like plus one slice copy per combination of
the rolled axes' body and tail. One signature, NumPy's: the int / long shift overloads went with
API-parity batch 5, as both convert to the array shift. https://numpy.org/doc/stable/reference/generated/numpy.roll.html
Exceptions
- ArgumentNullException
aorshiftis null.- AxisError
An axis is out of range for
a's rank.- IncorrectShapeException
shiftdoes not broadcast against the axes (NumPy's ValueErrorshape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (3,) and arg 1 with shape (2,).).- ValueError
shiftand the axes broadcast to two dimensions or more ('shift' and 'axis' should be scalars or 1D sequences); a NaN shift; a text shift that is no int literal; a 0-dawith the empty tuple (NumPy'snot enough values to unpack (expected 2, got 0)); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- OverflowError
An infinite shift.
rollaxis(NDArray, int, int)
Roll the specified axis backwards, until it lies in a given position.
This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11.
public static NDArray rollaxis(NDArray a, int axis, int start = 0)
Parameters
aNDArrayInput array.
axisintThe axis to roll backwards. The positions of the other axes do not change relative to one another.
startintThe axis is rolled until it lies before this position. The default, 0, results in a “complete” roll.
Returns
Remarks
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.).
roots(NDArray)
Return the roots of a polynomial with coefficients given in p.
If p has length n+1 the polynomial is
p[0]x**n + p[1]x(n-1) + ... + p[n].
public static NDArray roots(NDArray p)
Parameters
pNDArrayRank-1 array of polynomial coefficients.
Returns
- NDArray
The roots — the eigenvalues of the companion matrix, then one zero per trailing zero coefficient: real (float64, float32 for a float32 polynomial) when the coefficients are real and every eigenvalue is — NumPy 2.5's
_to_real_if_imag_zeroover the always complex eigvals — complex otherwise.
Remarks
Exceptions
- ValueError
pis not rank 1 afteratleast_1d(Input must be a rank-1 array.).- ValueError
A text coefficient between the first and last non-empty one that does not parse as a float (NumPy's
p.astype(float):could not convert string to float: np.str_('x')).- NotSupportedException
Two or more non-zero coefficients and no LAPACK backend installed.
- TypeError
A 0-d
p, or null (NumPy's None): NumPy'sarray_function_dispatchiterates what roots' dispatcher returns, the argument itself, and neither is iterable (dispatcher for array_function did not return an iterable), before roots' body runs.
rot90(NDArray, int, int[])
Rotate an array by 90 degrees in the plane specified by axes.
Rotation direction is from the first towards the second axis. This means that
for a 2-D array with the default k and axes
the rotation will be counterclockwise.
public static NDArray rot90(NDArray m, int k = 1, int[] axes = null)
Parameters
mNDArrayArray of two or more dimensions.
kintNumber of times the array is rotated by 90 degrees.
axesint[]The array is rotated in the plane defined by the axes. Axes must be different. Defaults to
(0, 1).
Returns
- NDArray
A rotated view of
m. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
Port of NumPy's numpy.rot90 (numpy/lib/_function_base_impl.py): a pure
composition of axis flips and a transpose, so the result is always a view that shares
memory with m (read-only when the source is, e.g. a broadcast view).
rot90(m, k=1, axes=(1, 0)) is the reverse of rot90(m, k=1, axes=(0, 1)).
https://numpy.org/doc/stable/reference/generated/numpy.rot90.html
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.).- ValueError
axesdoes not hold two axes ("len(axes) must be 2."), names one axis twice ("Axes must be different.", tested before the range), or is out of range ("Axes=(a, b) out of range for array of ndim=n.") — NumPy's own ValueErrors, not normalize_axis_index's AxisError.- NullReferenceException
mis null (its rank is read after the axes' length).
round(NDArray, int, NDArray)
Evenly round to the given number of decimals (NumPy's np.round, the NumPy 2.x name of the function;
around(NDArray, int, NDArray) is its documented alias).
public static NDArray round(NDArray a, int decimals = 0, NDArray @out = null)
Parameters
aNDArrayInput array (NumPy's keyword
a; a C# scalar converts to a 0-d array).decimalsintNumber of decimal places to round to (default 0). Half is rounded to even; a negative value rounds to positions left of the decimal point (
round([15, 25, -35], -1)is[20, 20, -40]).outNDArrayA location into which the result is stored; must be the correct shape, returned as-is. np.round is a FUNCTION, not a ufunc, so it takes
out=only, nowhere=/dtype=(probed 2.4.2).
Returns
- NDArray
An array of the same dtype as
a, containing the rounded values (an integer input is an identity copy fordecimals >= 0). Unlessoutwas specified, a new array is created (NumPy's read-only scalar for a 0-d input); with it,outitself is returned. The real and imaginary parts of complex numbers are rounded separately.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.round.html
NumPy's signature round(a, decimals=0, out=None). NumPy 2.0 removed np.round_ ("Use
np.round instead"), and NumSharp's np.round_ went with it on 2026-11-11, together with the
dtype parameter NumPy's round never had: np.round(a).astype(dtype) is the spelling of a
rounded result in another dtype.
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.).
row_stack(params NDArray[])
NumPy 2.4's row_stack(tup), vstack(params NDArray[]) under its other name: stacks the arrays
in sequence vertically (1-D arrays become rows) - concatenation along the first axis after atleast_2d.
public static NDArray row_stack(params NDArray[] tup)
Parameters
tupNDArray[]The arrays: the same shape along all but the first axis; 1-D arrays the same length.
Returns
- NDArray
The stacked array, at least 2-D (np.vstack's: a
numpy.matrixoperand gives a matrix, a chararray a plain array).
Remarks
https://numpy.org/doc/1.26/reference/generated/numpy.row_stack.html (NumPy 2.x's documentation has no page
for it). NumPy 2.5 removed np.row_stack (AttributeError: module 'numpy' has no attribute
'row_stack'); NumSharp keeps it on purpose, with no warning and no [Obsolete], so code written
against NumPy 2.4 or earlier compiles and runs unchanged. API-parity batch 12.
Exceptions
- ArgumentNullException
tupis null.- ValueError
tupis empty (need at least one array to concatenate); arrays whose other axes differ; anumpy.matrixresult of more than two long axes.
row_stack(NDArray[], DType, string)
NumPy 2.4's row_stack(tup, *, dtype=None, casting='same_kind'),
vstack(NDArray[], DType, string) under its other name: the arrays stacked vertically with
np.concatenate's dtype / casting.
public static NDArray row_stack(NDArray[] tup, DType dtype = null, string casting = "same_kind")
Parameters
tupNDArray[]The arrays (NumPy's sequence).
dtypeDTypeThe result dtype handed to np.concatenate, or null for the arrays' promoted dtype.
castingstringThe casting rule handed to np.concatenate (
'no','equiv','safe','same_kind'or'unsafe').
Returns
- NDArray
The stacked array, at least 2-D.
Remarks
NumPy 2.5 removed np.row_stack; NumSharp keeps it on purpose, with no warning and no
[Obsolete] (see row_stack(params NDArray[])). API-parity batch 12.
Exceptions
- ArgumentNullException
tupis null.- ValueError
tupis empty; anumpy.matrixresult of more than two long axes.- InvalidCastException
An array that does not cast to
dtypeundercasting(np.vstack's refusal with NumPy's text; NumPy's type is TypeError).
row_stack(NDListArray[])
NumPy 2.4's row_stack(tup) over object arrays of Python lists (NDListArray):
vstack(NDListArray[]) under its other name, the lists shared as NumPy's object pointers are.
public static NDListArray row_stack(NDListArray[] tup)
Parameters
tupNDListArray[]The list arrays (NumPy's sequence).
Returns
- NDListArray
A new object array of the lists, at least 2-D.
Remarks
NumPy 2.5 removed np.row_stack; NumSharp keeps it on purpose, with no warning and no
[Obsolete] (see row_stack(params NDArray[])). A sequence parameter, as vstack's (a second
params form would make np.row_stack() ambiguous). API-parity batch 12 (the owner: "support that
too").
Exceptions
- ArgumentNullException
tupor one of its arrays is null.- ValueError
No array; arrays whose other axes differ.
- NotSupportedException
A bytes list beside str lists.
- ObjectDisposedException
One of the arrays was disposed.
save(NDArray, bool)
Encode an array as .npy and return the bytes.
public static byte[] save(NDArray arr, bool allow_pickle = true)
Parameters
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
save(Stream, NDArray, bool)
Write an array in .npy format to an open stream.
public static void save(Stream file, NDArray arr, bool allow_pickle = true)
Parameters
fileStreamAn open, writable stream. Written from its current position and left open, so successive calls append — several arrays can share one file and be read back in order by load_npy(Stream, bool, long).
arrNDArrayThe array to save.
allow_pickleboolWhether a pickle may be written; see save(string, NDArray, bool).
Remarks
Exceptions
- ValueError
A
StringDTypearray withallow_picklefalse (after its header).
save(string, NDArray, bool)
Save an array to a .npy binary file.
public static void save(string file, NDArray arr, bool allow_pickle = true)
Parameters
filestringTarget path.
.npyis appended if the name does not already end with it, matching NumPy.arrNDArrayThe array to save. Any layout; a Fortran-contiguous array is stored as such.
allow_pickleboolWhether a pickle may be written (default true, as in NumPy). Only a NEP 55
StringDTypearray needs one: NumPy writes it as a pickle behind a'|O'header, and withfalseraises after the header.
Remarks
The file is byte-for-byte what NumPy 2.4.2's own np.save writes for the same array — a
StringDType array included: its pickle is NumPy's, opcode for opcode and frame for frame, so NumPy
loads it with allow_pickle=True and NumSharp loads NumPy's.
https://numpy.org/doc/stable/reference/generated/numpy.save.html
Exceptions
- NotSupportedException
The dtype has no NumPy equivalent — Decimal — or a
StringDTypemissing-data object has no pickle form NumSharp writes.- ValueError
Object arrays cannot be saved when allow_pickle=False(aStringDTypearray withallow_picklefalse; the file then holds the header only, as NumPy's does).
save(string, Array, bool)
Save an array to a .npy file, converting arr with
asanyarray(in object, DType, char?, string, bool?) first.
public static void save(string file, Array arr, bool allow_pickle = true)
Parameters
Remarks
save_version(Stream, NDArray, FormatVersion?, bool)
Write an array in .npy format using an explicit format version — NumPy's
numpy.lib.format.write_array.
public static void save_version(Stream file, NDArray arr, NpyFormat.FormatVersion? version, bool allow_pickle = true)
Parameters
fileStreamAn open, writable stream.
arrNDArrayThe array to save.
versionNpyFormat.FormatVersion?(1,0), (2,0), (3,0), or null to use the oldest that can hold the header. Version 2.0 widens the header-length field to 4 bytes; 3.0 also switches the header to UTF-8.
allow_pickleboolWhether a pickle may be written; see save(string, NDArray, bool).
Exceptions
- FormatException
The version is not one of (1,0), (2,0) or (3,0).
- ValueError
A
StringDTypearray withallow_picklefalse (after its header).
savetxt(Stream, NDArray, string, string, string, string, string, string, string)
Write a 1-D or 2-D array as text to an open byte stream (NumPy's binary file object). The stream is written
from its current position and left open (the caller owns it), and rows are separated by
newline verbatim — no platform newline translation, matching NumPy's file-handle path.
public static void savetxt(Stream stream, NDArray X, string fmt = "%.18e", string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
streamStreamThe byte stream.
XNDArrayThe 1-D or 2-D array to save.
fmtstringA single
%-format spec, or a multi-%row format.delimiterstringString separating columns.
newlinestringString separating rows.
headerstringString written first, each line prefixed by
comments.footerstringString written last, each line prefixed by
comments.commentsstringString prepended to the header / footer lines.
encodingstringThe encoding every write is encoded with, on its own (
str.encode: the BOM forms write a BOM before EVERY write, as NumPy'sWriteWrapdoes); null or empty is Latin-1, NumPy's default for a byte stream (WriteWrap(fh, encoding or 'latin1')), so a character pastU+00FFraises UnicodeEncodeError ('latin-1' codec can't encode character '\u4e2d' in position 0: ordinal not in range(256)) with the writes before it in the stream. An unknown or non-text name ("bytes"included) raises LookupError at the first write, a codec NumSharp does not implement NotSupportedException.
Remarks
Exceptions
- ArgumentNullException
streamis null.- ValueError
A 0-d or more than 2-d array, a format with the wrong number of specs, or a null
fmt(invalid fmt: None).- AttributeError
A null
delimiterwhere NumPy joins the specs with it.- TypeError
An element its spec cannot convert (
Mismatch between array dtype …), and the null newline / header / footer / comments errors of the file-name overload, at the same points.- UnicodeEncodeError
A write the encoding cannot encode.
- LookupError
An unknown or non-text encoding, at the first write.
- NotSupportedException
A codec NumSharp does not implement, at the first write.
savetxt(Stream, NDArray, string[], string, string, string, string, string, string)
Write a 1-D or 2-D array as text to an open byte stream, with one %-format spec per column.
public static void savetxt(Stream stream, NDArray X, string[] fmt, string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
streamStreamThe byte stream.
XNDArrayThe 1-D or 2-D array to save.
fmtstring[]One format spec per column (else AttributeError).
delimiterstringString separating columns.
newlinestringString separating rows.
headerstringString written first.
footerstringString written last.
commentsstringString prepended to the header / footer lines.
encodingstringAs for the single-spec overload (null is Latin-1).
Remarks
Exceptions
- ArgumentNullException
streamis null.- AttributeError
A spec list of the wrong length, or a null
delimiter.- TypeError
A null entry of
fmt, an element its spec cannot convert, and the null newline / header / footer / comments errors of the file-name overload.- ValueError
A 0-d or more than 2-d array, or a null
fmt.- UnicodeEncodeError
A write the encoding cannot encode.
- LookupError
An unknown or non-text encoding, at the first write.
- NotSupportedException
A codec NumSharp does not implement, at the first write.
savetxt(TextWriter, NDArray, string, string, string, string, string, string, string)
Write a 1-D or 2-D array as text to an open TextWriter (NumPy's text file object,
io.StringIO). The writer is written from its current position, flushed and left open (the caller owns
it); rows are separated by newline verbatim, with no platform newline translation.
public static void savetxt(TextWriter writer, NDArray X, string fmt = "%.18e", string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
writerTextWriterThe text target.
XNDArrayThe 1-D or 2-D array to save (a 1-D array is one value per line).
fmtstringA single
%-format spec (repeated for every column, joined bydelimiter), or a multi-%row format (delimiterthen unused).delimiterstringString separating columns.
newlinestringString separating rows.
headerstringString written first, each line prefixed by
comments.footerstringString written last, each line prefixed by
comments.commentsstringString prepended to the header / footer lines.
encodingstringAccepted for NumPy's signature and IGNORED, as NumPy ignores it for a text target (its
WriteWrapencodes only for a stream that refusesstr): any name, an unknown one included, writes the same text.
Remarks
What reached the writer before an error stays written (NumPy writes each row as it formats it), and the writer is flushed in every case. https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html
Exceptions
- ArgumentNullException
writeris null.- ValueError
A 0-d or more than 2-d array, a format with the wrong number of specs, or a null
fmt(invalid fmt: None).- AttributeError
A null
delimiterwhere NumPy joins the specs with it.- TypeError
An element its spec cannot convert (
Mismatch between array dtype …), and the null newline / header / footer / comments errors of the file-name overload, at the same points.
savetxt(TextWriter, NDArray, string[], string, string, string, string, string, string)
Write a 1-D or 2-D array to a TextWriter, with one %-format spec per column.
public static void savetxt(TextWriter writer, NDArray X, string[] fmt, string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
writerTextWriterThe text target.
XNDArrayThe 1-D or 2-D array to save.
fmtstring[]One format spec per column (else AttributeError), joined by
delimiter.delimiterstringString separating columns.
newlinestringString separating rows.
headerstringString written first.
footerstringString written last.
commentsstringString prepended to the header / footer lines.
encodingstringAccepted for NumPy's signature and ignored, as for the single-spec overload.
Remarks
Exceptions
- ArgumentNullException
writeris null.- AttributeError
A spec list of the wrong length, or a null
delimiter.- TypeError
A null entry of
fmt, an element its spec cannot convert, and the null newline / header / footer / comments errors of the file-name overload.- ValueError
A 0-d or more than 2-d array, or a null
fmt.
savetxt(string, NDArray, string, string, string, string, string, string, string)
Save a 1-D or 2-D array to a text file.
public static void savetxt(string fname, NDArray X, string fmt = "%.18e", string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
fnamestringTarget path. It is created (or truncated) first, as NumPy's
open(fname, 'wt').close(); a name whose extension is exactly.gzis then written gzip-compressed, as NumPy does (.GZis plain text, as in NumPy). NumPy writes.bz2/.xz/.lzmanames compressed too; .NET has no compressor for them, so NumSharp refuses those names before touching the file.XNDArrayThe 1-D or 2-D array to save (a 0-D or ≥3-D array raises ValueError).
fmtstringA single
%-format spec (%.18e, replicated once per column), or a multi-%format string applied to the whole row (in which casedelimiteris ignored). For a complexXa single spec becomes' (%s+%sj)'per column.delimiterstringString separating columns.
newlinestringString separating rows.
headerstringString written at the beginning of the file, each line prefixed by
comments.footerstringString written at the end of the file, each line prefixed by
comments.commentsstringString prepended to
header/footerlines.encodingstringThe file's encoding: any name Python's
codecs.lookupresolves for UTF-8 (utf-8-sigtoo), UTF-16 and UTF-32 (the BOM forms write their BOM once, at the start of the file), Latin-1, ASCII and the single-byte code pages (cp1252,iso8859_15, …). Null (and"locale") is UTF-8 without a BOM — NumPy's locale encoding on Linux and macOS (Windows NumPy uses the ANSI code page). Every write is encoded strictly, as Python's TextIOWrapper encodes it after its newline translation: a header, row or footer the encoding cannot hold raises UnicodeEncodeError (its position counting the translated write), with the writes before it in the file. NumPy's"bytes"is no encoding here (LookupErrorunknown encoding: bytes), nor is the empty name.
Remarks
Byte-for-byte what NumPy 2.4.2's own np.savetxt writes for the same array — including
the Python text-mode newline translation on a filename target: every \n is written as
the platform line separator (\r\n on Windows), so the file matches NumPy on the same
platform. The savetxt(Stream, NDArray, string, string, string, string, string, string, string)
and TextWriter overloads write \n verbatim, matching NumPy's file-handle path.
https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html
Exceptions
- ValueError
A 0-d or more than 2-d array, a format with the wrong number of specs, or a null
fmt(Python's None:invalid fmt: None).- AttributeError
A null
delimiterwhere NumPy joins the specs with it (one spec repeated per column:'NoneType' object has no attribute 'join'; a multi-%format never reads it).- TypeError
An element its spec cannot convert, or a null
newlineonce a row is built (Mismatch between array dtype …; for a complex array the plaincan only concatenate str (not "NoneType") to str); a nullheader/footer(object of type 'NoneType' has no len()), or a nullcomments/newlinewhile a non-empty header or footer is built. A footer's error comes after every row was written, as in NumPy.
savetxt(string, NDArray, string[], string, string, string, string, string, string)
Save a 1-D or 2-D array to a text file, with one %-format spec per column.
public static void savetxt(string fname, NDArray X, string[] fmt, string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
fnamestringXNDArrayfmtstring[]One format spec per column. Its length must equal the number of columns, else AttributeError is raised. For a complex array each entry must itself contain both the real and imaginary specs (e.g.
"%.3e%+.3ej").delimiterstringnewlinestringheaderstringfooterstringcommentsstringencodingstring
Remarks
Exceptions
- AttributeError
A spec list of the wrong length, or a null
delimiter(Python's None has nojoin).- TypeError
A null entry of
fmt(sequence item 1: expected str instance, NoneType found), an element its spec cannot convert, and the null header / footer / comments / newline errors of the single-spec overload.- ValueError
A 0-d or more than 2-d array, or a null
fmt(invalid fmt: None).
savez(params NDArray[])
Encode an uncompressed .npz archive of arr_0… arrays and return the bytes.
public static byte[] savez(params NDArray[] args)
Parameters
argsNDArray[]
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
savez(IDictionary<string, NDArray>)
Encode an uncompressed .npz archive of named arrays and return the bytes.
public static byte[] savez(IDictionary<string, NDArray> kwds)
Parameters
kwdsIDictionary<string, NDArray>
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
savez(Stream, params NDArray[])
Write an uncompressed .npz archive to an open stream.
public static void savez(Stream file, params NDArray[] args)
Parameters
Remarks
savez(Stream, NDArray[], IDictionary<string, NDArray>, bool)
Write an uncompressed .npz archive of positional and named arrays to an open stream.
public static void savez(Stream file, NDArray[] args, IDictionary<string, NDArray> kwds, bool allow_pickle = true)
Parameters
fileStreamargsNDArray[]kwdsIDictionary<string, NDArray>allow_pickleboolWhether a member may be pickled — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).
Remarks
Exceptions
- ValueError
A
StringDTypemember withallow_picklefalse.
savez(Stream, IDictionary<string, NDArray>)
Write an uncompressed .npz archive of named arrays to an open stream.
public static void savez(Stream file, IDictionary<string, NDArray> kwds)
Parameters
fileStreamkwdsIDictionary<string, NDArray>
Remarks
savez(string, params NDArray[])
Save several arrays into an uncompressed .npz archive, named arr_0,
arr_1, … in order.
public static void savez(string file, params NDArray[] args)
Parameters
filestringTarget path.
.npzis appended if not already present.argsNDArray[]The arrays, in order.
Remarks
savez(string, NDArray[], IDictionary<string, NDArray>, bool)
Save positional and named arrays into an uncompressed .npz archive.
public static void savez(string file, NDArray[] args, IDictionary<string, NDArray> kwds, bool allow_pickle = true)
Parameters
filestringTarget path.
.npzis appended if not already present.argsNDArray[]Positional arrays, stored as
arr_0,arr_1, …kwdsIDictionary<string, NDArray>Named arrays.
allow_pickleboolWhether a member may be written as a pickle (NumPy's
savez(file, *args, allow_pickle=True, **kwds)): a NEP 55StringDTypemember needs one, and withfalseraises after its header, leaving the archive with the members written before it (NumPy closes its zip file the same way).
Remarks
Exceptions
- ArgumentException
A name in
kwdscollides with a generatedarr_N.- ValueError
A
StringDTypemember withallow_picklefalse.
savez(string, IDictionary<string, NDArray>)
Save named arrays into an uncompressed .npz archive — NumPy's keyword form,
np.savez(file, weights=w, biases=b).
public static void savez(string file, IDictionary<string, NDArray> kwds)
Parameters
filestringTarget path.
.npzis appended if not already present.kwdsIDictionary<string, NDArray>Name/array pairs. Each becomes
<name>.npyin the archive.
Remarks
savez_compressed(params NDArray[])
Encode a compressed .npz archive of arr_0… arrays and return the bytes.
public static byte[] savez_compressed(params NDArray[] args)
Parameters
argsNDArray[]
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
savez_compressed(IDictionary<string, NDArray>)
Encode a compressed .npz archive of named arrays and return the bytes.
public static byte[] savez_compressed(IDictionary<string, NDArray> kwds)
Parameters
kwdsIDictionary<string, NDArray>
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
savez_compressed(Stream, params NDArray[])
Write a compressed .npz archive to an open stream.
public static void savez_compressed(Stream file, params NDArray[] args)
Parameters
Remarks
savez_compressed(Stream, NDArray[], IDictionary<string, NDArray>, bool)
Write a compressed .npz archive of positional and named arrays to an open stream.
public static void savez_compressed(Stream file, NDArray[] args, IDictionary<string, NDArray> kwds, bool allow_pickle = true)
Parameters
fileStreamargsNDArray[]kwdsIDictionary<string, NDArray>allow_pickleboolWhether a member may be pickled — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).
Remarks
Exceptions
- ValueError
A
StringDTypemember withallow_picklefalse.
savez_compressed(Stream, IDictionary<string, NDArray>)
Write a compressed .npz archive of named arrays to an open stream.
public static void savez_compressed(Stream file, IDictionary<string, NDArray> kwds)
Parameters
fileStreamkwdsIDictionary<string, NDArray>
Remarks
savez_compressed(string, params NDArray[])
Save several arrays into a compressed .npz archive, named arr_0,
arr_1, … in order.
public static void savez_compressed(string file, params NDArray[] args)
Parameters
filestringTarget path.
.npzis appended if not already present.argsNDArray[]The arrays, in order.
Remarks
savez_compressed(string, NDArray[], IDictionary<string, NDArray>, bool)
Save positional and named arrays into a compressed .npz archive.
public static void savez_compressed(string file, NDArray[] args, IDictionary<string, NDArray> kwds, bool allow_pickle = true)
Parameters
filestringargsNDArray[]kwdsIDictionary<string, NDArray>allow_pickleboolWhether a member may be pickled — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).
Remarks
Exceptions
- ValueError
A
StringDTypemember withallow_picklefalse.
savez_compressed(string, IDictionary<string, NDArray>)
Save named arrays into a compressed .npz archive.
public static void savez_compressed(string file, IDictionary<string, NDArray> kwds)
Parameters
filestringkwdsIDictionary<string, NDArray>
Remarks
sctype2char(NPTypeCode)
Return the string representation of a scalar dtype — NumPy 1.x's np.sctype2char(sctype). Kept on
purpose, so code written against NumPy 1.x compiles and runs unchanged, although NumPy 2.0 removed it
(AttributeError: ). New code reads char.np.sctype2char was removed in the NumPy 2.0 release. Use np.dtype(obj).char
instead.
public static char sctype2char(NPTypeCode sctype)
Parameters
sctypeNPTypeCodeA scalar type; a DType such as
np.int32converts implicitly.
Returns
- char
The character code for the type.
Examples
np.sctype2char(NPTypeCode.Int32) // 'i'
np.sctype2char(NPTypeCode.Double) // 'd'
Remarks
https://numpy.org/doc/1.26/reference/generated/numpy.sctype2char.html
The table is fixed and PORTABLE: each letter maps back to the same dtype through np.dtype(letter) on
every host ('i' int32, 'q' int64). NumPy 1.x answered np.dtype(sctype).char, which follows
the host's C long: int32 is 'l' on Windows and int64 is 'l' on Linux and macOS, and
char answers that way. Three answers have no NumPy counterpart: Char
is 'H' (its uint16 storage), Decimal is 'd', and a code without a dtype
(Empty) is '?' where NumPy 1.x raised ValueError: unrecognized type.
Character codes (NumPy): '?' - boolean 'b' - int8 (signed byte) 'B' - uint8 (unsigned byte) 'h' - int16 (short) 'H' - uint16 (unsigned short) 'i' - int32 'I' - uint32 'q' - int64 'Q' - uint64 'e' - float16 (Half) 'f' - float32 'd' - float64 'D' - complex128
searchsorted(NDArray, NDArray, string, NDArray)
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted array a such that, if the corresponding elements
in v were inserted before the indices, the order of a would be preserved.
public static NDArray searchsorted(NDArray a, NDArray v, string side = "left", NDArray sorter = null)
Parameters
aNDArrayInput 1-D array. Must be sorted ascending unless
sorteris provided.vNDArrayValues to insert into
a. May be a scalar or any shape.sidestringIf "left" (default), the index of the first suitable location is returned. If "right", the last such index.
sorterNDArrayOptional indices that sort
ainto ascending order (typicallyargsort(a)).
Returns
- NDArray
Array of insertion points with the same shape as
v, or a scalar ifvis a scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html
Text in a or v is searched as NumPy searches it: both converted to
their common string dtype (a number formatted, bytes decoded), then NumPy's generic binary search step for step
— its monotonic carry and its sorter checks included, so an unsorted haystack gives NumPy's answer too
(NumSharp.Backends.Sorting.TextSearch).
The whole call is the engine's (SearchSorted(NDArray, NDArray, string, NDArray)); this function's woven subclass path hands a subclass operand in as its plain view.
Exceptions
- ArgumentException
- ValueError
See searchsorted(NDArray, int, string, NDArray); or a StringDType comparison that touched a None-like NA.
- TypeError
See searchsorted(NDArray, int, string, NDArray); or a U array converted to StringDType (NumPy's 'safe' cast refusal).
- UnicodeDecodeError
A text search converts bytes that are not ASCII to the common
Udtype.- DTypePromotionError
Text with an operand that has no common dtype with it.
- NullReferenceException
aorvis null.
searchsorted(NDArray, double, string, NDArray)
Find index where a scalar should be inserted to maintain order.
public static long searchsorted(NDArray a, double v, string side = "left", NDArray sorter = null)
Parameters
aNDArrayInput 1-D array. Must be sorted ascending unless
sorteris provided.vdoubleValue to insert into
a.sidestringIf "left" (default), index of the first suitable location is returned. If "right", the last such index.
sorterNDArrayOptional indices that sort
ainto ascending order (typicallyargsort(a)).
Returns
- long
Scalar index for insertion point.
Remarks
The whole call is the engine's (SearchSorted(NDArray, double, string, NDArray)); this function's woven subclass path hands a subclass operand in as its plain view.
Exceptions
- ArgumentException
- ValueError
- TypeError
See searchsorted(NDArray, int, string, NDArray) (the object path's text names
'float').- NullReferenceException
ais null.
searchsorted(NDArray, int, string, NDArray)
Find index where a scalar should be inserted to maintain order.
public static long searchsorted(NDArray a, int v, string side = "left", NDArray sorter = null)
Parameters
aNDArrayInput 1-D array. Must be sorted ascending unless
sorteris provided.vintValue to insert into
a.sidestringIf "left" (default), index of the first suitable location is returned. If "right", the last such index.
sorterNDArrayOptional indices that sort
ainto ascending order (typicallyargsort(a)).
Returns
- long
Scalar index for insertion point.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html
A text a is searched as text: the key is formatted into the common string dtype, as
NumPy converts it.
The whole call is the engine's (SearchSorted(NDArray, int, string, NDArray)); this function's woven subclass path hands a subclass operand in as its plain view.
Exceptions
- ArgumentException
sideis not"left"/"right"(NumPy's two ValueError texts).- ValueError
ais not 1-D, a sorter of uint64, a sorter whose size differs froma's, or a sorter index outsideathat the search reaches.- TypeError
A sorter that is not 1-D (
could not parse sorter argument) or not integer (sorter must only contain integers), or a StringDTypeawhose first comparison with the key Python refuses ('<' not supported between instances of 'str' and 'int').- NullReferenceException
ais null.
select(NDArray[], object[], object)
Return an array drawn from elements in choicelist, depending on
condlist. The output at position m is the m-th element
of the array in choicelist where the m-th element of the
corresponding array in condlist is true. When multiple
conditions are satisfied, the FIRST one encountered in condlist wins;
positions where every condition is false take default.
public static NDArray select(NDArray[] condlist, object[] choicelist, object @default = null)
Parameters
condlistNDArray[]The conditions that determine which array in
choicelisteach output element is taken from. Must be boolean arrays and the same length aschoicelist. All conditions are broadcast against each other.choicelistobject[]The arrays the output elements are drawn from. Each entry is either an NDArray (strong dtype) or a boxed C# scalar. As in NumPy (NEP50), an
int/float/double/Complex literal is a weak scalar that adopts the other operands' dtype, whilebool,char, Half,decimal, arrays and every NDArray are strong. An NDArray[] binds here directly via array covariance; scalar choices need an explicitnew object[] { … }. All choices ANDdefaultare broadcast against each other.defaultobjectThe value inserted where all conditions are
false.null(the C# default) is NumPy'sdefault=0— a weak python int. Accepts a scalar or an NDArray (which participates in the choice broadcast shape).
Returns
- NDArray
A fresh C-contiguous array whose dtype is result_type(params object[]) of every choice and the default (NEP50), and whose shape is the broadcast of the conditions against the choices.
Remarks
Port of NumPy 2.x numpy.select (numpy/lib/_function_base_impl.py): fill the
result with the default, then copyto(NDArray, NDArray, string, NDArray) each choice onto it under its
condition mask in REVERSE order so the first matching condition takes precedence — the
same composition NumPy uses, so every masked write rides NumSharp's SIMD masked-cast
kernel. The contiguous, no-cast, full-size-array-choice case (the one NumPy leaves
memory-bound, since its (n+1) masked copytos each re-read and re-write the whole result)
is instead served by a fused single-pass IL kernel — see
GetSelectKernel(NPTypeCode, int, bool).
https://numpy.org/doc/stable/reference/generated/numpy.select.html
Exceptions
- ValueError
condlistandchoicelistdiffer in length, orcondlistis empty.- TypeError
A condition is not a boolean array.
- IncorrectShapeException
The conditions, the choices, or the two groups against each other cannot be broadcast (NumSharp's house form of NumPy's broadcast
ValueError).
set_printoptions(int?, int?, int?, int?, bool?, string, string, char?, string)
Set printing options (NumPy's np.set_printoptions). These options determine the
way floating point numbers, arrays and other NumPy objects are displayed.
public static void set_printoptions(int? precision = null, int? threshold = null, int? edgeitems = null, int? linewidth = null, bool? suppress = null, string nanstr = null, string infstr = null, char? sign = null, string floatmode = null)
Parameters
precisionint?thresholdint?edgeitemsint?linewidthint?suppressbool?nanstrstringinfstrstringsignchar?floatmodestring
Remarks
setbufsize(long)
Set the size of the buffer used in ufuncs (the default buffer size for buffered NDIter/ufunc iteration in the caller's flow) and return the previous size.
public static long setbufsize(long size)
Parameters
sizelongNew buffer size in elements. Must be non-negative, at most 10,000,000, at least 5, and a multiple of 16 — so the smallest accepted value is 16.
Returns
- long
The buffer size in effect before this call.
Remarks
Mirrors numpy.setbufsize(size). The setting is context-local (NumPy 2.x's extobj
ContextVar, with Python 3.12's thread rule): it persists in the caller's flow until changed again,
the asynchronous work the flow starts afterwards (Task.Run, the thread pool, await
continuations) inherits it, and it never reaches a thread already running nor a dedicated thread, which
starts at the default. Buffering is a performance/chunking knob: results are
unchanged EXCEPT where NumPy's own are — a reduction that casts through the buffer, or the flat
np.sum / np.mean of several short runs (see getbufsize()), pairwise-sums per
chunk, so its last bits follow the size, as NumPy's do.
Unlike NumPy — which accepts any Python int and raises TypeError for a
float/bool and OverflowError for a value beyond the platform integer —
C#'s type system already rejects a non-integer argument at compile time, so only the
value-range ValueErrors remain reachable.
Exceptions
- ValueError
If
sizeis invalid. The message and the order in which the checks run match NumPy verbatim: negative →"buffer size must be non-negative"; greater than 10,000,000 →"Buffer size, {size}, is too big"; less than 5 →"Buffer size, {size}, is too small"; not a multiple of 16 →"Buffer size, {size}, is not a multiple of 16".
setdiff1d(NDArray, NDArray, bool)
Find the set difference of two arrays.
Return the unique values in ar1 that are not in ar2.
public static NDArray setdiff1d(NDArray ar1, NDArray ar2, bool assume_unique = false)
Parameters
ar1NDArrayInput array.
ar2NDArrayInput comparison array.
assume_uniqueboolIf True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
Returns
- NDArray
1-D array of values in
ar1that are not inar2. Sorted whenassume_uniqueis False. Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
Exceptions
- UnicodeDecodeError
The membership test's sort path decodes
Stext holding a byte that is not ASCII (seenp.isin).- ValueError
A NEP 55
StringDTypearray whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy'sCannot compare null that is not a nan-like value.- ArgumentNullException
ar1is null.
setxor1d(NDArray, NDArray, bool)
Find the set exclusive-or of two arrays.
Return the sorted, unique values that are in only one (not both) of the input arrays.
public static NDArray setxor1d(NDArray ar1, NDArray ar2, bool assume_unique = false)
Parameters
ar1NDArrayInput array.
ar2NDArrayInput array.
assume_uniqueboolIf True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
Returns
- NDArray
Sorted 1-D array of unique values that are in only one of the input arrays.
Remarks
Exceptions
- UnicodeDecodeError
A
Uresult overStext holding a non-ASCII byte.- DTypePromotionError
A
StringDTypeoperand beside a class the concatenation finds no common DType with (a number, bool,Sbytes): NumPy's verbatim promotion text.- ValueError
A NEP 55
StringDTypearray whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy'sCannot compare null that is not a nan-like value.- ArgumentNullException
ar1is null.
shape(NDArray)
Return the shape of an array (NumPy's np.shape, the module function beside the
shape property).
public static long[] shape(NDArray a)
Parameters
aNDArrayInput array (NumPy's keyword
a). A C# scalar converts to a 0-d array and a C# array to an array of its shape, sonp.shape(5)is empty as NumPy's().
Returns
- long[]
The lengths of
a's dimensions, NumPy's tuple as a freshlong[](the same copy shape returns, so writing into it never reshapes the array); empty for a 0-d input.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.shape.html
NumPy's statements: a.shape, or asarray(a).shape for an object without the attribute (the
implicit conversions to NDArray are that asarray here). The return type follows
shape and numpy.ma's np.ma.shape. No collision with the shape members of
NDArray or of the types nested in np (np.broadcast.shape, ...): those are members
of other classes, and inside a nested type its own member wins the name lookup.
Exceptions
- ArgumentNullException
ais null (NumSharp has no object dtype for NumPy'snp.shape(None), which is(); size(NDArray, NDAxis?) refuses null the same way).
shares_memory(NDArray, NDArray, long)
Determine whether two arrays share ANY byte of memory — the EXACT answer, not a bound.
public static bool shares_memory(NDArray a, NDArray b, long max_work = -1)
Parameters
aNDArrayFirst array. Any layout is accepted (contiguous, sliced, strided, transposed, negative-stride, or broadcast view). A
nullreference has no memory and shares nothing.bNDArraySecond array, under the same rules as
a.max_worklongEffort cap on the overlap solver, mirroring NumPy's
max_work:-1(the default) and-2solve the collision EXACTLY however long it takes;0checks only the byte bounds (so an undecided result becomes TooHardError here); a positive value examines at most that many candidate solutions before giving up. Values below-2are rejected.
Returns
- bool
trueonly when at least one addressable byte is common to both arrays.
Remarks
This is the STRICT counterpart of may_share_memory(NDArray, NDArray, long): two
interleaved views of one buffer (e.g. base[::2] and base[1::2]) have overlapping
byte bounds yet no common byte, so shares_memory returns false there while
may_share_memory returns true. Because the general problem is NP-hard, an
adversarial pair with a small default budget can exhaust the work cap and raise
TooHardError rather than silently guessing — pass a larger (or the default
unlimited) max_work to force a definite answer. Mirrors
numpy.shares_memory(a, b, /, max_work=-1) (NumPy 2.4.2), which raises on the undecided
and overflow outcomes.
https://numpy.org/doc/stable/reference/generated/numpy.shares_memory.html
Exceptions
- ValueError
max_workis less than-2.- TooHardError
The solver hit the
max_workcandidate cap (or was restricted to a bounds check viamax_work: 0) before it could decide exactly.- OverflowError
The solver's integer arithmetic overflowed while computing overlap.
- RuntimeError
The solver reported an internal error (does not occur for valid inputs).
sign(NDArray, NDArray, NDArray, DType)
Returns an element-wise indication of the sign of a number.
The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0. nan is returned for nan inputs.
public static NDArray sign(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput values.
outNDArrayA location into which the result is stored (NumPy ufunc out=);
nullallocates the result.whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeThe loop dtype (NumPy's
dtype=):xmust cast to it undersame_kind, so a float input with an integer dtype is refused.nullkeeps the input's dtype (the sign of an integer array is an integer array).
Returns
- NDArray
The sign of x, in the input's dtype unless
dtypenames another. This is a scalar if x is a scalar.
Remarks
Exceptions
- TypeError
A
dtypethe input cannot reach undersame_kind(Cannot cast ufunc 'sign' input from dtype('float64') to dtype('int64') with casting rule 'same_kind'; NumPy raisesUFuncTypeError).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
signbit(NDArray, NDArray, NDArray, DType)
Return element-wise True where the sign bit is set (negative numbers, and — for floats —
-0.0 and a negative NaN). Mirrors NumPy's ufunc signature:
signbit(x, /, out=None, *, where=True, dtype=None). A plain call returns a bool-dtype
array (the instance is an NDArray<TDType> of bool).
public static NDArray signbit(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array. Complex is unsupported (raises TypeError).
outNDArrayA location into which the result is stored; any numeric dtype (bool casts same_kind to all, True→1); returned as-is.
whereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.
Returns
- NDArray
A boolean array (or
out), True wherex's sign bit is set.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.signbit.html
This is NOT x < 0: it tests the raw sign bit, so on floats -0.0 → True and a
negative NaN → True while +0.0/+inf/positive NaN → False. Signed integers follow
x < 0 (their two's-complement MSB IS the sign bit); unsigned integers and bool are
always False; float16/float32/float64 test the IEEE sign bit. It is the primitive
isposinf(NDArray, NDArray)/isneginf(NDArray, NDArray) are defined on (isinf(x) & ~signbit(x)
/ isinf(x) & signbit(x)).
Exceptions
- TypeError
xis complex — signbit has no complex loop (NumPy raises the same, its signbit is ambiguous on complex).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
sin(NDArray, NDArray, NDArray, DType)
Trigonometric sine, element-wise.
Mirrors NumPy's ufunc signature: sin(x, /, out=None, *, where=True, dtype=None).
public static NDArray sin(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngle, in radians (2 \pi rad equals 360 degrees).
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
The sine of each element of x. This is a scalar if x is a scalar.
Remarks
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.).
sinc(NDArray)
Return the normalized sinc function, element-wise: sin(pix) / (pix), with the
removable singularity at every zero of pi*x filled by its limit value 1.
public static NDArray sinc(NDArray x)
Parameters
xNDArrayInput values (any shape, any memory layout — C/F/strided/broadcast/negative-stride views are all read through their own strides). Integer and boolean inputs are promoted to float64 before evaluation.
Returns
- NDArray
sinc(x), same shape asx, in the promoted dtype described above. A scalar (0-d) input yields a 0-d result; an empty input yields an empty float64 array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.sinc.html
Note the pi normalization: this is the signal-processing sinc. For the
mathematical sin(x)/x, call np.sinc(x / np.pi).
RESULT DTYPE follows pi * x (a NEP 50 weak-float promotion), NOT np.sin's tier:
bool and EVERY integer width (and Char) → float64; float16/float32/
float64 are preserved; complex → complex128; Decimal → decimal
(a NumSharp extension — NumPy has no decimal). Bit-identical to NumPy 2.4.2 for every
real dtype (validated exhaustively on all 65,536 float16 inputs and over 1,000,000
adversarial float32 and float64 inputs); complex128 is accurate to ≤~2.5 ULP RELATIVE and
np.allclose-passing but its per-component bits are not reproducible — see the file header.
A Decimal input outside the double bridge's domain (e.g. a magnitude whose pi*x
overflows decimal) throws OverflowException, exactly as the
other decimal transcendentals do.
Exceptions
- ArgumentNullException
xisnull(NumPy would attemptasanyarray(None); NumSharp rejects it up front rather than surfacing a bare NullReferenceException).- OverflowException
xis a Decimal array whosepi*xoverflows the decimal range (a limitation of the shared decimal→double transcendental bridge, not a NumPy behaviour).
sinh(NDArray, NDArray, NDArray, DType)
Hyperbolic sine, element-wise.
Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).
public static NDArray sinh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The sine of each element of x. This is a scalar if x is a scalar.
Remarks
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.).
size(NDArray, int)
size(NDArray, NDAxis?) with the axis as one int: the overload a C# integer binds
(its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer,
error, layout and subclass result is that overload's.
public static long size(NDArray a, int axis)
Parameters
Returns
- long
The number of elements along the given axes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.size.html
NumPy 2.4's statements: axis = normalize_axis_tuple(axis, len(shape)), then the product of those
lengths — so a 0-d input has no axis at all (only the empty tuple, whose product is 1).
One signature since API-parity batch 4 (2026-11-12): the axis was an int?, so NumPy's tuple form
had no spelling; an int? argument converts to NDAxis.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range ("axis … is out of bounds for array of dimension …", the first one in order, as given; every axis is range-checked before the repeat check).
- ValueError
A tuple names an axis twice (
repeated axis).
size(NDArray, int[])
size(NDArray, NDAxis?) with the axes as an int[]: the overload an int[]
binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to
the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is
()).
public static long size(NDArray a, int[] axis)
Parameters
Returns
- long
The number of elements along the given axes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.size.html
NumPy 2.4's statements: axis = normalize_axis_tuple(axis, len(shape)), then the product of those
lengths — so a 0-d input has no axis at all (only the empty tuple, whose product is 1).
One signature since API-parity batch 4 (2026-11-12): the axis was an int?, so NumPy's tuple form
had no spelling; an int? argument converts to NDAxis.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range ("axis … is out of bounds for array of dimension …", the first one in order, as given; every axis is range-checked before the repeat check).
- ValueError
A tuple names an axis twice (
repeated axis).
size(NDArray, NDAxis?)
NumPy's np.size(a, axis=None): the number of elements along the given axes - every element by default,
the length of one axis, or the product of the lengths of a tuple of axes.
public static long size(NDArray a, NDAxis? axis = null)
Parameters
aNDArrayInput data.
axisNDAxis?NumPy's
axis:null(None, the default) counts every element; one axis (1,-1) gives that axis' length; a tuple ((0, 2),new[] { 0, 2 }) the product of its axes' lengths, and the empty tuple 1. Negative axes count from the end.
Returns
- long
The number of elements along the given axes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.size.html
NumPy 2.4's statements: axis = normalize_axis_tuple(axis, len(shape)), then the product of those
lengths — so a 0-d input has no axis at all (only the empty tuple, whose product is 1).
One signature since API-parity batch 4 (2026-11-12): the axis was an int?, so NumPy's tuple form
had no spelling; an int? argument converts to NDAxis.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range ("axis … is out of bounds for array of dimension …", the first one in order, as given; every axis is range-checked before the repeat check).
- ValueError
A tuple names an axis twice (
repeated axis).
sort(NDArray, int?, string, object, bool?, bool?)
Return a sorted copy of an array, sorted along axis (default last; null flattens
first). NumPy's np.sort(a, axis=-1, kind=None, order=None, *, stable=None, descending=False).
public static NDArray sort(NDArray a, int? axis = -1, string kind = null, object order = null, bool? stable = null, bool? descending = null)
Parameters
aNDArrayArray to sort.
axisint?Axis to sort along. -1 = last axis. null = sort the flattened array.
kindstringThe sort algorithm, as NumPy parses it: the first letter decides, case-insensitively —
'q'uicksort (the default),'h'eapsort (the default kind under another name),'m'ergesort or's'table. A value sort gives one answer for every kind, except where equal values have different bits: the default kind leaves the float NaNs in the order NumPy's x86-simd-sort moves them to the end and the stable kind in input order (every NaN's bits kept), and a descending default-kind sort places equal values as NumPy's introsort does.orderobjectField names to sort by. No NumSharp dtype has fields, so any value is refused, as NumPy refuses it for an array without fields.
stablebool?NumPy's keyword-only
stable: true asks for the stable kind. It cannot be combined withkind(false included).descendingbool?NumPy 2.5's keyword-only
descending: true sorts the largest value first, NaN still last (complex: the NaN classes last, each descending). It cannot be combined withkind(false included); null and false sort ascending.
Returns
- NDArray
The sorted copy, laid out as
a.copy(order='K')(a 1-D C array foraxis=null). Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
NaN floats sort to the end; complex sorts lexicographically (real then imaginary), any-NaN-part last; text
(S / U) sorts by code points, compared unsigned — matching NumPy 2.5.4.
Exceptions
- ValueError
An unknown
kind,kindgiven withstableordescending, or anorder; or anumpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- AxisError
The axis is out of bounds (a 0-d input refuses every axis).
- RuntimeError
A
StringDTypearray sorted descending (unsupported sort kind).- ValueError
A
StringDTypeline of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy'sCannot compare null that is not a nan-like value, raised after the lines before it were sorted).- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).- ArgumentNullException
ais null.
sort_complex(NDArray)
Sort a complex array using the real part first, then the imaginary part.
Port of NumPy's numpy/lib/_function_base_impl.py: b = array(a, copy=True);
b.sort() — i.e. sorted along the LAST axis in the input's own dtype — then up-cast
to complex. Always returns a fresh complex array; the input is never mutated.
public static NDArray sort_complex(NDArray a)
Parameters
aNDArrayInput array.
Returns
- NDArray
Sorted complex array (sorted along the last axis). A
numpy.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.sort_complex.html
NumPy widths: int8/uint8/int16/uint16 up-cast to complex64, longdouble to clongdouble,
everything else to complex128; NumSharp has the single Complex
(complex128) width, so every non-complex dtype lands there — the VALUES are identical
(all four narrow-int ranges are exact in float32 and float64 alike), only the width differs.
Char/Decimal (no NumPy analog) take the same route: sort in their own dtype, then cast.
NaN floats sort to the end (→ nan+0j); complex sorts lexicographically with NumPy's
any-NaN-part-last ordering. A 0-d input leaks ndarray.sort()'s own
"axis -1 is out of bounds for array of dimension 0" — exactly as NumPy leaks it.
A StringDType text converts with the value Python's complex() parses: NumPy 2.4.2's
StringDType to complex loop stores the REAL part into both parts ('1+2j' becomes 1+1j, '-0'
becomes -0-0j), a bug NumSharp's cast does not reproduce.
Exceptions
- AxisError
A 0-d array (
axis -1 is out of bounds for array of dimension 0, which NumPy'sb.sort()raises).- ValueError
Text that is not a complex number (
complex() arg is a malformed string): NumPy sorts the text, thenastype('D')parses it, the first malformed string in the sorted array's C order raising. AStringDTypearray: a None-like NA in a line of two or more elements (the sort'sCannot compare null that is not a nan-like value), or any NA left for the cast (Arrays with missing data cannot be converted to a non-nullable type).- ArgumentNullException
ais null.
spacing(NDArray, NDArray, NDArray, DType)
Return the distance between each value of x and the nearest adjacent
representable number in the direction AWAY from zero — i.e. one unit in the last place (ULP)
at that value. spacing(1.0) == np.finfo(x.dtype).eps.
Mirrors NumPy's ufunc signature: spacing(x, /, out=None, *, where=True, dtype=None).
public static NDArray spacing(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array (float family; integer/bool inputs promote to a float per NumPy's width rule, complex is rejected).
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=); masked-off slots of
outkeep their prior contents.dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): must be a FLOAT loop — an integer/bool or complex request raises NumPy's "No loop matching" error.
Returns
- NDArray
Array of the same shape as
xholding each element's spacing. This is a scalar ifxis a scalar.
Remarks
The result carries the SIGN of the input for float32/float64 (spacing(1.0) = +eps,
spacing(-1.0) = -eps) and is +minsubnormal at ±0, ±inf and NaN
both map to NaN, and the largest finite value overflows to +inf. float16 follows
NumPy's separate npy_half_spacing routine, which is always non-negative and halves
the ULP at negative power-of-2 boundaries — a NumPy inconsistency reproduced for parity.
https://numpy.org/doc/stable/reference/generated/numpy.spacing.html
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.).
split(NDArray, int, int)
Split an array into multiple sub-arrays as views into ary.
public static NDArray[] split(NDArray ary, int indices_or_sections, int axis = 0)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintIf an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.
axisintThe axis along which to split, default is 0.
Returns
- NDArray[]
A list of sub-arrays as views into ary. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
Exceptions
- ArgumentNullException
aryis null.- IndexError
axisis out of range: NumPy readsary.shape[axis]first, a Python tuple index ("tuple index out of range"), so a 0-d array refuses every axis.- ValueError
The sections do not divide the axis ("array split does not result in an equal division"), or are not positive ("number sections must be larger than 0.").
- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
split(NDArray, int[], int)
Split an array into multiple sub-arrays as views into ary.
public static NDArray[] split(NDArray ary, int[] indices, int axis = 0)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indicesint[]The split points along
axis:[2, 3]givesary[:2],ary[2:3],ary[3:]. Each point is clamped as a slice bound (a negative one counts from the end), and unsorted points give empty sub-arrays.axisintThe axis along which to split, default is 0.
Returns
- NDArray[]
indices.Length + 1sub-arrays as views into ary. Anumpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
A numpy.char.chararray operand gives chararrays over the results (NumPy creates them as the
subclass).
Exceptions
- ArgumentNullException
aryis null, orindicesis.- IndexError
axisis out of range ("tuple index out of range"; a 0-d array refuses every axis).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
split(NDArray, long[], int)
Split an array into multiple sub-arrays as views into ary.
public static NDArray[] split(NDArray ary, long[] indices, int axis = 0)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indiceslong[]The split points along
axis:[2, 3]givesary[:2],ary[2:3],ary[3:]. Each point is clamped as a slice bound (a negative one counts from the end), and unsorted points give empty sub-arrays.axisintThe axis along which to split, default is 0.
Returns
- NDArray[]
indices.Length + 1sub-arrays as views into ary. Anumpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
A numpy.char.chararray operand gives chararrays over the results (NumPy creates them as the
subclass).
Exceptions
- ArgumentNullException
aryis null, orindicesis.- IndexError
axisis out of range ("tuple index out of range"; a 0-d array refuses every axis).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
sqrt(NDArray, NDArray, NDArray, DType)
Return the non-negative square-root of an array, element-wise.
Mirrors NumPy's ufunc signature: sqrt(x, /, out=None, *, where=True, dtype=None).
public static NDArray sqrt(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayThe values whose square-roots are required.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar.
Remarks
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.).
square(NDArray, NDArray, NDArray, DType)
Return the element-wise square of the input.
Mirrors NumPy's ufunc signature: square(x, /, out=None, *, where=True, dtype=None).
public static NDArray square(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput data.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the input must be same_kind-castable to it.
Returns
- NDArray
Element-wise
x*x(outitself when given).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.square.html
<p>One signature, NumPy's ufunc form: the one-argument overload went with API-parity batch 3 (2026-11-11), so
<code>np.square(x)</code> binds here with the defaults (the same loop, bits and dtype). A method group needs a lambda now
(<code>xs.Select(x => np.square(x))</code>), as for every other ufunc.</p>
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.).
squeeze(NDArray, int)
squeeze(NDArray, NDAxis?) with the axis as one int: the overload a C# integer binds
(its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer,
error, layout and subclass result is that overload's.
public static NDArray squeeze(NDArray a, int axis)
Parameters
Returns
- NDArray
A view of
awith the selected dimensions of length 1 removed: a fresh view object every time,a.view()when there is nothing to remove (NumPy returnsaitself there; a fresh view keeps disposing the result from disposing the input - the plan's D15). Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
A pure VIEW like NumPy's PyArray_Squeeze: the length-one axes are dropped from the
dims AND strides while offset/buffer stay — never a reshape (which rebuilds C-strides and
so lost F-contiguity, and MATERIALIZED non-contiguous inputs where NumPy shares memory).
Probed: np.asfortranarray(zeros((3,1,4))).squeeze() is F-contiguous, a transposed
input stays a strided view, and a broadcast input keeps stride-0 (read-only).
With an axis: NumPy's PyArray_ConvertMultiAxis then PyArray_SqueezeSelected. Its integer
branch lets axis 0 and -1 through for a 0-d input (no axis is selected, so nothing is removed) and checks every
other axis with normalize_axis_index; its tuple branch checks each axis in order - the range, then
whether an earlier item named it (duplicate value in 'axis'), so (0, 0, 5) reports the
repeat and (5, 0, 0) the range. Then every selected axis must have length one.
https://numpy.org/doc/stable/reference/generated/numpy.squeeze.html
One overload, NumPy's signature (2026-11-11): squeeze(a) and squeeze(a, int axis) were
two overloads, so np.squeeze(a, axis: null) did not compile; the NumSharp-only
Shape squeeze(Shape) had no caller and went. The axis is an NDAxis since API-parity
batch 4 (2026-11-12): NumPy's tuple of axes (the axis-type decision, OD1); an int? argument
converts.
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.).- AxisError
An axis is out of range ("axis … is out of bounds for array of dimension …", the axis as given).
- ValueError
A selected axis does not have length one ("cannot select an axis to squeeze out which has size not equal to one"), or a tuple names an axis twice ("duplicate value in 'axis'").
squeeze(NDArray, int[])
squeeze(NDArray, NDAxis?) with the axes as an int[]: the overload an int[]
binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to
the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is
()).
public static NDArray squeeze(NDArray a, int[] axis)
Parameters
Returns
- NDArray
A view of
awith the selected dimensions of length 1 removed: a fresh view object every time,a.view()when there is nothing to remove (NumPy returnsaitself there; a fresh view keeps disposing the result from disposing the input - the plan's D15). Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
A pure VIEW like NumPy's PyArray_Squeeze: the length-one axes are dropped from the
dims AND strides while offset/buffer stay — never a reshape (which rebuilds C-strides and
so lost F-contiguity, and MATERIALIZED non-contiguous inputs where NumPy shares memory).
Probed: np.asfortranarray(zeros((3,1,4))).squeeze() is F-contiguous, a transposed
input stays a strided view, and a broadcast input keeps stride-0 (read-only).
With an axis: NumPy's PyArray_ConvertMultiAxis then PyArray_SqueezeSelected. Its integer
branch lets axis 0 and -1 through for a 0-d input (no axis is selected, so nothing is removed) and checks every
other axis with normalize_axis_index; its tuple branch checks each axis in order - the range, then
whether an earlier item named it (duplicate value in 'axis'), so (0, 0, 5) reports the
repeat and (5, 0, 0) the range. Then every selected axis must have length one.
https://numpy.org/doc/stable/reference/generated/numpy.squeeze.html
One overload, NumPy's signature (2026-11-11): squeeze(a) and squeeze(a, int axis) were
two overloads, so np.squeeze(a, axis: null) did not compile; the NumSharp-only
Shape squeeze(Shape) had no caller and went. The axis is an NDAxis since API-parity
batch 4 (2026-11-12): NumPy's tuple of axes (the axis-type decision, OD1); an int? argument
converts.
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.).- AxisError
An axis is out of range ("axis … is out of bounds for array of dimension …", the axis as given).
- ValueError
A selected axis does not have length one ("cannot select an axis to squeeze out which has size not equal to one"), or a tuple names an axis twice ("duplicate value in 'axis'").
squeeze(NDArray, NDAxis?)
Remove axes of length one from a (NumPy's np.squeeze(a, axis=None)): all of them,
or only the ones axis names.
public static NDArray squeeze(NDArray a, NDAxis? axis = null)
Parameters
aNDArrayInput data.
axisNDAxis?NumPy's
axis:null(None, the default) removes every axis of length one; one axis removes only that axis; a tuple ((0, 2)ornew[] { 0, 2 }) removes each axis it names, and the empty tuple removes none. Every named axis must have length one; negative axes count from the end. The integer form is NumPy's backward-compatibility case on a 0-d input (axis 0 and -1 are accepted and remove nothing); a tuple there has no axis to name.
Returns
- NDArray
A view of
awith the selected dimensions of length 1 removed: a fresh view object every time,a.view()when there is nothing to remove (NumPy returnsaitself there; a fresh view keeps disposing the result from disposing the input - the plan's D15). Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
A pure VIEW like NumPy's PyArray_Squeeze: the length-one axes are dropped from the
dims AND strides while offset/buffer stay — never a reshape (which rebuilds C-strides and
so lost F-contiguity, and MATERIALIZED non-contiguous inputs where NumPy shares memory).
Probed: np.asfortranarray(zeros((3,1,4))).squeeze() is F-contiguous, a transposed
input stays a strided view, and a broadcast input keeps stride-0 (read-only).
With an axis: NumPy's PyArray_ConvertMultiAxis then PyArray_SqueezeSelected. Its integer
branch lets axis 0 and -1 through for a 0-d input (no axis is selected, so nothing is removed) and checks every
other axis with normalize_axis_index; its tuple branch checks each axis in order - the range, then
whether an earlier item named it (duplicate value in 'axis'), so (0, 0, 5) reports the
repeat and (5, 0, 0) the range. Then every selected axis must have length one.
https://numpy.org/doc/stable/reference/generated/numpy.squeeze.html
One overload, NumPy's signature (2026-11-11): squeeze(a) and squeeze(a, int axis) were
two overloads, so np.squeeze(a, axis: null) did not compile; the NumSharp-only
Shape squeeze(Shape) had no caller and went. The axis is an NDAxis since API-parity
batch 4 (2026-11-12): NumPy's tuple of axes (the axis-type decision, OD1); an int? argument
converts.
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.).- AxisError
An axis is out of range ("axis … is out of bounds for array of dimension …", the axis as given).
- ValueError
A selected axis does not have length one ("cannot select an axis to squeeze out which has size not equal to one"), or a tuple names an axis twice ("duplicate value in 'axis'").
stack(NDArray[], int, NDArray, DType, string)
Join a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.
public static NDArray stack(NDArray[] arrays, int axis = 0, NDArray @out = null, DType dtype = null, string casting = "same_kind")
Parameters
arraysNDArray[]Each array must have the same shape.
axisintThe axis in the result array along which the input arrays are stacked.
outNDArrayNumPy's
out=: the destination of the stacked result (it must have the result's shape; the values are cast into it undercasting), returned itself;nullallocates.dtypeDTypeNumPy's
dtype=: the result's dtype (the inputs are cast to it undercasting);nullpromotes the inputs. Cannot be combined without.castingstringNumPy's
casting=rule for those casts ("no","equiv","safe","same_kind"- the default - or"unsafe").
Returns
- NDArray
The stacked array has one more dimension than the input arrays: stacking
n0-d arrays gives shape(n,). 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.stack.html
<p>NumPy's statements: <code>if len({arr.shape for arr in arrays}) != 1: raise ValueError(...)</code>, then each
array gets a new axis at <code class="paramref">axis</code> (normalized against <code>ndim + 1</code>) and the expanded arrays are
concatenated along it. A 0-d operand is expanded as it is — to <code>(1,)</code> — so scalars stack to <code>(n,)</code>
(running them through <code>atleast_1d</code> first, as this method once did, gave <code>(n, 1)</code>). The caller's array
of operands is not modified.</p>
Exceptions
- ArgumentNullException
arraysis null.- ValueError
arraysis empty (need at least one array to stack), or the arrays' shapes differ (all input arrays must have the same shape, checked before the axis).- AxisError
axisis outside the RESULT's rank (the operands' rank plus one;axis 3 is out of bounds for array of dimension 3, the axis as given).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).- TypeError
An input that
dtype/outdoes not reach undercasting(NumPy'sCannot cast array data from ... according to the rule ...), or bothoutanddtype.
std(NDArray, int, DType, NDArray, int, bool, NDArray, NDArray, int?)
std(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) with the axis as
one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray std(NDArray a, int axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe values whose standard deviation is desired.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypeThe loop of both sums (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). An integer or bool dtype with a result that has dimensions is NumPy's sqrt output-cast error; a 0-d result truncates the root instead.
outNDArrayThe FLOAT or complex array the result is written into and returned. NumPy runs the variance into it and takes the square root in place (an integer out is refused after the variance is stored). Footgun: the FOURTH positional parameter, as in NumPy; write
ddof:andkeepdims:by name.ddofintDelta degrees of freedom: the variance divides by
max(N - ddof, 0).keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask of the elements each output takes (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). The C#
trueliteral is NumPy's default;nullis no mask.meanNDArrayThe mean to subtract instead of computing it, used as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or
null.correctionint?The Array API's name of
ddof(see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), ornull.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.
Remarks
Exceptions
- ArgumentNullException
ais null.- ValueError
A nonzero
ddoftogether withcorrection(raised first); a read-only or misshapenout. Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis out of bounds.- TypeError
An integer or bool
dtypewith a result that has dimensions, or an integer or boolout: NumPy'sCannot cast ufunc 'sqrt' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'.- ArgumentException
A non-bool
where.- IncorrectShapeException
out,whereormeandoes not broadcast againsta.- TypeError
A boolean subtraction (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)); a C# scalar passed as
out; NumPy's text refusals; anumpy.matrixoperand withkeepdims,whereormean.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
std(NDArray, int[], DType, NDArray, int, bool, NDArray, NDArray, int?)
std(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) with the axes as
an int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray std(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe values whose standard deviation is desired.
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypeThe loop of both sums (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). An integer or bool dtype with a result that has dimensions is NumPy's sqrt output-cast error; a 0-d result truncates the root instead.
outNDArrayThe FLOAT or complex array the result is written into and returned. NumPy runs the variance into it and takes the square root in place (an integer out is refused after the variance is stored). Footgun: the FOURTH positional parameter, as in NumPy; write
ddof:andkeepdims:by name.ddofintDelta degrees of freedom: the variance divides by
max(N - ddof, 0).keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask of the elements each output takes (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). The C#
trueliteral is NumPy's default;nullis no mask.meanNDArrayThe mean to subtract instead of computing it, used as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or
null.correctionint?The Array API's name of
ddof(see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), ornull.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.
Remarks
Exceptions
- ArgumentNullException
ais null.- ValueError
A nonzero
ddoftogether withcorrection(raised first); a read-only or misshapenout. Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis out of bounds.- TypeError
An integer or bool
dtypewith a result that has dimensions, or an integer or boolout: NumPy'sCannot cast ufunc 'sqrt' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'.- ArgumentException
A non-bool
where.- IncorrectShapeException
out,whereormeandoes not broadcast againsta.- TypeError
A boolean subtraction (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)); a C# scalar passed as
out; NumPy's text refusals; anumpy.matrixoperand withkeepdims,whereormean.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
std(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)
Compute the standard deviation along the specified axis — NumPy's np.std(a, axis=None, dtype=None,
out=None, ddof=0, keepdims=<no value>, *, where=<no value>, mean=<no value>,
correction=<no value>) (_methods._std): the square root of var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?). This is the only
overload: NumPy's whole signature, with NumPy's names, order and defaults.
public static NDArray std(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe values whose standard deviation is desired.
axisNDAxis?The axis to compute along (negative counts from the end);
nulluses every element. A 0-d array takes no axis unlesswhereis a mask. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypeThe loop of both sums (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). An integer or bool dtype with a result that has dimensions is NumPy's sqrt output-cast error; a 0-d result truncates the root instead.
outNDArrayThe FLOAT or complex array the result is written into and returned. NumPy runs the variance into it and takes the square root in place (an integer out is refused after the variance is stored). Footgun: the FOURTH positional parameter, as in NumPy; write
ddof:andkeepdims:by name.ddofintDelta degrees of freedom: the variance divides by
max(N - ddof, 0).keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask of the elements each output takes (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). The C#
trueliteral is NumPy's default;nullis no mask.meanNDArrayThe mean to subtract instead of computing it, used as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or
null.correctionint?The Array API's name of
ddof(see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), ornull.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.
Remarks
Exceptions
- ArgumentNullException
ais null.- ValueError
A nonzero
ddoftogether withcorrection(raised first); a read-only or misshapenout. Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis out of bounds.- TypeError
An integer or bool
dtypewith a result that has dimensions, or an integer or boolout: NumPy'sCannot cast ufunc 'sqrt' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'.- ArgumentException
A non-bool
where.- IncorrectShapeException
out,whereormeandoes not broadcast againsta.- TypeError
A boolean subtraction (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)); a C# scalar passed as
out; NumPy's text refusals; anumpy.matrixoperand withkeepdims,whereormean.- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
subtract(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray subtract(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
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.).
sum(NDArray, int, DType, NDArray, bool, object, NDArray)
sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) with the axis as one
int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray sum(NDArray a, int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayElements to sum (any dtype;
StringDTypeconcatenates, fixed-width text is refused).axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypeThe accumulator and result dtype (a C# Type, an NPTypeCode or a NumPy dtype string converts implicitly): every element is cast to it before it is added.
nullis NumPy's default, NEP 50's accumulator — int64 for bool and the signed integers narrower than 64 bits, uint64 for the unsigned ones, the input's own dtype otherwise — or, without,promote_types(out, a)(no small-integer widening: an int8 sum into an int8 out wraps in int8).outNDArrayThe array the sum is written into and returned. It must have the result's shape; its dtype may differ (the loop's values are cast into it unsafely). Footgun: this is the FOURTH positional parameter, as in NumPy, so a positional bool there (
np.sum(a, 0, null, true)) is a C# scalar passed as out and raises NumPy's TypeError; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions, so the result broadcasts against
a.initialobjectThe value every sum starts from instead of 0, converted into the loop dtype the way NumPy's element setter converts a Python value: a C# integer is a Python int (range-checked, never wrapped:
initial: 1000into an int8 loop raises), adoublea Python float (truncated into an integer loop), a 0-d NDArray is cast. An empty sum is the initial value.nullis NumPy's default, the identity 0 (NumPy'sinitial=None, which starts from each output's first element, has no C# spelling).whereNDArrayA bool mask broadcast against
a: only the selected elements are summed, and an output with none selected is the start value. The C#trueliteral is NumPy's defaultwhere=True;falseselects nothing.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.sum.html. A float sum is NumPy's add.reduce bit for
bit: the result starts at the identity (+0.0, so a sum of only -0.0 is +0.0) or the initial value, and each
inner-loop call of NumPy's iterator adds its pairwise sum. With initial or
where the call runs NumPy's reduction iterator itself; without them the engine's own
schedules, which give the same bits.
Exceptions
- ArgumentNullException
ais null.- TypeError
outis a C# scalar converted to a 0-d array ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; NumPy's text refusals; anumpy.matrixoperand withkeepdims,initialorwhere(NumPy callsmatrix.sum(axis, dtype, out), which has none of them:matrix.sum() got an unexpected keyword argument 'keepdims').- ValueError
A read-only or misshapen
out; a mask with more axes thana; an unconvertibleinitial(a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast againsta.- OverflowError
initialdoes not fit an integer loop ("Python integer 1000 out of bounds for int8").- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out: NumPy's matrix method computes into it and then callsout._collapse.
sum(NDArray, int[], DType, NDArray, bool, object, NDArray)
sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray) with the axes as an
int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray sum(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayElements to sum (any dtype;
StringDTypeconcatenates, fixed-width text is refused).axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypeThe accumulator and result dtype (a C# Type, an NPTypeCode or a NumPy dtype string converts implicitly): every element is cast to it before it is added.
nullis NumPy's default, NEP 50's accumulator — int64 for bool and the signed integers narrower than 64 bits, uint64 for the unsigned ones, the input's own dtype otherwise — or, without,promote_types(out, a)(no small-integer widening: an int8 sum into an int8 out wraps in int8).outNDArrayThe array the sum is written into and returned. It must have the result's shape; its dtype may differ (the loop's values are cast into it unsafely). Footgun: this is the FOURTH positional parameter, as in NumPy, so a positional bool there (
np.sum(a, 0, null, true)) is a C# scalar passed as out and raises NumPy's TypeError; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions, so the result broadcasts against
a.initialobjectThe value every sum starts from instead of 0, converted into the loop dtype the way NumPy's element setter converts a Python value: a C# integer is a Python int (range-checked, never wrapped:
initial: 1000into an int8 loop raises), adoublea Python float (truncated into an integer loop), a 0-d NDArray is cast. An empty sum is the initial value.nullis NumPy's default, the identity 0 (NumPy'sinitial=None, which starts from each output's first element, has no C# spelling).whereNDArrayA bool mask broadcast against
a: only the selected elements are summed, and an output with none selected is the start value. The C#trueliteral is NumPy's defaultwhere=True;falseselects nothing.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.sum.html. A float sum is NumPy's add.reduce bit for
bit: the result starts at the identity (+0.0, so a sum of only -0.0 is +0.0) or the initial value, and each
inner-loop call of NumPy's iterator adds its pairwise sum. With initial or
where the call runs NumPy's reduction iterator itself; without them the engine's own
schedules, which give the same bits.
Exceptions
- ArgumentNullException
ais null.- TypeError
outis a C# scalar converted to a 0-d array ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; NumPy's text refusals; anumpy.matrixoperand withkeepdims,initialorwhere(NumPy callsmatrix.sum(axis, dtype, out), which has none of them:matrix.sum() got an unexpected keyword argument 'keepdims').- ValueError
A read-only or misshapen
out; a mask with more axes thana; an unconvertibleinitial(a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast againsta.- OverflowError
initialdoes not fit an integer loop ("Python integer 1000 out of bounds for int8").- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out: NumPy's matrix method computes into it and then callsout._collapse.
sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)
Sum of array elements over a given axis — NumPy's np.sum(a, axis=None, dtype=None, out=None,
keepdims=<no value>, initial=<no value>, where=<no value>), i.e. np.add.reduce(a, axis,
dtype, out, keepdims=keepdims, initial=initial, where=where). This is the only overload: NumPy's whole
signature, with NumPy's names, order and defaults.
public static NDArray sum(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)
Parameters
aNDArrayElements to sum (any dtype;
StringDTypeconcatenates, fixed-width text is refused).axisNDAxis?The axis to sum over (negative counts from the end);
nullsums every element. A 0-d array accepts 0 and -1 as every axis (ufunc.reduce's rule). A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypeThe accumulator and result dtype (a C# Type, an NPTypeCode or a NumPy dtype string converts implicitly): every element is cast to it before it is added.
nullis NumPy's default, NEP 50's accumulator — int64 for bool and the signed integers narrower than 64 bits, uint64 for the unsigned ones, the input's own dtype otherwise — or, without,promote_types(out, a)(no small-integer widening: an int8 sum into an int8 out wraps in int8).outNDArrayThe array the sum is written into and returned. It must have the result's shape; its dtype may differ (the loop's values are cast into it unsafely). Footgun: this is the FOURTH positional parameter, as in NumPy, so a positional bool there (
np.sum(a, 0, null, true)) is a C# scalar passed as out and raises NumPy's TypeError; writekeepdims: trueby name.keepdimsboolKeep the reduced axes as length-1 dimensions, so the result broadcasts against
a.initialobjectThe value every sum starts from instead of 0, converted into the loop dtype the way NumPy's element setter converts a Python value: a C# integer is a Python int (range-checked, never wrapped:
initial: 1000into an int8 loop raises), adoublea Python float (truncated into an integer loop), a 0-d NDArray is cast. An empty sum is the initial value.nullis NumPy's default, the identity 0 (NumPy'sinitial=None, which starts from each output's first element, has no C# spelling).whereNDArrayA bool mask broadcast against
a: only the selected elements are summed, and an output with none selected is the start value. The C#trueliteral is NumPy's defaultwhere=True;falseselects nothing.nullis no mask.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis withoutkeepdims.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.sum.html. A float sum is NumPy's add.reduce bit for
bit: the result starts at the identity (+0.0, so a sum of only -0.0 is +0.0) or the initial value, and each
inner-loop call of NumPy's iterator adds its pairwise sum. With initial or
where the call runs NumPy's reduction iterator itself; without them the engine's own
schedules, which give the same bits.
Exceptions
- ArgumentNullException
ais null.- TypeError
outis a C# scalar converted to a 0-d array ("return arrays must be of ArrayType");initialis complex for a real loop or of an unconvertible type; NumPy's text refusals; anumpy.matrixoperand withkeepdims,initialorwhere(NumPy callsmatrix.sum(axis, dtype, out), which has none of them:matrix.sum() got an unexpected keyword argument 'keepdims').- ValueError
A read-only or misshapen
out; a mask with more axes thana; an unconvertibleinitial(a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array (NumPy's TypeError text).- AxisError
axisis out of bounds.- IncorrectShapeException
whereoroutdoes not broadcast againsta.- OverflowError
initialdoes not fit an integer loop ("Python integer 1000 out of bounds for int8").- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out: NumPy's matrix method computes into it and then callsout._collapse.
swapaxes(NDArray, int, int)
Interchange two axes of an array.
public static NDArray swapaxes(NDArray a, int axis1, int axis2)
Parameters
Returns
Remarks
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.).
take(NDArray, NDArray, int?, NDArray, string)
Take elements from an array along an axis. Equivalent to fancy indexing along the specified axis.
public static NDArray take(NDArray a, NDArray indices, int? axis = null, NDArray @out = null, string mode = "raise")
Parameters
aNDArraySource array.
indicesNDArrayInteger array of indices to take (any layout; read in C order).
axisint?Axis along which to take.
null(default) flattensaand treatsindicesas flat indices. A 0-dais flattened too, so its axis must be valid for one dimension (0 or -1).outNDArrayOptional destination array. When supplied, its shape must match the natural take output; values are cast to
out's dtype via copyto(NDArray, NDArray, string, NDArray) with unsafe casting and the method returnsoutitself. Whennull(default), a fresh array is allocated witha's dtype.modestringBoundary mode:
"raise"(default — throw on OOB),"wrap"(modulo with sign correction), or"clip"(saturate);nullis NumPy'sNone(raise).
Returns
- NDArray
New array with shape:
axis=None: same asindices.axis=k:a.shape[:k] + indices.shape + a.shape[k+1:].
Dtype matches
a(orout's dtype whenoutis supplied). Anumpy.char.chararrayoperand gives a chararray over the result; a 0-d result withoutoutis the element's UNSTRIPPED NumPy scalar (PyArray_Return), NumSharp's read-only stand-in.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.take.html
One overload, NumPy's signature (2026-11-11): a C# integer index converts to a 0-d index array (the
result has the taken element's shape, a 0-d one without an axis), so the former (long index)
overload is gone.
The work is TakeFrom(NDArray, NDArray, int?, NDArray, int), NumPy's PyArray_TakeFrom, which also fixes the order of the
checks above.
[NDScoped] reclaims the int64 index copy, the C-order source copy and the natural-result temp on the out= path.
Exceptions
- ArgumentNullException
aorindicesis null.- ValueError
A bad
mode(ClipmodeConverter(string)), checked first; anoutof another shape (output array does not match result of ndarray.take) or a read-only one (WRITEBACKIFCOPY base is read-only).- AxisError
axisis out of range.- TypeError
The index dtype does not cast to int64 under
same_kind(float, complex), an empty index array included; orout's dtype does not cast toa's undersafe.- IndexError
A non-empty result from an empty axis (
cannot do a non-empty take from an empty axes.), or an index out of bounds undermode="raise"(index 9 is out of bounds for axis 0 with size 4).- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
take_along_axis(NDArray, NDArray, int?)
Take values from the input array by matching 1-D index and data slices.
Iterates over matching 1-D slices oriented along axis in the
index and data arrays, using the former to look up values in the latter. These
slices can be different lengths. Functions returning an index along an axis, like
argsort(NDArray, int?, string, object, bool?) and argmax/argmin with
keepdims, produce suitable indices.
public static NDArray take_along_axis(NDArray arr, NDArray indices, int? axis = -1)
Parameters
arrNDArraySource array
(Ni..., M, Nk...).indicesNDArrayInteger index array
(Ni..., J, Nk...). Must match the dimension count ofarr; the non-axis dimensionsNi/Nkonly need to broadcast againstarr.axisint?The axis to take 1-D slices along (default
-1, matching NumPy 2.3+). Whennullthe source is treated as if first flattened to 1-D in C-order, for consistency withsort/argsort; thenindicesmust be 1-D.
Returns
- NDArray
A fresh C-contiguous array of shape
(Ni..., J, Nk...)(the broadcast of the non-axis dimensions, withJ = indices.shape[axis]) and dtype ofarr. Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
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.).
tan(NDArray, NDArray, NDArray, DType)
Compute tangent element-wise.
Equivalent to np.sin(x)/np.cos(x) element-wise.
Mirrors NumPy's ufunc signature: tan(x, /, out=None, *, where=True, dtype=None).
public static NDArray tan(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngle, in radians (2 \pi rad equals 360 degrees).
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
The tangent of each element of x. This is a scalar if x is a scalar.
Remarks
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.).
tanh(NDArray, NDArray, NDArray, DType)
Compute hyperbolic tangent element-wise.
Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).
public static NDArray tanh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The sine of each element of x. This is a scalar if x is a scalar.
Remarks
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.).
tensordot(NDArray, NDArray, int)
Tensor contraction over the given axes — a sum product over the last
axes axes of a and the first
axes of b.
public static NDArray tensordot(NDArray a, NDArray b, int axes = 2)
Parameters
aNDArrayThe first tensor (not null).
bNDArrayThe second tensor (not null).
axesintHow many trailing axes of
ato contract against leading axes ofb.0gives the outer (tensor) product;1is dot(NDArray, NDArray, NDArray);2(the default) is the double contraction. A NEGATIVE count contracts nothing — NumPy formsrange(-axes, 0), which is empty for anyaxes <= 0.
Returns
- NDArray
A new array of
a's kept axes followed byb's.
Remarks
Exceptions
- IndexError
More axes than an operand has (
tuple index out of range).- ValueError
Contracted extents that differ (
shape-mismatch for sum), or the final dot's refusals of text.- TypeError
The final dot's refusals of text operands.
- NotSupportedException
A
StringDTypeoperand beside a number (NumPy's object product).- NullReferenceException
aorbis null.
tensordot(NDArray, NDArray, (int AxisA, int AxisB))
Tensor contraction pairing one axis of a with one of
b — NumPy's axes=(int, int) spelling.
public static NDArray tensordot(NDArray a, NDArray b, (int AxisA, int AxisB) axes)
Parameters
aNDArrayThe first tensor (not null).
bNDArrayThe second tensor (not null).
axes(int AxisA, int AxisB)The axis of
aand the axis ofbto contract.
Returns
- NDArray
A new array of
a's kept axes followed byb's.
Remarks
A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or
ends with np.concatenate), which drops the class. NumPy's axes_a, axes_b = axes with two ints makes
the one-element lists [axes_a] / [axes_b], so the pair calls
Tensordot(NDArray, NDArray, int[], int[]), on a's engine.
Exceptions
- IndexError
An axis out of range (
tuple index out of range).- ValueError
Extents that differ (
shape-mismatch for sum), or the final dot's refusals of text.- TypeError
The final dot's refusals of text operands.
- NotSupportedException
A
StringDTypeoperand beside a number.- NullReferenceException
aorbis null.
tensordot(NDArray, NDArray, (int[] AxesA, int[] AxesB))
Tensor contraction pairing a list of axes of a with a list of axes of b,
element by element — NumPy's axes=([1, 0], [0, 1]) spelling, the pair as ONE argument:
np.tensordot(a, b, axes: (new[] { 1, 0 }, new[] { 0, 1 })).
public static NDArray tensordot(NDArray a, NDArray b, (int[] AxesA, int[] AxesB) axes)
Parameters
aNDArrayThe first tensor (not null).
bNDArrayThe second tensor (not null).
axes(int[] AxesA, int[] AxesB)NumPy's pair of axis lists:
AxesA, the axes ofato contract in pairing order, andAxesB, the axes ofbpaired with them element by element.
Returns
- NDArray
A new array of
a's kept axes followed byb's.
Remarks
A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or
ends with np.concatenate), which drops the class. NumPy's axes_a, axes_b = axes, then the
statements of Tensordot(NDArray, NDArray, int[], int[]), on a's
engine.
NumPy has ONE axes argument; until API-parity batch 7 NumSharp split the pair into two parameters,
tensordot(a, b, int[] axesA, int[] axesB), the four-argument call NumPy refuses
(tensordot() takes from 2 to 3 positional arguments but 4 were given).
Exceptions
- ValueError
"duplicate axes are not allowed in tensordot"when either list repeats a raw axis value (checked first, ahead of everything), or"shape-mismatch for sum"for unequal list lengths and mismatched contracted extents alike.- IndexError
"tuple index out of range"when a contraction axis is out of range — NumPy indexes the shape tuple with the raw axis, so this is an index error, not a shape mismatch. A mismatched extent found earlier in the list settles as the shape mismatch first, hiding a later out-of-range axis.- TypeError
The final dot's refusals of text operands.
- NotSupportedException
A
StringDTypeoperand beside a number (NumPy's object product).- NullReferenceException
a,bor an axis list is null.
tile(NDArray, Shape)
Construct an array by repeating A the number of times given by reps —
NumPy's np.tile(A, reps).
If reps has length d, the result has dimension max(d, A.ndim).
If A.ndim < d, A is promoted to be d-dimensional by prepending size-1 axes.
If A.ndim > d, reps is promoted to A.ndim by prepending 1s.
public static NDArray tile(NDArray A, Shape reps)
Parameters
ANDArrayThe input array.
repsShapeThe number of repetitions of A along each axis, as ONE argument: an int (
2), a tuple ((2, 3)), anint[]/long[]or a Shape (all convert implicitly; only the values are read). An emptyrepsis a copy ofA.
Returns
- NDArray
The tiled output array, of
A's dtype: C-contiguous for a real repetition, a keep-order copy for all-one repetitions. Anumpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.tile.html — NumPy's statements are the array object's
(NDArray.tile), which releases its intermediates: the interleaved reshape of A, its
broadcast view and the materialized copy, the reshape of a lower-rank A on the all-ones
path, and the zero-filled array behind an empty result's view.
One signature since API-parity batch 8 (2026-11-12): the params int[] reps and long[] reps
overloads went. A tuple now compiles (np.tile(a, (2, 2))), and the loose np.tile(a, 2, 2) — NumPy's
TypeError: tile() takes 2 positional arguments but 3 were given — no longer does. A negative repetition
raised an ArgumentException naming the padded index before.
Exceptions
- ArgumentNullException
Ais null.- ValueError
A negative repetition that NumPy's
repeatreaches while the tile still holds elements (negative dimensions are not allowed); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- IncorrectShapeException
A negative repetition of an empty tile: NumPy's final reshape refuses the negative extent (
cannot reshape array of size 0 into shape (0,newaxis), NumPy's ValueError text).
trace(NDArray, int, int, int, DType, NDArray)
Return the sum along diagonals of the array. For a 2-D array,
trace(a) == sum(a.diagonal()). For an N-D array, traces
the diagonals along the 2-D sub-arrays defined by
axis1 / axis2 and reduces
them, leaving an array with those two axes removed.
public static NDArray trace(NDArray a, int offset = 0, int axis1 = 0, int axis2 = 1, DType dtype = null, NDArray @out = null)
Parameters
aNDArraySource array. Must have at least 2 dimensions.
offsetintOffset of the diagonal from the main diagonal. See diagonal(NDArray, int, int, int) for details.
axis1intFirst axis of the 2-D sub-array. Default 0.
axis2intSecond axis of the 2-D sub-array. Default 1.
dtypeDTypeOutput dtype.
null(default) preservesa.dtype, except narrow integer dtypes widen per NumPy's add.reduce rule: signed ints and bool promote to long, UNSIGNED ints (and Char, the uint16 twin) promote to ulong — trace(uint8) is uint64, exactly as in NumPy.outNDArrayOptional output array. Shape must equal the natural reduction output; values are copied with unsafe casting and the method returns
outitself. Withoutdtypethe sum runs inpromote_types(out.dtype, a.dtype)with no widening, as NumPy's add.reduce does once an out is given: an int8 diagonal [100, 100, 56] into a bool out wraps to 0 and stores False.
Returns
- NDArray
Sum along the diagonal. 2-D input → 0-d scalar. N-D input → array with
a.shapeminusaxis1andaxis2.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.trace.html
Mirrors NumPy's PyArray_Trace: sum(diagonal(a,
offset, axis1, axis2), axis=-1, dtype=dtype, out=out). The
diagonal view is the heavy lifting; the sum is a regular
reduction that goes through NumSharp's IL reduction kernels.
Exceptions
- ValueError
ahas fewer than two dimensions, or the two axes are the same axis ("axis1 and axis2 cannot be the same"); a read-onlyout("output array is read-only") or one of the wrong rank ("output parameter for reduction operation add has the wrong number of dimensions: ...").- AxisError
An axis is out of range: "axis1: axis …" / "axis2: axis …" (axis1 checked first).
- ArgumentNullException
ais null.- TypeError
NumPy's loop resolution refuses text: a text operand with another out class, a text out for numbers, a string
dtype.- IncorrectShapeException
out's length does not broadcast against the diagonal (NumPy's "operands could not be broadcast together with remapped shapes" text).
transpose(NDArray, int[])
Permute the dimensions of an array: a view, never a copy, with the dimensions and strides reordered.
public static NDArray transpose(NDArray a, int[] axes = null)
Parameters
aNDArrayInput array.
axesint[]NumPy's
axes: a permutation of[0, 1, ..., a.ndim - 1](negative axes count from the end), ornull(NumPy'sNone, the default) to reverse the dimensions. An empty permutation is a permutation like any other: it fits only a 0-d array.
Returns
- NDArray
a with its axes permuted. A view is returned whenever possible. A
numpy.char.chararrayoperand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.transpose.html
NumPy's signature transpose(a, axes=None), keyword for keyword: the parameter was called
premute until 2026-11-11, so a ported np.transpose(a, axes: ...) did not compile.
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.).- ValueError
axesdoes not have one entry per dimension (axes don't match array), or repeats an axis (repeated axis in transpose).- AxisError
An entry of
axesis out of bounds.
trapezoid(NDArray, NDArray, double, int)
Integrate y along the given axis using the
composite trapezoidal rule.
public static NDArray trapezoid(NDArray y, NDArray x = null, double dx = 1, int axis = -1)
Parameters
yNDArrayInput array to integrate (at least one dimensional).
xNDArrayThe sample points corresponding to the
yvalues. Whennull(the default) the samples are assumed evenly spaceddxapart. A 1-Dxsupplies the spacing alongaxis(broadcast across the other axes); an N-Dxis differenced along its ownaxis(counted againstx.ndim, as NumPy'sdiff(x, axis=axis)does) and broadcast againsty. Integration followsx's order — the points are NOT sorted, so a decreasingxintegrates in reverse (negative area).dxdoubleThe spacing between sample points when
xisnull. Default 1. Ignored whenxis supplied.axisintThe axis along which to integrate; default is the last axis. Negative axes count from the end. It is read against each array of the composition the way NumPy reads it:
y's slices usey.ndim, the N-Dx's difference usesx.ndim, and the final sum uses the rank of the broadcast product (which an N-Dxwith more dimensions thanyraises).
Returns
- NDArray
Definite integral approximated along
axis. Ifyis 1-D (and no higher-rankxbroadcasts it) the result is a 0-D array (a scalar); otherwise it is the broadcast productd * (y[1:] + y[:-1])with the integration axis removed, laid out as NumPy's reduction lays it out. The dtype follows NEP50 promotion of the composition and is always in the float family (float16/float32/float64/complex128, or the NumSharp-only Decimal); integer and boolean inputs yield float64. The values are bit-identical to NumPy's for every memory layout ofyandx, a single interval included: its final sum runs over a length-1 axis, which starts from NumPy's+0.0identity, so a-0.0area comes back+0.0(np_sum_identity_tests.Trapezoid_OneInterval_NegativeZeroArea_IsPositiveZero).
Remarks
Exceptions
- ArgumentNullException
yisnull.- IndexError
axisis outside[-y.ndim, y.ndim-1], which every axis of a 0-Dyis: NumPy's "list assignment index out of range", verbatim. NumPy's trapezoid never checks the axis; Python's assignment into its list of lengthy.ndimraises. An error inx(the two below) is reported first, as in NumPy, which resolves the spacing before it slicesy.- ArgumentOutOfRangeException
An N-D
xhas no axisaxis: diff(NDArray, int, int, object, object)'s "axis N is out of bounds for array of dimension M" (NumPy'sAxisErrorfromdiff(x, axis=axis)).- ArgumentException
A 0-D
x("diff requires input that is at least one dimensional", diff(NDArray, int, int, object, object)'s error).- IncorrectShapeException
The spacing does not broadcast against
y[1:] + y[:-1]— NumPy'soperands could not be broadcast together with shapes …from thed * (…)multiply, verbatim.- TypeError
A text
yorx(U, S or StringDType): NumPy's statements run as they are, and the first one without a loop for its operands refuses with NumPy's text — np.diff's subtract for a textx, the multiply of the spacing and the concatenatedy[1:] + y[:-1](for a fixed-widthyand an integer spacing, the string multiply's "The 'out' kwarg is necessary" error), or the division by2.0of a StringDType product an integer spacing repeated. A StringDType concatenation that meets an NA it cannot add raises NumPy's ValueError instead.
tri(int, int?, int, DType)
An array with ones at and below the given diagonal and zeros elsewhere.
public static NDArray tri(int N, int? M = null, int k = 0, DType dtype = null)
Parameters
NintNumber of rows in the array.
Mint?Number of columns in the array. By default,
Mis taken equal toN.kintThe sub-diagonal at and below which the array is filled.
k = 0is the main diagonal, whilek < 0is below it, andk > 0is above.dtypeDTypeData type of the returned array. Defaults to double.
Returns
- NDArray
Array with shape
(N, M)whose lower triangle — filled with ones — is at and below thek-th diagonal. Always a freshly allocated, C-contiguous, writeable array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.tri.html
NumPy computes this as greater_equal.outer(arange(N), arange(-k, M-k))
followed by an astype — two full N×M passes plus a bool temporary.
Because row i is exactly c_i = clamp(i + k + 1, 0, M) ones followed
by zeros, NumSharp instead allocates the (already zeroed) result and blits a
prefix of a single pre-built ones row into each row. That is one
MemoryCopy(void*, void*, long, long) per row over an untouched zero tail — no
comparison kernel, no mask temporary, and completely dtype-agnostic (the copy
only ever sees bytes).
Negative N/M clamp to zero, matching
NumPy (whose arange of a negative count yields an empty axis).
The dtype is read as its storage lane (GetTypeCode()), which the array object's tri fills; it has no operand, so no class rule applies.
tril(NDArray, int)
Lower triangle of an array — a copy of m with all elements
above the k-th diagonal zeroed.
public static NDArray tril(NDArray m, int k = 0)
Parameters
mNDArrayInput array. For arrays with
ndim > 2,trilapplies to the final two axes.kintDiagonal above which to zero elements.
k = 0(the default) is the main diagonal,k < 0is below it andk > 0is above.
Returns
- NDArray
Lower triangle of
m, of the same dtype. Always a fresh, writeable, C-contiguous array (2-D for a 1-Dm, whose row is broadcast down a square matrix).
Remarks
Exceptions
- ArgumentNullException
mis null.- TypeError
mis 0-d (NumPy's leaked CPython TypeError:tri() missing 1 required positional argument: 'N').
tril_indices(int, int, int?)
Return the indices for the lower-triangle of an (n, m) array.
public static NDArray<long>[] tril_indices(int n, int k = 0, int? m = null)
Parameters
nintThe row dimension of the arrays for which the returned indices will be valid; a negative count is an empty axis.
kintDiagonal offset.
k = 0(default) is the main diagonal.mint?The column dimension. By default
mis taken equal ton.
Returns
- NDArray<long>[]
The row and column indices of the lower triangle, in C (row-major) order: two owning int64 arrays (OWNDATA True, as NumPy's boolean-mask gathers are).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.tril_indices.html
<p>NumPy's statements are the array object's (<code>NDArray.tril_indices</code>), which emits the triangle's row
runs in O(output) and releases its column ladder.</p>
tril_indices_from(NDArray, int)
Return the indices for the lower-triangle of arr.
public static NDArray<long>[] tril_indices_from(NDArray arr, int k = 0)
Parameters
Returns
- NDArray<long>[]
The row and column indices of
arr's lower triangle (see tril_indices(int, int, int?)).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.tril_indices_from.html
<p>Only the shape is read, so no class rule applies (a numpy.matrix has two axes).</p>
Exceptions
- ArgumentNullException
arris null.- ArgumentException
input array must be 2-d(NumPyValueError, verbatim).- OverflowException
A dimension of
arrexceeds MaxValue.
trim_zeros(NDArray, string, int)
trim_zeros(NDArray, string, NDAxis?) with the axis as one int: the overload a C#
integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so
every answer, error, layout and subclass result is that overload's.
public static NDArray trim_zeros(NDArray filt, string trim, int axis)
Parameters
filtNDArrayInput array.
trimstringA string with 'f' representing trim from front and 'b' to trim from back. By default, zeros are trimmed on both sides ("fb"). Case-insensitive; "bf" is accepted as an alias of "fb".
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).
Returns
- NDArray
A view of
filtwith leading/trailing all-zero hyperplanes removed. The number of dimensions and the input dtype are preserved. Anumpy.char.chararrayornumpy.matrixoperand gives its class over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.trim_zeros.html. A string array is trimmed by its
truth values (an empty string — all NULs — is a zero): NumPy's _arg_trim_zeros runs np.argwhere,
the dtype's nonzero route, which never raises; the result is a view of the text itself.
<p>One signature since API-parity batch 4 (2026-11-12): it replaces <code>(filt, trim = "fb", int? axis)</code>
and <code>(filt, string trim, int[] axis)</code>, which made <code>np.trim_zeros(filt, "fb", null)</code> ambiguous
(CS0121) and had no tuple literal.</p>
Exceptions
- ArgumentNullException
filtis null.- ValueError
trimcontains unexpected characters, an axis is repeated (repeated axis in), or aaxisargumentnumpy.matrixoperand's result cannot be a matrix (more than two axes longer than 1:shape too large to be a matrix.).- AxisError
An axis is out of bounds for
filt(axis: axis 2 is out of bounds for array of dimension 2: NumPy names the argument; every axis is checked before the repeat check).
trim_zeros(NDArray, string, int[])
trim_zeros(NDArray, string, NDAxis?) with the axes as an int[]: the overload an
int[] binds, and a bare null too (null converts to int[] better than to NDAxis),
forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new
int[0] is ()).
public static NDArray trim_zeros(NDArray filt, string trim, int[] axis)
Parameters
filtNDArrayInput array.
trimstringA string with 'f' representing trim from front and 'b' to trim from back. By default, zeros are trimmed on both sides ("fb"). Case-insensitive; "bf" is accepted as an alias of "fb".
axisint[]The axes as NumPy's tuple, or
nullfor None.
Returns
- NDArray
A view of
filtwith leading/trailing all-zero hyperplanes removed. The number of dimensions and the input dtype are preserved. Anumpy.char.chararrayornumpy.matrixoperand gives its class over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.trim_zeros.html. A string array is trimmed by its
truth values (an empty string — all NULs — is a zero): NumPy's _arg_trim_zeros runs np.argwhere,
the dtype's nonzero route, which never raises; the result is a view of the text itself.
<p>One signature since API-parity batch 4 (2026-11-12): it replaces <code>(filt, trim = "fb", int? axis)</code>
and <code>(filt, string trim, int[] axis)</code>, which made <code>np.trim_zeros(filt, "fb", null)</code> ambiguous
(CS0121) and had no tuple literal.</p>
Exceptions
- ArgumentNullException
filtis null.- ValueError
trimcontains unexpected characters, an axis is repeated (repeated axis in), or aaxisargumentnumpy.matrixoperand's result cannot be a matrix (more than two axes longer than 1:shape too large to be a matrix.).- AxisError
An axis is out of bounds for
filt(axis: axis 2 is out of bounds for array of dimension 2: NumPy names the argument; every axis is checked before the repeat check).
trim_zeros(NDArray, string, NDAxis?)
NumPy's np.trim_zeros(filt, trim='fb', axis=None): remove the leading and/or trailing hyperplanes that
are zero along all other dimensions - over every axis (the smallest bounding box that still holds every non-zero
value) by default, or only along the given axes.
public static NDArray trim_zeros(NDArray filt, string trim = "fb", NDAxis? axis = null)
Parameters
filtNDArrayInput array.
trimstringA string with 'f' representing trim from front and 'b' to trim from back. By default, zeros are trimmed on both sides ("fb"). Case-insensitive; "bf" is accepted as an alias of "fb".
axisNDAxis?NumPy's
axis:null(None, the default) cropsfiltto the smallest bounding box that still contains all non-zero values; one axis (0,-1) or a tuple ((0, 1),new[] { 0, 1 }) slices only those dimensions, on the sidestrimselects. The empty tuple leaves the input unmodified.
Returns
- NDArray
A view of
filtwith leading/trailing all-zero hyperplanes removed. The number of dimensions and the input dtype are preserved. Anumpy.char.chararrayornumpy.matrixoperand gives its class over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.trim_zeros.html. A string array is trimmed by its
truth values (an empty string — all NULs — is a zero): NumPy's _arg_trim_zeros runs np.argwhere,
the dtype's nonzero route, which never raises; the result is a view of the text itself.
<p>One signature since API-parity batch 4 (2026-11-12): it replaces <code>(filt, trim = "fb", int? axis)</code>
and <code>(filt, string trim, int[] axis)</code>, which made <code>np.trim_zeros(filt, "fb", null)</code> ambiguous
(CS0121) and had no tuple literal.</p>
Exceptions
- ArgumentNullException
filtis null.- ValueError
trimcontains unexpected characters, an axis is repeated (repeated axis in), or aaxisargumentnumpy.matrixoperand's result cannot be a matrix (more than two axes longer than 1:shape too large to be a matrix.).- AxisError
An axis is out of bounds for
filt(axis: axis 2 is out of bounds for array of dimension 2: NumPy names the argument; every axis is checked before the repeat check).
triu(NDArray, int)
Upper triangle of an array — a copy of m with all elements
below the k-th diagonal zeroed.
public static NDArray triu(NDArray m, int k = 0)
Parameters
mNDArrayInput array. For arrays with
ndim > 2,triuapplies to the final two axes.kintDiagonal below which to zero elements.
k = 0(the default) is the main diagonal,k < 0is below it andk > 0is above.
Returns
- NDArray
Upper triangle of
m, of the same dtype. Always a fresh, writeable, C-contiguous array (2-D for a 1-Dm, whose row is broadcast down a square matrix).
Remarks
Exceptions
- ArgumentNullException
mis null.- TypeError
mis 0-d (NumPy's leaked CPython TypeError:tri() missing 1 required positional argument: 'N').
triu_indices(int, int, int?)
Return the indices for the upper-triangle of an (n, m) array.
public static NDArray<long>[] triu_indices(int n, int k = 0, int? m = null)
Parameters
nintThe size of the arrays for which the returned indices will be valid; a negative count is an empty axis.
kintDiagonal offset.
k = 0(default) is the main diagonal.mint?The column dimension. By default
mis taken equal ton.
Returns
- NDArray<long>[]
The row and column indices of the upper triangle, in C (row-major) order: two owning int64 arrays (OWNDATA True, as NumPy's boolean-mask gathers are).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.triu_indices.html
<p>NumPy's statements are the array object's (<code>NDArray.triu_indices</code>).</p>
triu_indices_from(NDArray, int)
Return the indices for the upper-triangle of arr.
public static NDArray<long>[] triu_indices_from(NDArray arr, int k = 0)
Parameters
Returns
- NDArray<long>[]
The row and column indices of
arr's upper triangle (see triu_indices(int, int, int?)).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.triu_indices_from.html
<p>Only the shape is read, so no class rule applies (a numpy.matrix has two axes).</p>
Exceptions
- ArgumentNullException
arris null.- ArgumentException
input array must be 2-d(NumPyValueError, verbatim).- OverflowException
A dimension of
arrexceeds MaxValue.
true_divide(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray true_divide(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
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.).
trunc(NDArray, NDArray, NDArray, DType)
Return the truncated value of the input, element-wise. The truncated value of the scalar x is the nearest integer i which is closer to zero than x is.
public static NDArray trunc(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The truncated value of each element in x. This is a scalar if x is a scalar.
Remarks
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.).
typename(string)
Returns a human-readable description for an array-protocol data-type CODE (np.typename) — e.g.
"i" -> "integer", "D" -> "complex double precision". This is a
type-CODE lookup, NOT a dtype-name lookup: it expects the single-character codes
(?bBhHiIlLqQfdgFDGSUVO) or the two-character "S1", is CASE-SENSITIVE, and has no
entry for "e" (half) — matching NumPy, which omits it.
public static string typename(string @char)
Parameters
charstringThe array-protocol type code to describe. Footgun:
"S1"->"character"but a bare"S"->"string"(two distinct entries), so the wrong one returns a different valid description rather than raising; a differently-cased code ("s") or a dtype NAME ("int32") is not a code and raises.
Returns
- string
The description string for
char.
Remarks
Exceptions
- KeyError
charis not one of the 22 recognised codes — this covers an unknown code, an empty or multi-character string, a differently-cased code, and anullargument. The message is the Pythonreprof the argument ('x','',None), matching the rawdictKeyError NumPy leaks.
union1d(NDArray, NDArray)
Find the union of two arrays.
Return the unique, sorted array of values that are in either of the two input arrays.
public static NDArray union1d(NDArray ar1, NDArray ar2)
Parameters
ar1NDArrayInput array (flattened if not already 1-D).
ar2NDArrayInput array (flattened if not already 1-D).
Returns
- NDArray
Unique, sorted union of the input arrays.
Remarks
Exceptions
- UnicodeDecodeError
A
Uunion overStext holding a non-ASCII byte (NumPy's concatenation decodes it first).- DTypePromotionError
A
StringDTypeoperand beside a class the concatenation finds no common DType with (a number, bool,Sbytes): NumPy's verbatim promotion text.- ValueError
A NEP 55
StringDTypearray whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy'sCannot compare null that is not a nan-like value.- ArgumentNullException
ar1is null.
unique(NDArray, bool, bool, bool, int?, bool, bool)
Find the unique elements of an array — the single NumPy-shaped entry point.
Returns the sorted unique elements and, per the return_* flags, the
first-occurrence indices, the reconstruction (inverse) indices, and the per-value counts,
bundled in a np.UniqueResult that stands in for NumPy's bare-array-or-tuple
return. Because np.UniqueResult converts implicitly to both NDArray
and NDArray[], every NumPy call shape ports verbatim — including
np.unique(ar, return_counts: true) and np.unique(ar, axis: 0).
public static np.UniqueResult unique(NDArray ar, bool return_index = false, bool return_inverse = false, bool return_counts = false, int? axis = null, bool equal_nan = true, bool sorted = true)
Parameters
arNDArrayInput array. Unless
axisis given, it is flattened first.return_indexboolIf True, also return the first-occurrence indices of
ar(alongaxisif given) that produce the unique values.return_inverseboolIf True, also return the indices of the unique array that reconstruct
ar.return_countsboolIf True, also return the number of times each unique value appears.
axisint?The axis to operate on. If
null(default), the array is flattened first.equal_nanboolIf True (default), all NaN values collapse to a single output value; if False, each NaN is a distinct value.
sortedboolAccepted for NumPy 2.3 parity; NumSharp always returns sorted output (NumPy's
sorted=Falsehash-iteration order for integer/complex values is platform-specific and not reproducible in C# — spec-compliant, the Array API leaves it unspecified). See unique_values(NDArray).
Returns
- np.UniqueResult
A np.UniqueResult carrying
valuesand the requested outputs. Anumpy.char.chararrayoperand gives a chararray VIEW of the unique values (NumPy's_array_converter.wrap); the index arrays stay plain.
Remarks
Exceptions
- AxisError
axisis out of range.- TypeError
A NEP 55
StringDTypearray with anaxisover two or more dimensions: NumPy's structured path refusesStringDTypefields (The axis argument to unique is not supported for dtype StringDType(); rows of zero width:Cannot change data-type for array of references.).- ValueError
A NEP 55
StringDTypearray whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry (the sorted path:sortedor a return flag; NumPy's values-onlysorted=Falsehash pass compares nothing): NumPy'sCannot compare null that is not a nan-like value.- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
unique_all(NDArray)
Find the unique elements of x together with the first-occurrence indices,
reconstruction indices, and counts.
Array API compatible alternative to np.unique(x, return_index=True, return_inverse=True,
return_counts=True, equal_nan=False). The input is flattened. Each NaN is treated as
a distinct value.
public static np.UniqueAllResult unique_all(NDArray x)
Parameters
xNDArrayInput array. Flattened if it is not already 1-D.
Returns
- np.UniqueAllResult
A np.UniqueAllResult: (values, indices, inverse_indices, counts). A
numpy.char.chararrayoperand gives a chararray VIEW of the unique values (NumPy's_array_converter.wrap); the index arrays stay plain.
Remarks
Exceptions
- ValueError
A NEP 55
StringDTypearray whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy'sCannot compare null that is not a nan-like value.- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
unique_counts(NDArray)
Find the unique elements and counts of an input array x.
Array API compatible alternative to np.unique(x, return_counts=True, equal_nan=False).
The input is flattened. Each NaN is treated as a distinct value.
public static np.UniqueCountsResult unique_counts(NDArray x)
Parameters
xNDArrayInput array. Flattened if it is not already 1-D.
Returns
- np.UniqueCountsResult
A np.UniqueCountsResult: (values, counts). A
numpy.char.chararrayoperand gives a chararray VIEW of the unique values (NumPy's_array_converter.wrap); the index arrays stay plain.
Remarks
Exceptions
- ValueError
A NEP 55
StringDTypearray whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy'sCannot compare null that is not a nan-like value.- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
unique_inverse(NDArray)
Find the unique elements of x and the indices that reconstruct it.
Array API compatible alternative to np.unique(x, return_inverse=True, equal_nan=False).
The input is flattened. Each NaN is treated as a distinct value.
public static np.UniqueInverseResult unique_inverse(NDArray x)
Parameters
xNDArrayInput array. Flattened if it is not already 1-D.
Returns
- np.UniqueInverseResult
A np.UniqueInverseResult: (values, inverse_indices).
inverse_indiceshas the same shape asx, sonp.take(values, inverse_indices)reconstructs the input. Anumpy.char.chararrayoperand gives a chararray VIEW of the unique values (NumPy's_array_converter.wrap); the index arrays stay plain.
Remarks
Exceptions
- ValueError
A NEP 55
StringDTypearray whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy'sCannot compare null that is not a nan-like value.- MemoryError
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
unique_values(NDArray)
Returns the unique elements of an input array x.
Array API compatible alternative to np.unique(x, equal_nan=False, sorted=False).
The input is flattened. Each NaN is treated as a distinct value.
public static NDArray unique_values(NDArray x)
Parameters
xNDArrayInput array. Flattened if it is not already 1-D.
Returns
- NDArray
The unique elements of
x(dtype preserved). Anumpy.char.chararrayoperand gives a chararray VIEW of a text result (NumPy'sarray_wrap: OWNDATA False); a result of another dtype stays plain.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.unique_values.html
NumSharp returns the values SORTED (like np.unique(x, equal_nan=False)). For integer and
complex dtypes NumPy 2.4.2's sorted=False path returns them in a platform-specific hash
order that is not portable (both contain the same set); float dtypes are sorted on both sides.
The Array API leaves the order unspecified.
Exceptions
- MemoryError
A corrupt NEP 55
StringDTypecell (NumPy'sMemoryErrortext). AStringDTypearray otherwise computes without raising: NumPy's values-onlysorted=Falsepass hashes the texts and compares no NA (the values come back sorted here, NumPy's hash set keeps its own order — the same set).
unpackbits(NDArray, int?, long?, string)
Unpacks each uint8 element of an array into 8 binary-valued (0/1) uint8 elements along an axis — the inverse of packbits(NDArray, int?, string).
public static NDArray unpackbits(NDArray a, int? axis = null, long? count = null, string bitorder = "big")
Parameters
aNDArrayInput array. Must be uint8 (any other dtype raises); read in logical order for any memory layout.
axisint?Axis to unpack along.
null(NumPyNone) unpacks the C-order flattened array and returns a 1-D result.countlong?Number of output elements along
axis— undoes packing a non-multiple-of-8 size.nullunpacks everything (8·len); a non-negative value takes exactly that many bits (truncating, or zero-padding past the available bits); a negative value trims that many bits off the end (and must not exceed the available bits).bitorderstring"big"(default) or"little". Matched to NumPy's unpack rule: only the FIRST character is inspected ('l'⇒ little,'b'⇒ big);nullis"big".
Returns
- NDArray
A uint8 array of 0/1 values — same ndim as
a(exceptaxis=null⇒ 1-D), F-contiguous iffais.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html
<p>The body is
<xref href="NumSharp.TensorEngine.Unpackbits(NumSharp.NDArray%2cSystem.Nullable%7bSystem.Int32%7d%2cSystem.Nullable%7bSystem.Int64%7d%2cSystem.String)" data-throw-if-not-resolved="false"></xref> (the np-layer dtype plan); this facade keeps the <code>numpy.matrix</code>
rule.</p>
Exceptions
- ArgumentNullException
ais null.- ValueError
bitorderdoes not begin with 'l' or 'b', or-countexceeds the available bits.- TypeError
ais not uint8.- AxisError
axisis out of bounds fora's rank.- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
unravel_index(NDArray, Shape, char)
Converts a flat index or an array of flat indices into a tuple of coordinate arrays — NumPy's
arr_unravel_index (numpy/_core/src/multiarray/compiled_base.c), statement for statement.
Inverse of ravel_multi_index(NDArray[], Shape, string, char).
public static NDArray<long>[] unravel_index(NDArray indices, Shape shape, char order = 'C')
Parameters
indicesNDArrayAn integer (or bool) array of flat indices into an array of dimensions
shape, of any rank and layout. Read as int64: a uint64 index at or past 2^63 wraps negative and is out of bounds, as NumPy's same_kind cast to intp makes it.shapeShapeThe dimensions to unravel into: NumPy's idiom
np.unravel_index(np.argmax(a), a.shape)passesa.shape(along[]) ora.Shapeas it is, and anint[], a tuple or a collection expression converts. An empty shape (NumPy's()) is legal: its one valid index is 0, and only a 0-d index array may use it. Negative dimensions are kept (NumPy multiplies them in).orderchar'C'(row-major, the default) or'F'(column-major), in either case.
Returns
- NDArray<long>[]
One int64 array per dimension of
shape, each ofindices' shape — NumPy'sret_arr[..., j]: the COLUMNS of one interleaved buffer of shapeindices.shape + (len(shape),), so every array is a strided VIEW (OWNDATA false, element stridelen(shape)along the fastest axis) and they share that buffer. The buffer is laid out alongindices' iteration order: C for a C-ordered, broadcast or reversed index array, F for an F-ordered one, the same permutation for a transposed one. A 0-dindicesgives NumPy's scalars instead — fresh read-only 0-d arrays that own their value. An emptyshapewith a 0-d index gives an empty array (NumPy's()).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.unravel_index.html
BREAKING (NumPy parity): the coordinate arrays used to be separate owning C-contiguous arrays.
They are now views with an element stride of len(shape), so code that reads their raw buffer
(Storage.Address, Unsafe.Span) must go through the strides or take
np.ascontiguousarray first. An out-of-range index raises ValueError (NumPy's type)
where it raised ArgumentOutOfRangeException, and a lowercase order letter is accepted.
Lifetime: the shared buffer lives while any coordinate array does (each holds a counted reference); disposing one coordinate array leaves the others valid.
Iteration order: NumPy walks the indices with NpyIter (KEEPORDER,
DONT_NEGATE_STRIDES) and writes the coordinates of the k-th element it visits into the k-th row of
the buffer, which NpyIter_CreateCompatibleStrides lays out along that same order. NumSharp copies a
non-int64 or differently laid out index array into that layout (an int64 array already laid out so —
every C-contiguous one — is read in place) and runs one IL kernel over it linearly, so the rows, the
strides and the out-of-range index that is reported first are NumPy's.
The body is UnravelIndex(NDArray, long[], char) (the np-layer dtype plan): this facade computes
a numpy.matrix operand as a plain array and calls the operand's engine.
shape is a Shape since API-parity batch 13 (parity QA-56): it was an
int[], which neither a.shape (long[]) nor a.Shape converted to.
Exceptions
- ArgumentNullException
indicesis null.- ValueError
In NumPy's order:
orderis not one of C / F / A / K in either case (order must be one of 'C', 'F', 'A', or 'K' (got 'X'), the argument parse's error); the dimensions' product overflows int64 or is exactly -1 (dimensions are too large; …); then — after the TypeError below — an'A'or'K'order (only 'C' or 'F' order is permitted); an index outside[0, prod(shape)), the FIRST one in the iteration order (index N is out of bounds for array with size M; a shape with a zero or an odd number of negative dimensions has no valid index); and, for an emptyshape, an index array of rank 1 or more (multiple indices are not supported for 0d arrays, checked after the indices).- TypeError
indicesis neither integer nor bool (only int indices permitted; a float is refused, never truncated, and text is refused, never parsed).- NotSupportedException
Runtime code generation is unavailable (the IL kernel cannot be emitted).
unravel_index(long, Shape, char)
Scalar convenience overload — converts a single flat index into its coordinates, the values NumPy's
np.unravel_index(indices, shape, order) returns as a tuple of scalars, without NDArray wrapping.
public static long[] unravel_index(long indices, Shape shape, char order = 'C')
Parameters
indiceslongThe flat index (NumPy's keyword name,
indices, which also takes an array: an array binds unravel_index(NDArray, Shape, char)).shapeShapeThe dimensions to unravel into (
a.shape,a.Shape, anint[], a tuple); an empty shape (NumPy's()) accepts the index 0 and returns no coordinate.orderchar'C'(row-major, the default) or'F'(column-major), in either case.
Returns
- long[]
One coordinate per dimension of
shape.
Remarks
Named index before API-parity batch 7 (NumPy's keyword is indices). A named call
unravel_index(indices: 5L, shape: s) binds THIS overload since the rename (a long argument beats
its conversion to NDArray) and returns long[]; before, it bound the array form and returned
NDArray<long>[].
Exceptions
- ValueError
In NumPy's order: an order letter that is not C / F / A / K; a dimensions' product that overflows int64 or is exactly -1; an
'A'or'K'order (only 'C' or 'F' order is permitted); an index outside[0, prod(shape))(index N is out of bounds for array with size M).
unstack(NDArray, int)
Split an array into a sequence of arrays along the given axis.
The axis parameter specifies the dimension along
which the array will be split. For example, if axis=0 (the
default) it will be the first dimension and if axis=-1 it
will be the last dimension.
Added in NumPy 2.1.
public static NDArray[] unstack(NDArray x, int axis = 0)
Parameters
Returns
- NDArray[]
The unstacked arrays —
x.shape[axis]VIEWS intox(shared memory, matching NumPy), each with shape equal tox.shapewith theaxisentry removed. An emptyxgives empty views too. Anumpy.char.chararrayoperand of two or more dimensions gives chararray views (NumPy iterates the chararray); a 1-d one gives its elements as NumPy's iteration does, the read-only stand-ins of the Pythonstr/byteswith the trailing whitespace stripped.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.unstack.html
unstack serves as the reverse operation of stack(NDArray[], int, NDArray, DType, string):
stack(unstack(x, axis), axis) == x. Semantically equivalent to
NumPy's tuple(np.moveaxis(x, axis, 0)) — moving axis
to the front and then indexing it away leaves the remaining axes in
their original relative order, so each view is constructed directly
by dropping axis from dims/strides and advancing the offset
by i * strides[axis]; no iterator or data movement anywhere.
Exceptions
- ArgumentNullException
xis null.- ValueError
xis 0-d ("Input array must be at least 1-d.").- AxisError
axisis out of range: moveaxis' "source: axis … is out of bounds for array of dimension …".- ValueError
A
numpy.matrixoperand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).
unwrap(NDArray, double?, int, NDArray)
Unwrap p by changing deltas larger than max(discont, period/2) to their
period-complement, so adjacent differences never exceed period/2: NumPy's
unwrap(p, discont=None, axis=-1, , period=2pi), one signature in NumPy's order.
public static NDArray unwrap(NDArray p, double? discont = null, int axis = -1, NDArray period = null)
Parameters
pNDArrayInput array (at least one dimensional; a 0-D input is rejected exactly as NumPy's inner diff(NDArray, int, int, object, object) rejects it).
discontdouble?Maximum discontinuity between values.
null(the default) meansperiod/2. Values belowperiod/2have no effect: taking the complement of a jump smaller thanperiod/2would only enlarge it. A positional second argument is this one, as in NumPy:np.unwrap(a, 4)isdiscont=4.axisintAxis along which to unwrap; default is the last axis. Negative axes count from the end.
periodNDArraySize of the range over which the input wraps;
nullis NumPy's default2*pi. Its kind picks NumPy's path: a C# integer (NumPy's Python int) keeps an integer input integral (the interval half-width isperiod // 2, the boundary ambiguous only for an even period; a bool input gives int64); a C# double (a Python float) gives a float result that keeps a float input's width (an integer input gives float64). A NumPy scalar or a 0-d array is NumPy's STRONG period: the result dtype isresult_type(diff(p), period)(an int8 input withnp.int64(4)is int64, withnp.float32(4)float32). NumPy'speriodis keyword-only: writeperiod:.
Returns
- NDArray
A fresh, writeable, C-contiguous array of the unwrapped signal,
p's shape, the dtype described forperiod. Anumpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray, which drops the class.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.unwrap.html. One signature since API-parity batch 6:
the double period and long period overloads it replaced made a positional integer second
argument bind period (np.unwrap(a, 4) returned the period-4 unwrap, where NumPy reads
discont=4).
Exceptions
- ArgumentNullException
pis null.- ValueError
pis 0-D (propagated from diff(NDArray, int, int, object, object)).- AxisError
axisis out of bounds forp's rank.- TypeError
porperiodis complex (NumPy'smodhas no complex loop), orperiodis text (unsupported operand type(s) for /: 'str' and 'int').- OverflowError
An integer path whose negative
interval_low(or the period itself) the input's integer dtype cannot hold - every unsigned input, a too-narrow signed one (NumPy'sPython integer N out of bounds for <dtype>), raised for empty inputs too.- NotSupportedException
A
periodof several elements (NumPy broadcasts it into the elementwise steps), or a C# bool period over a boolp.
vander(NDArray, int?, bool)
Generate a Vandermonde matrix.
The columns of the output matrix are powers of the input vector. When
increasing is false (the default) the i-th output column is
the input vector raised element-wise to the power of N - i - 1.
public static NDArray vander(NDArray x, int? N = null, bool increasing = false)
Parameters
xNDArray1-D input array.
Nint?Number of columns. If
null, a square matrix is returned (N = len(x)).increasingboolIf
truethe powers increase left to right (x^0 ... x^(N-1)); iffalsethey are reversed (first columnx^(N-1)).
Returns
- NDArray
The Vandermonde matrix, shape
(len(x), N).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.vander.html
<p>NumPy's statements: <code>v = empty((len(x), N), dtype=promote_types(x.dtype, int))</code>; <code>if N > 0:
tmp[:, 0] = 1</code>; <code>if N > 1: tmp[:, 1:] = x[:, None]; multiply.accumulate(tmp[:, 1:], ...)</code>. A text
<code class="paramref">x</code> promotes to a 21-character string (int64 formatted), so its matrix is the empty allocation
for no columns or no rows with one column, the formatted <code>'1'</code> column otherwise for one column, and the
multiply's refusal from two columns on — for an empty <code class="paramref">x</code> too (the dtype decides).</p>
Exceptions
- ValueError
xis not one-dimensional, orNis negative (the allocation'snegative dimensions are not allowed).- TypeError
A text
xwith two or more columns: the powers come frommultiply.accumulate, which has no string loop.- DTypePromotionError
A 1-D
StringDTypex:promote_types(x.dtype, int)finds no common DType (The DTypes <class 'numpy.dtypes.StringDType'> and <class 'numpy.dtypes.Int64DType'> do not have a common DType. ...), whateverN.- ArgumentNullException
xis null.
var(NDArray, int, DType, NDArray, int, bool, NDArray, NDArray, int?)
var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) with the axis as
one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one),
forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.
public static NDArray var(NDArray a, int axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe values whose variance is desired.
axisintThe axis (NumPy's
axis=k; a negative value counts from the end).dtypeDTypeThe loop of both sums.
nullis NumPy's default: float64 for bool and integer input, the input's own dtype otherwise; an integer dtype truncates the mean, as in NumPy.outNDArrayThe array the variance is written into and returned (the result's shape). NumPy hands it to the LAST sum only (whose loop it joins) and divides it in place. Footgun: the FOURTH positional parameter, as in NumPy; write
ddof:andkeepdims:by name.ddofintDelta degrees of freedom: the divisor is
max(N - ddof, 0), soddof >= Ngives +inf (NaN when every deviation is 0), never a negative variance.keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask broadcast against
a: each output takes its selected elements only (its own count, mean and divisor). The C#trueliteral is NumPy's default.nullis no mask.meanNDArrayThe mean to subtract instead of computing it: an array that broadcasts against
a(the shapenp.mean(a, axis, keepdims: true)has), or a C# number standing for a Python scalar. Footgun: it is used as given, so the deviations takea - mean's dtype (an int32 array with an integer mean subtracts and squares in int32, wrapping), and a mean that broadcasts to a larger shape makes the result larger.nullcomputes it.correctionint?The Array API's name of
ddof: with it given,ddofmust be 0, and the variance divides bymax(N - correction, 0).nullis none.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.
Remarks
Exceptions
- ArgumentNullException
ais null.- ValueError
A nonzero
ddoftogether withcorrection(ddof and correction can't be provided simultaneously., raised first); a read-only or misshapenout. Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis out of bounds.- ArgumentException
whereis not a bool array (NumPy's TypeError text).- IncorrectShapeException
out,whereormeandoes not broadcast againsta.- TypeError
A bool input with
dtype: bool, or a boolmeanof a bool input (NumPy's boolean-subtract refusal); a C# scalar passed asout; NumPy's text refusals; anumpy.matrixoperand withkeepdims,whereormean(matrix.var() got an unexpected keyword argument 'keepdims').- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
var(NDArray, int[], DType, NDArray, int, bool, NDArray, NDArray, int?)
var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) with the axes as
an int[]: the overload an int[] binds, and a bare null too (null converts to
int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any
other array NumPy's tuple (new int[0] is ()).
public static NDArray var(NDArray a, int[] axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe values whose variance is desired.
axisint[]The axes as NumPy's tuple, or
nullfor None.dtypeDTypeThe loop of both sums.
nullis NumPy's default: float64 for bool and integer input, the input's own dtype otherwise; an integer dtype truncates the mean, as in NumPy.outNDArrayThe array the variance is written into and returned (the result's shape). NumPy hands it to the LAST sum only (whose loop it joins) and divides it in place. Footgun: the FOURTH positional parameter, as in NumPy; write
ddof:andkeepdims:by name.ddofintDelta degrees of freedom: the divisor is
max(N - ddof, 0), soddof >= Ngives +inf (NaN when every deviation is 0), never a negative variance.keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask broadcast against
a: each output takes its selected elements only (its own count, mean and divisor). The C#trueliteral is NumPy's default.nullis no mask.meanNDArrayThe mean to subtract instead of computing it: an array that broadcasts against
a(the shapenp.mean(a, axis, keepdims: true)has), or a C# number standing for a Python scalar. Footgun: it is used as given, so the deviations takea - mean's dtype (an int32 array with an integer mean subtracts and squares in int32, wrapping), and a mean that broadcasts to a larger shape makes the result larger.nullcomputes it.correctionint?The Array API's name of
ddof: with it given,ddofmust be 0, and the variance divides bymax(N - correction, 0).nullis none.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.
Remarks
Exceptions
- ArgumentNullException
ais null.- ValueError
A nonzero
ddoftogether withcorrection(ddof and correction can't be provided simultaneously., raised first); a read-only or misshapenout. Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis out of bounds.- ArgumentException
whereis not a bool array (NumPy's TypeError text).- IncorrectShapeException
out,whereormeandoes not broadcast againsta.- TypeError
A bool input with
dtype: bool, or a boolmeanof a bool input (NumPy's boolean-subtract refusal); a C# scalar passed asout; NumPy's text refusals; anumpy.matrixoperand withkeepdims,whereormean(matrix.var() got an unexpected keyword argument 'keepdims').- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)
Compute the variance along the specified axis — NumPy's np.var(a, axis=None, dtype=None, out=None, ddof=0,
keepdims=<no value>, *, where=<no value>, mean=<no value>, correction=<no value>)
(_methods._var): the mean of the squared deviations from the mean, divided by max(N - ddof, 0).
This is the only overload: NumPy's whole signature, with NumPy's names, order and defaults.
public static NDArray var(NDArray a, NDAxis? axis = null, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
aNDArrayThe values whose variance is desired.
axisNDAxis?The axis to compute along (negative counts from the end);
nulluses every element. A 0-d array takes no axis unlesswhereis a mask. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).dtypeDTypeThe loop of both sums.
nullis NumPy's default: float64 for bool and integer input, the input's own dtype otherwise; an integer dtype truncates the mean, as in NumPy.outNDArrayThe array the variance is written into and returned (the result's shape). NumPy hands it to the LAST sum only (whose loop it joins) and divides it in place. Footgun: the FOURTH positional parameter, as in NumPy; write
ddof:andkeepdims:by name.ddofintDelta degrees of freedom: the divisor is
max(N - ddof, 0), soddof >= Ngives +inf (NaN when every deviation is 0), never a negative variance.keepdimsboolKeep the reduced axes as length-1 dimensions.
whereNDArrayA bool mask broadcast against
a: each output takes its selected elements only (its own count, mean and divisor). The C#trueliteral is NumPy's default.nullis no mask.meanNDArrayThe mean to subtract instead of computing it: an array that broadcasts against
a(the shapenp.mean(a, axis, keepdims: true)has), or a C# number standing for a Python scalar. Footgun: it is used as given, so the deviations takea - mean's dtype (an int32 array with an integer mean subtracts and squares in int32, wrapping), and a mean that broadcasts to a larger shape makes the result larger.nullcomputes it.correctionint?The Array API's name of
ddof: with it given,ddofmust be 0, and the variance divides bymax(N - correction, 0).nullis none.
Returns
- NDArray
outitself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.
Remarks
Exceptions
- ArgumentNullException
ais null.- ValueError
A nonzero
ddoftogether withcorrection(ddof and correction can't be provided simultaneously., raised first); a read-only or misshapenout. Also a tuple that names an axis twice (duplicate value in 'axis').- AxisError
axisis out of bounds.- ArgumentException
whereis not a bool array (NumPy's TypeError text).- IncorrectShapeException
out,whereormeandoes not broadcast againsta.- TypeError
A bool input with
dtype: bool, or a boolmeanof a bool input (NumPy's boolean-subtract refusal); a C# scalar passed asout; NumPy's text refusals; anumpy.matrixoperand withkeepdims,whereormean(matrix.var() got an unexpected keyword argument 'keepdims').- AttributeError
A
numpy.matrixoperand with a plain (non-matrix)out.
vdot(NDArray, NDArray)
Dot product of two vectors, flattening both operands and conjugating the first.
public static NDArray vdot(NDArray a, NDArray b)
Parameters
Returns
- NDArray
A 0-d result, always —
vdotnever performs a matrix product. 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.vdot.html
Two differences from dot(NDArray, NDArray, NDArray): the first argument is replaced by its complex conjugate, and multi-dimensional operands are flattened rather than multiplied as matrices — so for two 2-D operands of the same shape this is their Frobenius inner product.
A length mismatch reports a RESHAPE error, not a length one. NumPy's
array_vdot flattens both operands through one reused PyArray_Dims buffer
holding a single -1; _fix_unknown_dimension writes the resolved length
back into that buffer, so the second flatten asks for (a.size,) rather than
(-1,). np.vdot(ones(3), ones(5)) therefore raises "cannot reshape array
of size 5 into shape (3,)", and the "vectors have different lengths" check that
follows it in the C source is unreachable.
vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char)
Vector dot product of two arrays (NumPy 2.0) — the gufunc (n),(n)->(),
conjugating the first operand.
public static NDArray vecdot(NDArray x1, NDArray x2, NDArray @out = null, int[][] axes = null, int? axis = null, bool keepdims = false, DType dtype = null, string casting = "same_kind", char order = 'K')
Parameters
x1NDArrayFirst operand. Conjugated when complex.
x2NDArraySecond operand.
outNDArrayWhere to deposit the answer. Returned as-is when given.
axesint[][]Which axes carry the core dimensions, per operand:
{x1, x2, out}. The output entry may be omitted here —vecdot's output has no core axes. Cannot be combined withaxis.axisint?The shared core axis, in place of the default last one. Applied to both operands — the special case of
axesthat this signature admits because both core dimensions are the SAME one.keepdimsboolLeave the contracted axis in the result with length 1.
dtypeDTypeSelects the LOOP: computation runs at this dtype, not merely the result.
castingstringNumPy's
casting=: the rule each input's cast to the loop, and the answer's cast intoout, is checked under -no,equiv,safe,same_kind(the default) orunsafe.ordercharNumPy's
order=, the layout of an allocated result:'K'(the default: the loop axes in the inputs' memory order),'C','F', or'A'(F when both inputs are F-contiguous, else C); lowercase is accepted, and it is ignored without.
Returns
- NDArray
The vector dot products (the operands' loop axes broadcast together), or
outitself holding them.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.vecdot.html
Unlike sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray), the accumulation happens in the LOOP dtype rather than
NEP50's wider accumulator: vecdot's registered loops are 'ii->i', so an
int32 pair reduces to int32 where np.sum would give int64.
Core dimensions do NOT broadcast — a length-1 core axis against a length-3 one is an error. Only the leading (loop) axes broadcast.
NumPy's subok and signature keywords are absent: subok concerns ndarray
subclasses, which the woven subclass path already decides, and signature is what
dtype does.
The whole call is the engine member TensorEngine.Vecdot(x1, x2, out, axes, axis, keepdims, dtype, casting, order)
since the np-layer dtype plan's P2; this function's woven subclass path answers for a numpy.matrix operand.
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 0-d operand; core axes of different lengths; anaxeslist of the wrong length; loop axes that do not broadcast together, or a read-onlyoutor one the answer does not broadcast into (NumPy's gufunc iterator texts).- TypeError
axiswithaxes; adtypewith details beyond its class; text operands or a textdtype(no vecdot loop).- AxisError
An
axesentry of the wrong length, or an axis out of range.- TypeError
An input cannot be cast to the loop, or the answer into
out, undercasting(NumPy's UFuncTypeError text:Cannot cast ufunc 'vecdot' input 0 from dtype('int32') to dtype('float64') with casting rule 'no').- ValueError
A
castingorordername NumPy refuses (casting first).- NullReferenceException
x1orx2is null.
vecmat(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char)
Vector-matrix product (NumPy 2.2) — the gufunc (n),(n,m)->(m), conjugating the
vector operand.
public static NDArray vecmat(NDArray x1, NDArray x2, NDArray @out = null, int[][] axes = null, int? axis = null, bool keepdims = false, DType dtype = null, string casting = "same_kind", char order = 'K')
Parameters
x1NDArrayVector operand, at least 1-D. Conjugated when complex.
x2NDArrayMatrix operand, at least 2-D. Leading axes broadcast.
outNDArrayWhere to deposit the answer. Returned as-is when given.
axesint[][]Which axes carry the core dimensions, per operand:
{(n), (n,m), (m)}. All THREE entries are required — the output has a core axis.axisint?Present for signature parity only. NumPy raises
TypeErrorfor any value — this signature's core dimensions are two DISTINCT ones; useaxes.keepdimsboolPresent for signature parity only. NumPy raises
TypeErrorwhen true.dtypeDTypeSelects the LOOP: computation runs at this dtype, not merely the result.
castingstringNumPy's
casting=: the rule each input's cast to the loop, and the answer's cast intoout, is checked under -no,equiv,safe,same_kind(the default) orunsafe.ordercharNumPy's
order=, the layout of an allocated result:'K'(the default: the loop axes in the inputs' memory order),'C','F', or'A'(F when both inputs are F-contiguous, else C); lowercase is accepted, and it is ignored without.
Returns
- NDArray
The vector-matrix products (the operands' loop axes broadcast together), or
outitself holding them.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.vecmat.html
The conjugation is what makes this the adjoint of matvec(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char) rather than its
mirror image: vecmat(v, m) is conj(v) @ m, so for real operands it is the
plain row-vector product and for complex ones it agrees with vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char)'s
convention.
NumPy's subok and signature keywords are absent: subok concerns ndarray
subclasses, which the woven subclass path already decides, and signature is what
dtype does.
The whole call is the engine member TensorEngine.Vecmat(x1, x2, out, axes, axis, keepdims, dtype, casting, order)
since the np-layer dtype plan's P2; this function's woven subclass path answers for a numpy.matrix operand.
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.); an operand with too few dimensions; core axes of different lengths; anaxeslist without three entries; loop axes that do not broadcast together, or a read-onlyoutor one the answer does not broadcast into (NumPy's gufunc iterator texts).- TypeError
axiswithaxes, or either given; adtypewith details beyond its class; text operands or a textdtype;keepdims.- AxisError
An
axesentry of the wrong length, or an axis out of range.- TypeError
An input cannot be cast to the loop, or the answer into
out, undercasting(NumPy's UFuncTypeError text:Cannot cast ufunc 'vecmat' input 0 from dtype('int32') to dtype('float64') with casting rule 'no').- ValueError
A
castingorordername NumPy refuses (casting first).- IncorrectShapeException
Loop axes that do not broadcast.
- NullReferenceException
x1orx2is null.
vectorize(Delegate, DType[])
Builds a Vectorized from any delegate — the general element-wise (no signature) form.
Reach it by casting a concrete delegate to Delegate (np.vectorize((Delegate)f));
a bare lambda binds the typed overloads instead. Supports any arity and multi-output (a
ValueTuple return) via CallMany(params NDArray[]).
public static Vectorized vectorize(Delegate pyfunc, DType[] otypes = null)
Parameters
pyfuncDelegateThe per-element function (any supported arity; may return a tuple for multi-output).
otypesDType[]Optional per-output dtype overrides (length must equal the output count).
Returns
- Vectorized
A Vectorized in element-wise mode.
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ArgumentException
A parameter is NDArray (needs a signature) or a return component is not a supported dtype.
- ValueError
otypeslength does not match the output count.
vectorize(Delegate, string, DType[])
Builds a signature-mode Vectorized from any delegate — the general gufunc form for arities or multi-output shapes the typed signature overloads do not spell. Reach it by casting to Delegate.
public static Vectorized vectorize(Delegate pyfunc, string signature, DType[] otypes = null)
Parameters
pyfuncDelegateApplied to core sub-arrays; must take/return NDArray (a tuple / array for multi-output).
signaturestringThe gufunc signature; its input arity must equal the delegate's parameter count.
otypesDType[]Optional per-output dtype overrides.
Returns
- Vectorized
A Vectorized in signature mode.
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ValueError
signatureis malformed or its input arity mismatches the delegate.
vectorize(Func<NDArray, NDArray, NDArray, NDArray>, string, DType[])
Builds a signature (gufunc) vectorizer over a three-argument function on NDArray core sub-arrays.
public static Vectorized vectorize(Func<NDArray, NDArray, NDArray, NDArray> pyfunc, string signature, DType[] otypes = null)
Parameters
pyfuncFunc<NDArray, NDArray, NDArray, NDArray>Applied to each triple of core sub-arrays.
signaturestringThe gufunc signature (input side must have exactly three arguments).
otypesDType[]Optional per-output dtype overrides.
Returns
- Vectorized
A Vectorized in signature mode.
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ValueError
signatureis malformed or its input arity is not 3.
vectorize(Func<NDArray, NDArray, NDArray>, string, DType[])
Builds a signature (gufunc) vectorizer over a two-argument function on NDArray core sub-arrays (e.g. "(m,n),(n)->(m)").
public static Vectorized vectorize(Func<NDArray, NDArray, NDArray> pyfunc, string signature, DType[] otypes = null)
Parameters
pyfuncFunc<NDArray, NDArray, NDArray>Applied to each pair of core sub-arrays.
signaturestringThe gufunc signature (input side must have exactly two arguments).
otypesDType[]Optional per-output dtype overrides.
Returns
- Vectorized
A Vectorized in signature mode.
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ValueError
signatureis malformed or its input arity is not 2.
vectorize(Func<NDArray, NDArray>, string, DType[])
Builds a signature (gufunc) vectorizer over a one-argument function that consumes and returns
NDArray core sub-arrays — e.g. signature: "(n)->()" to reduce each 1-D slice.
Call Call(params NDArray[]) (single output) or CallMany(params NDArray[]) (a tuple / array return).
public static Vectorized vectorize(Func<NDArray, NDArray> pyfunc, string signature, DType[] otypes = null)
Parameters
pyfuncFunc<NDArray, NDArray>Applied to each core sub-array; receives an NDArray of the input core shape.
signaturestringThe gufunc signature (input side must have exactly one argument to match the arity).
otypesDType[]Optional per-output dtype overrides; when absent the first result's dtype is used.
Returns
- Vectorized
A Vectorized in signature mode.
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ValueError
signatureis malformed or its input arity is not 1.
vectorize<T1, TR>(Func<T1, TR>, DType[])
Vectorizes a one-argument scalar function into a broadcasting element-wise operation. The returned
delegate reads like NumPy's vfunc(a): apply it to an array of any layout and it returns a fresh
array of TR whose shape is the input's.
public static Func<NDArray, NDArray> vectorize<T1, TR>(Func<T1, TR> pyfunc, DType[] otypes = null)
Parameters
pyfuncFunc<T1, TR>The per-element function.
otypesDType[]Optional single output-dtype override (a trailing cast); usually unnecessary since
TRalready fixes the dtype.
Returns
Type Parameters
T1The element type the function consumes; inputs are cast to it (NEP50 at the edge).
TRThe element type the function returns; the result array's dtype (unless
otypesoverrides).
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ArgumentException
TRis not one of the 15 supported dtypes.
vectorize<T1, TR1, TR2>(Func<T1, (TR1, TR2)>, DType[])
Vectorizes a one-argument function returning TWO components; call the result's CallMany(params NDArray[]) for both outputs.
public static Vectorized vectorize<T1, TR1, TR2>(Func<T1, (TR1, TR2)> pyfunc, DType[] otypes = null)
Parameters
pyfuncFunc<T1, (TR1, TR2)>The per-element function returning a 2-tuple.
otypesDType[]Optional per-output dtype overrides (length 2 if given).
Returns
- Vectorized
A Vectorized producing two arrays.
Type Parameters
T1Argument element type.
TR1First output element type.
TR2Second output element type.
Exceptions
- ArgumentNullException
pyfuncis null.- ArgumentException
A return component is not a supported dtype.
- ValueError
otypeslength is not 2.
vectorize<T1, T2, TR>(Func<T1, T2, TR>, DType[])
Vectorizes a two-argument scalar function into a broadcasting element-wise operation. The two inputs
broadcast together (NumPy rules); the returned delegate reads like vfunc(a, b).
public static Func<NDArray, NDArray, NDArray> vectorize<T1, T2, TR>(Func<T1, T2, TR> pyfunc, DType[] otypes = null)
Parameters
pyfuncFunc<T1, T2, TR>The per-element function.
otypesDType[]Optional single output-dtype override.
Returns
- Func<NDArray, NDArray, NDArray>
A delegate applying
pyfuncelement-wise across the broadcast of its two inputs.
Type Parameters
T1First argument's element type.
T2Second argument's element type.
TRReturn element type (the result dtype unless
otypesoverrides).
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ArgumentException
TRis not one of the 15 supported dtypes.
vectorize<T1, TR1, TR2, TR3>(Func<T1, (TR1, TR2, TR3)>, DType[])
Vectorizes a one-argument function returning THREE components; call the result's CallMany(params NDArray[]) for all outputs.
public static Vectorized vectorize<T1, TR1, TR2, TR3>(Func<T1, (TR1, TR2, TR3)> pyfunc, DType[] otypes = null)
Parameters
pyfuncFunc<T1, (TR1, TR2, TR3)>The per-element function returning a 3-tuple.
otypesDType[]Optional per-output dtype overrides (length 3 if given).
Returns
- Vectorized
A Vectorized producing three arrays.
Type Parameters
T1Argument element type.
TR1First output element type.
TR2Second output element type.
TR3Third output element type.
Exceptions
- ArgumentNullException
pyfuncis null.- ArgumentException
A return component is not a supported dtype.
- ValueError
otypeslength is not 3.
vectorize<T1, T2, TR1, TR2>(Func<T1, T2, (TR1, TR2)>, DType[])
Vectorizes a two-argument function returning TWO components; the inputs broadcast together and CallMany(params NDArray[]) returns both outputs.
public static Vectorized vectorize<T1, T2, TR1, TR2>(Func<T1, T2, (TR1, TR2)> pyfunc, DType[] otypes = null)
Parameters
pyfuncFunc<T1, T2, (TR1, TR2)>The per-element function returning a 2-tuple.
otypesDType[]Optional per-output dtype overrides (length 2 if given).
Returns
- Vectorized
A Vectorized producing two arrays.
Type Parameters
T1First argument element type.
T2Second argument element type.
TR1First output element type.
TR2Second output element type.
Exceptions
- ArgumentNullException
pyfuncis null.- ArgumentException
A return component is not a supported dtype.
- ValueError
otypeslength is not 2.
vectorize<T1, T2, T3, TR>(Func<T1, T2, T3, TR>, DType[])
Vectorizes a three-argument scalar function into a broadcasting element-wise operation (all three inputs broadcast together).
public static Func<NDArray, NDArray, NDArray, NDArray> vectorize<T1, T2, T3, TR>(Func<T1, T2, T3, TR> pyfunc, DType[] otypes = null)
Parameters
pyfuncFunc<T1, T2, T3, TR>The per-element function.
otypesDType[]Optional single output-dtype override.
Returns
- Func<NDArray, NDArray, NDArray, NDArray>
A delegate applying
pyfuncelement-wise across the broadcast of its three inputs.
Type Parameters
T1First argument's element type.
T2Second argument's element type.
T3Third argument's element type.
TRReturn element type.
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ArgumentException
TRis not one of the 15 supported dtypes.
vectorize<T1, T2, T3, T4, TR>(Func<T1, T2, T3, T4, TR>, DType[])
Vectorizes a four-argument scalar function into a broadcasting element-wise operation (all four
inputs broadcast together) — the widest element-wise arity with a typed Func return. For more
inputs, build a Vectorized via vectorize(Delegate, DType[]) and call .Call.
public static Func<NDArray, NDArray, NDArray, NDArray, NDArray> vectorize<T1, T2, T3, T4, TR>(Func<T1, T2, T3, T4, TR> pyfunc, DType[] otypes = null)
Parameters
pyfuncFunc<T1, T2, T3, T4, TR>The per-element function.
otypesDType[]Optional single output-dtype override.
Returns
- Func<NDArray, NDArray, NDArray, NDArray, NDArray>
A delegate applying
pyfuncelement-wise across the broadcast of its four inputs.
Type Parameters
T1First argument's element type.
T2Second argument's element type.
T3Third argument's element type.
T4Fourth argument's element type.
TRReturn element type.
Remarks
Exceptions
- ArgumentNullException
pyfuncis null.- ArgumentException
TRis not one of the 15 supported dtypes.
vsplit(NDArray, int)
Split an array into multiple sub-arrays vertically (row-wise).
public static NDArray[] vsplit(NDArray ary, int indices_or_sections)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintIf an integer, N, the array will be divided into N equal arrays along axis 0. If such a split is not possible, an error is raised.
Returns
- NDArray[]
A list of sub-arrays as views into ary. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
Equivalent to split with axis=0. Array must have ndim >= 2. https://numpy.org/doc/stable/reference/generated/numpy.vsplit.html
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.).- ArgumentException
aryhas fewer than two dimensions ("vsplit only works on arrays of 2 or more dimensions"; NumPy raises the text as a ValueError).- ValueError
The sections are not positive ("number sections must be larger than 0."), or do not divide the axis ("array split does not result in an equal division").
- NullReferenceException
aryis null (its rank is read first).
vsplit(NDArray, int[])
Split an array into multiple sub-arrays vertically (row-wise).
public static NDArray[] vsplit(NDArray ary, int[] indices)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indicesint[]A 1-D array of sorted integers indicating where along axis 0 the array is split. For example, [2, 3] would result in ary[:2], ary[2:3], ary[3:].
Returns
- NDArray[]
A list of sub-arrays as views into ary. A
numpy.char.chararrayoperand gives chararrays over the results (NumPy creates them as the subclass).
Remarks
Equivalent to split with axis=0. Array must have ndim >= 2. https://numpy.org/doc/stable/reference/generated/numpy.vsplit.html
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.).- ArgumentException
aryhas fewer than two dimensions ("vsplit only works on arrays of 2 or more dimensions"; NumPy raises the text as a ValueError).- ArgumentNullException
indicesis null (checked after the rank).- NullReferenceException
aryis null (its rank is read first).
vstack(params NDArray[])
Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays of shape(N,) have been reshaped to(1, N). Rebuilds arrays divided by vsplit.
public static NDArray vstack(params NDArray[] tup)
Parameters
tupNDArray[]The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.
Returns
- NDArray
The array formed by stacking the given arrays, will be at least 2-D. A
numpy.char.chararrayoperand gives a plain array: NumPy converts it withasarray(or ends withnp.concatenate), which drops the class.
Remarks
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.).- ArgumentNullException
tupis null.- ValueError
tupis empty ("need at least one array to concatenate").
vstack(NDArray[], DType, string)
NumPy's vstack(tup, *, dtype=None, casting='same_kind'): stack the arrays in sequence vertically (1-D
arrays become rows), with np.concatenate's dtype / casting.
public static NDArray vstack(NDArray[] tup, DType dtype = null, string casting = "same_kind")
Parameters
tupNDArray[]The arrays (NumPy's sequence): the same shape along all but the first axis; 1-D arrays the same length.
dtypeDTypeThe result dtype handed to np.concatenate, or null for the arrays' promoted dtype.
castingstringThe casting rule handed to np.concatenate (
'no','equiv','safe','same_kind'or'unsafe').
Returns
- NDArray
The array formed by stacking the given arrays, at least 2-D (a
numpy.matrixoperand gives a matrix; a chararray a plain array).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.vstack.html
<p>NumPy's keywords beside NumSharp's <code>params</code> form, which the owner kept (API-parity batch 3): C#
allows nothing after a <code>params</code> array, so <code>np.vstack(a, b)</code> stays and <code>np.vstack(new[] { a, b },
dtype: np.int8, casting: "unsafe")</code> binds here. A plain array argument with no keyword binds here too;
both answer alike.</p>
Exceptions
- ArgumentNullException
tupis null.- ValueError
tupis empty ("need at least one array to concatenate"); anumpy.matrixresult of more than two long axes.- InvalidCastException
An array that does not cast to
dtypeundercasting(np.concatenate's refusal with NumPy's text; NumPy's type is TypeError, pinned inOpenBugs.ApiParity.cs).
vstack(NDListArray[])
NumPy's vstack(tup) over object arrays of Python lists - np.char.split's NDListArray
results: atleast_2d of each, then a concatenation along the first axis, the lists SHARED as NumPy's
object pointers are (np.vstack(new[] { a, b }) of two split results is the (2, n) object array of
their lists).
public static NDListArray vstack(NDListArray[] tup)
Parameters
tupNDListArray[]The list arrays (NumPy's sequence), the same shape along all but the first axis after
atleast_2d.
Returns
- NDListArray
A new object array of the lists, at least 2-D, owning its pointers.
Remarks
A sequence parameter, not params: a second params form would make NumPy's np.vstack()
(an empty tuple) ambiguous in C#. NumPy's dtype / casting only raise over lists (or turn them
into truth values), so this form has neither. API-parity batch 12, with np.row_stack.
Exceptions
- ArgumentNullException
tupor one of its arrays is null.- ValueError
No array (
need at least one array to concatenate); arrays whose other axes differ (np.concatenate's text).- NotSupportedException
A bytes list beside str lists (NumSharp's lists hold one class per family).
- ObjectDisposedException
One of the arrays was disposed.
where(NDArray)
Equivalent to nonzero(NDArray): returns the indices where
condition is non-zero.
public static NDArray<long>[] where(NDArray condition)
Parameters
conditionNDArrayInput array. Non-zero entries yield their indices.
Returns
Remarks
where(NDArray, NDArray, NDArray)
Return elements chosen from x or y depending on condition.
public static NDArray where(NDArray condition, NDArray x, NDArray y)
Parameters
conditionNDArrayWhere True, yield
x, otherwise yieldy.xNDArrayValues from which to choose where condition is True.
yNDArrayValues from which to choose where condition is False.
Returns
- NDArray
An array with elements from
xwhereconditionis True, and elements fromyelsewhere.
Remarks
where(NDArray, NDArray, object)
Return elements chosen from x or y depending on condition.
Scalar overload for y.
public static NDArray where(NDArray condition, NDArray x, object y)
Parameters
Returns
where(NDArray, object, NDArray)
Return elements chosen from x or y depending on condition.
Scalar overload for x.
public static NDArray where(NDArray condition, object x, NDArray y)
Parameters
Returns
where(NDArray, object, object)
Return elements chosen from x or y depending on condition.
Scalar overload for both x and y.
public static NDArray where(NDArray condition, object x, object y)
Parameters
Returns
zeros(Shape, DType, char, string)
Return a new array of given shape and type, filled with zeros — NumPy's one signature,
np.zeros(shape, dtype=None, order='C', *, device=None).
public static NDArray zeros(Shape shape, DType dtype = null, char order = 'C', string device = null)
Parameters
shapeShapeThe dimensions: an int (
2), a tuple ((2, 3)), anint[]/long[]or a Shape (all convert implicitly). Only the dimensions are read: the layout comes fromorder, as NumPy's shape is a tuple of ints — a Shape taken from a transposed view gives a C-ordered array unlessordersays'F'.dtypeDTypeThe desired dtype — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType (uint8) all convert implicitly. Null (NumPy's None) is float64.orderchar'C'(row-major, the default) or'F'(column-major), in either case. NumPy's'A'and'K'mean nothing without a source array and are refused. The fill is order-independent, so only the layout (strides, flags) differs.devicestringNull or
"cpu"(the Array-API device; NumPy has no other).
Returns
- NDArray
A new, owned, writeable array of zeros (empty strings for a text dtype).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.zeros.html — NumPy's array_zeros
(multiarraymodule.c), whose argument handling is CreationLayout(Shape, char, string).
One signature since API-parity batch 8 (2026-11-12): the int / int[] / long[] /
Shape-only overloads, the (Shape, DType dtype, string device) form whose dtype was required (so
np.zeros(s, device: "cpu") did not compile) and the (Shape, char order, DType) form with the order
before the dtype all went, as did the generic zeros<T> forms (write the dtype:
np.zeros(shape, np.float64)). A positional char after the shape no longer compiles: NumPy reads
np.zeros(s, 'F')'s 'F' as the DTYPE (complex64), so write order: 'F'.
Exceptions
- ValueError
In NumPy's order:
orderis not one of C, F, A, K (order must be one of 'C', 'F', 'A', or 'K' (got 'X'));deviceis not"cpu"(Device not understood. Only "cpu" is allowed, but received: gpu);orderis A or K (only 'C' or 'F' order is permitted); a negative dimension (negative dimensions are not allowed) or a byte count past the allocation limit.- NotSupportedException
dtypenames a class NumSharp has no storage for.
zeros_like(NDArray, DType, char, Shape?, string)
Return an array of zeros with the same shape and type as a given array: NumPy's
zeros_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None).
public static NDArray zeros_like(NDArray a, DType dtype = null, char order = 'K', Shape? shape = null, string device = null)
Parameters
aNDArrayThe shape and data-type of
adefine these same attributes of the returned array.dtypeDTypeOverrides the data type of the result, or null for
a's.ordercharMemory layout:
'C','F','A'(F whenais F-contiguous and not C-contiguous, else C) or'K'(the default:a's axis order, kept also for ashapeof the same rank), in either case.shapeShape?Overrides the shape of the result (an int, an int[] or a tuple converts to Shape), or null for
a's. With'K'and a different rank the result is C-ordered, as NumPy's.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity; NumPy's is keyword-only).
Returns
- NDArray
A new, owned, writeable array of zeros (a text dtype's empty strings) in the requested layout. A
numpy.char.chararrayoperand gives a chararray (NumPy allocates the result as the subclass).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.zeros_like.html
<p>One signature in NumPy's order (API-parity batch 3, 2026-11-11): it replaces the former <code>(a, dtype, device)</code> / <code>(a, dtype, order, device)</code> pair,
so <code>order</code> no longer needs a <code>dtype</code> before it and <code>shape</code> takes None; a positional
<code>device</code> is written <code>device: "cpu"</code>. <code>subok</code> stays out (the parity plan's
exclusion).</p>
Exceptions
- ValueError
orderis not one of C, F, A, K in either case (order must be one of 'C', 'F', 'A', or 'K' (got 'Z')), reported before the device, as NumPy's empty_like converts its arguments in order;deviceis neither null nor"cpu"(NumPy'sDevice not understood. Only "cpu" is allowed, but received: ...); a negative dimension inshape(negative dimensions are not allowed); anumpy.matrixoperand whose result cannot be a matrix (shape too large to be a matrix.).- ValueError
A
numpy.char.chararrayoperand with a dtype that is not string data: NumPy's finalize error (Can only create a chararray from string data.), before anything is filled.- NullReferenceException
ais null (its layout is read after the order and device checks).