Table of Contents

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

DType

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

DType

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

DType

byte

public static readonly DType @byte

Field Value

DType

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

DType

cdouble

public static readonly DType cdouble

Field Value

DType

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

DType

complex128

public static readonly DType complex128

Field Value

DType

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: np.complex_ was removed in the NumPy 2.0 release. Use np.complex128 instead.). New code writes complex128.

public static readonly DType complex_

Field Value

DType

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

DType

double

public static readonly DType @double

Field Value

DType

float16

public static readonly DType float16

Field Value

DType

float32

public static readonly DType float32

Field Value

DType

float64

public static readonly DType float64

Field Value

DType

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: np.float_ was removed in the NumPy 2.0 release. Use np.float64 instead.). New code writes float64.

public static readonly DType float_

Field Value

DType

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

DType

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

DType

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

DType

int32

public static readonly DType int32

Field Value

DType

int64

public static readonly DType int64

Field Value

DType

int8

public static readonly DType int8

Field Value

DType

int_

public static readonly DType int_

Field Value

DType

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

DType

intp

public static readonly DType intp

Field Value

DType

long

public static readonly DType @long

Field Value

DType

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

DType

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

DType

newaxis

A convenient alias for None, useful for indexing arrays.

public static readonly Slice newaxis

Field Value

Slice

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

DType

short

public static readonly DType @short

Field Value

DType

single

public static readonly DType single

Field Value

DType

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

DType

ubyte

public static readonly DType ubyte

Field Value

DType

uint

public static readonly DType @uint

Field Value

DType

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

DType

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

DType

uint32

public static readonly DType uint32

Field Value

DType

uint64

public static readonly DType uint64

Field Value

DType

uint8

public static readonly DType uint8

Field Value

DType

uintc

numpy.uintc (C unsigned int, char 'I'): its own class on Windows, uint32 elsewhere (see intc).

public static readonly DType uintc

Field Value

DType

uintp

public static readonly DType uintp

Field Value

DType

ulong

public static readonly DType @ulong

Field Value

DType

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

DType

ushort

public static readonly DType @ushort

Field Value

DType

Properties

BackendEngine

public static BackendType BackendEngine { get; set; }

Property Value

BackendType

False_

numpy.False_: NumPy's bool scalar False — the C# false (see True_).

public static bool False_ { get; }

Property Value

bool

Inf

public static double Inf { get; }

Property Value

double

Infinity

public static double Infinity { get; }

Property Value

double

NAN

public static double NAN { get; }

Property Value

double

NINF

public static double NINF { get; }

Property Value

double

NaN

public static double NaN { get; }

Property Value

double

PINF

public static double PINF { get; }

Property Value

double

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

IReadOnlyList<NDScalarType>

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

bool

c_

Builds arrays by stacking columns — see np.CClass.

public static np.CClass c_ { get; }

Property Value

np.CClass

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

CharModule

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

NDScalarType

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

DType

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

NDScalarType

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

NDScalarType

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

NDScalarType

e

public static double e { get; }

Property Value

double

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

EmathModule

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

double

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

FourierModule

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

NDScalarType

Remarks

Abstract: converting it to a dtype raises Converting np.generic to a dtype is not allowed. (NumPy's text for both classes).

floating

numpy.floating: float16, float32, float64, and NumSharp's decimal.

public static NDScalarType floating { get; }

Property Value

NDScalarType

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

NDScalarType

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

np.IndexExpression

Remarks

inexact

numpy.inexact: the floating-point and complex classes (the dtypes with a np.finfo).

public static NDScalarType inexact { get; }

Property Value

NDScalarType

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

double

infinity

public static double infinity { get; }

Property Value

double

infty

public static double infty { get; }

Property Value

double

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

NDScalarType

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

bool

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

MaskedArrayModule

Remarks

mgrid

Returns a dense multi-dimensional "meshgrid" when indexed — see np.MGridClass.

public static np.MGridClass mgrid { get; }

Property Value

np.MGridClass

Remarks

nan

public static double nan { get; }

Property Value

double

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

NDScalarType

Remarks

Abstract: converting it to a dtype raises NumPy's Converting np.inexact or np.floating to a dtype not allowed (NumPy's own text names those two classes for np.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

NDScalarType

ogrid

Returns an open multi-dimensional "meshgrid" when indexed — see np.OGridClass.

public static np.OGridClass ogrid { get; }

Property Value

np.OGridClass

Remarks

pi

public static double pi { get; }

Property Value

double

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

PolynomialModule

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

np.RClass

Remarks

random

public static NumPyRandom random { get; }

Property Value

NumPyRandom

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

np.IndexExpression

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

IReadOnlyDictionary<string, DType>

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

NDScalarType

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

IReadOnlyDictionary<string, string>

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

NDScalarType

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

NDScalarType

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

a NDArray

Input value.

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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 out itself 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.matrix operand 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

a NDArray

Input value.

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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 out itself 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.matrix operand 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

x NDArray

Input array (a C# scalar converts to a 0-d array marked as the Python scalar it stands for).

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

The loop dtype (NumPy ufunc dtype=); only non-integer dtypes have a loop.

Returns

NDArray

The result of arccos(NDArray, NDArray, NDArray, DType): out itself 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.matrix operand 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

x NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x1 NDArray
x2 NDArray
out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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

a NDArray

Input 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

a is null.

SystemError

A U array 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

a NDArray

Input array (any dtype; a text element is true when non-empty).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

NumPy's out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an int out stores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.all(a, 0, true)) is NumPy's TypeError: return arrays must be of ArrayType: write keepdims: true.

keepdims bool

If True, the reduced axes are left as dimensions with size one, so the result broadcasts against a.

where NDArray

NumPy's where=: a bool mask that broadcasts TO a's shape. Elements where it is False are left out of the reduction (they count as True, the identity of all). A mask of any other dtype raises, as in NumPy. Null for no mask.

Returns

NDArray

out itself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (an NDArray<bool> instance: AsGeneric<bool>() gives the typed view), read-only when 0-d (NumPy's np.bool scalar). A numpy.matrix operand gives NumPy's matrix.all answer: 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

a is null.

ValueError

out is read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts); where has more axes than a or would make a stretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).

ArgumentException

where is not a bool array (NumPy's TypeError text: the mask must cast to bool under the safe rule).

AxisError

An axis is out of bounds (the first one in order, as given).

IncorrectShapeException

where or out does not broadcast against a.

TypeError

out is a C# scalar (return arrays must be of ArrayType); a numpy.matrix operand with keepdims: true or a mask: NumPy calls the matrix method, which has no such keyword (matrix.all() got an unexpected keyword argument 'keepdims'), or with an out (Cannot construct a dtype from an array).

SystemError

A U array 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

a NDArray

Input array (any dtype; a text element is true when non-empty).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

NumPy's out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an int out stores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.all(a, 0, true)) is NumPy's TypeError: return arrays must be of ArrayType: write keepdims: true.

keepdims bool

If True, the reduced axes are left as dimensions with size one, so the result broadcasts against a.

where NDArray

NumPy's where=: a bool mask that broadcasts TO a's shape. Elements where it is False are left out of the reduction (they count as True, the identity of all). A mask of any other dtype raises, as in NumPy. Null for no mask.

Returns

NDArray

out itself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (an NDArray<bool> instance: AsGeneric<bool>() gives the typed view), read-only when 0-d (NumPy's np.bool scalar). A numpy.matrix operand gives NumPy's matrix.all answer: 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

a is null.

ValueError

out is read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts); where has more axes than a or would make a stretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).

ArgumentException

where is not a bool array (NumPy's TypeError text: the mask must cast to bool under the safe rule).

AxisError

An axis is out of bounds (the first one in order, as given).

IncorrectShapeException

where or out does not broadcast against a.

TypeError

out is a C# scalar (return arrays must be of ArrayType); a numpy.matrix operand with keepdims: true or a mask: NumPy calls the matrix method, which has no such keyword (matrix.all() got an unexpected keyword argument 'keepdims'), or with an out (Cannot construct a dtype from an array).

SystemError

A U array 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

a NDArray

Input array (any dtype; a text element is true when non-empty).

axis NDAxis?

NumPy's axis: null (None, the default) reduces every axis; one axis (0, -1) reduces that axis; a tuple ((0, 2) or new[] { 0, 2 }) reduces each of its axes, and the empty tuple reduces none (the truth values in a's shape). Negative axes count from the end. A 0-d a takes the integer axis 0 or -1 (the ufunc reduction's special case) and the empty tuple.

out NDArray

NumPy's out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an int out stores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.all(a, 0, true)) is NumPy's TypeError: return arrays must be of ArrayType: write keepdims: true.

keepdims bool

If True, the reduced axes are left as dimensions with size one, so the result broadcasts against a.

where NDArray

NumPy's where=: a bool mask that broadcasts TO a's shape. Elements where it is False are left out of the reduction (they count as True, the identity of all). A mask of any other dtype raises, as in NumPy. Null for no mask.

Returns

NDArray

out itself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (an NDArray<bool> instance: AsGeneric<bool>() gives the typed view), read-only when 0-d (NumPy's np.bool scalar). A numpy.matrix operand gives NumPy's matrix.all answer: 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

a is null.

ValueError

out is read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts); where has more axes than a or would make a stretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).

ArgumentException

where is not a bool array (NumPy's TypeError text: the mask must cast to bool under the safe rule).

AxisError

An axis is out of bounds (the first one in order, as given).

IncorrectShapeException

where or out does not broadcast against a.

TypeError

out is a C# scalar (return arrays must be of ArrayType); a numpy.matrix operand with keepdims: true or a mask: NumPy calls the matrix method, which has no such keyword (matrix.all() got an unexpected keyword argument 'keepdims'), or with an out (Cannot construct a dtype from an array).

SystemError

A U array 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

a NDArray

Input array to compare with b

b NDArray

Input array to compare with a.

rtol double

The relative tolerance parameter(see Notes)

atol double

The absolute tolerance parameter(see Notes)

equal_nan bool

Whether to compare NaN's as equal. If True, NaN's in a will be considered equal to NaN's in b in the output array.

Returns

bool

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

a NDArray

Input data. A NaN propagates.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null; requires initial.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer (see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)).

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.max() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does 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

a NDArray

Input data. A NaN propagates.

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null; requires initial.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer (see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)).

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.max() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does 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

a NDArray

Input data. A NaN propagates.

axis NDAxis?

The axis to reduce (negative counts from the end), or null for 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).

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null; requires initial.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer (see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)).

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.max() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does 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

a NDArray

Input data. A NaN propagates.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.amin(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null.

where NDArray

A bool mask of the elements to reduce, or null; requires initial.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer (see min(NDArray, NDAxis?, NDArray, bool, object, NDArray)).

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does 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

a NDArray

Input data. A NaN propagates.

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.amin(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null.

where NDArray

A bool mask of the elements to reduce, or null; requires initial.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer (see min(NDArray, NDAxis?, NDArray, bool, object, NDArray)).

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does 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

a NDArray

Input data. A NaN propagates.

axis NDAxis?

The axis to reduce (negative counts from the end), or null for 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).

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.amin(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null.

where NDArray

A bool mask of the elements to reduce, or null; requires initial.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer (see min(NDArray, NDAxis?, NDArray, bool, object, NDArray)).

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does 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

z NDArray

A complex number or sequence of complex numbers (any real dtype is also accepted).

deg bool

Return the angle in degrees if true, radians (default) if false.

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 yields 0 for a positive value and pi for 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

TypeError

Text: arctan2 has no string loop (NumPy's no-loop text for StringDType, the legacy resolver's text for S / U).

any(NDArray)

Test whether any array element evaluates to True.

public static bool any(NDArray a)

Parameters

a NDArray

Input 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

a is null.

SystemError

A U array 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

a NDArray

Input array (any dtype; a text element is true when non-empty).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

NumPy's out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an int out stores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.any(a, 0, true)) is NumPy's TypeError: return arrays must be of ArrayType: write keepdims: true.

keepdims bool

If True, the reduced axes are left as dimensions with size one, so the result broadcasts against a.

where NDArray

NumPy's where=: a bool mask that broadcasts TO a's shape. Elements where it is False are left out of the reduction (they count as False, the identity of any). A mask of any other dtype raises, as in NumPy. Null for no mask.

Returns

NDArray

out itself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (an NDArray<bool> instance: AsGeneric<bool>() gives the typed view), read-only when 0-d (NumPy's np.bool scalar). A numpy.matrix operand gives NumPy's matrix.any answer: 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

a is null.

ValueError

out is read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts); where has more axes than a or would make a stretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).

ArgumentException

where is not a bool array (NumPy's TypeError text: the mask must cast to bool under the safe rule).

AxisError

An axis is out of bounds (the first one in order, as given).

IncorrectShapeException

where or out does not broadcast against a.

TypeError

out is a C# scalar (return arrays must be of ArrayType); a numpy.matrix operand with keepdims: true or a mask: NumPy calls the matrix method, which has no such keyword (matrix.any() got an unexpected keyword argument 'keepdims'), or with an out (Cannot construct a dtype from an array).

SystemError

A U array 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

a NDArray

Input array (any dtype; a text element is true when non-empty).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

NumPy's out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an int out stores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.any(a, 0, true)) is NumPy's TypeError: return arrays must be of ArrayType: write keepdims: true.

keepdims bool

If True, the reduced axes are left as dimensions with size one, so the result broadcasts against a.

where NDArray

NumPy's where=: a bool mask that broadcasts TO a's shape. Elements where it is False are left out of the reduction (they count as False, the identity of any). A mask of any other dtype raises, as in NumPy. Null for no mask.

Returns

NDArray

out itself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (an NDArray<bool> instance: AsGeneric<bool>() gives the typed view), read-only when 0-d (NumPy's np.bool scalar). A numpy.matrix operand gives NumPy's matrix.any answer: 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

a is null.

ValueError

out is read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts); where has more axes than a or would make a stretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).

ArgumentException

where is not a bool array (NumPy's TypeError text: the mask must cast to bool under the safe rule).

AxisError

An axis is out of bounds (the first one in order, as given).

IncorrectShapeException

where or out does not broadcast against a.

TypeError

out is a C# scalar (return arrays must be of ArrayType); a numpy.matrix operand with keepdims: true or a mask: NumPy calls the matrix method, which has no such keyword (matrix.any() got an unexpected keyword argument 'keepdims'), or with an out (Cannot construct a dtype from an array).

SystemError

A U array 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

a NDArray

Input array (any dtype; a text element is true when non-empty).

axis NDAxis?

NumPy's axis: null (None, the default) reduces every axis; one axis (0, -1) reduces that axis; a tuple ((0, 2) or new[] { 0, 2 }) reduces each of its axes, and the empty tuple reduces none (the truth values in a's shape). Negative axes count from the end. A 0-d a takes the integer axis 0 or -1 (the ufunc reduction's special case) and the empty tuple.

out NDArray

NumPy's out=: an array of the result's shape and ANY dtype that receives the result with unsafe casting (an int out stores 0 / 1), and is returned; null allocates a fresh bool array. A C# scalar here (np.any(a, 0, true)) is NumPy's TypeError: return arrays must be of ArrayType: write keepdims: true.

keepdims bool

If True, the reduced axes are left as dimensions with size one, so the result broadcasts against a.

where NDArray

NumPy's where=: a bool mask that broadcasts TO a's shape. Elements where it is False are left out of the reduction (they count as False, the identity of any). A mask of any other dtype raises, as in NumPy. Null for no mask.

Returns

NDArray

out itself when given (of its own dtype, which is why the declared type is NDArray); otherwise a fresh bool array (an NDArray<bool> instance: AsGeneric<bool>() gives the typed view), read-only when 0-d (NumPy's np.bool scalar). A numpy.matrix operand gives NumPy's matrix.any answer: 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

a is null.

ValueError

out is read-only ("output array is read-only", checked first), has the wrong rank, or cannot hold the result (NumPy's reduction-iterator texts); where has more axes than a or would make a stretch; or a tuple names an axis twice ("duplicate value in 'axis'", after every axis' range).

ArgumentException

where is not a bool array (NumPy's TypeError text: the mask must cast to bool under the safe rule).

AxisError

An axis is out of bounds (the first one in order, as given).

IncorrectShapeException

where or out does not broadcast against a.

TypeError

out is a C# scalar (return arrays must be of ArrayType); a numpy.matrix operand with keepdims: true or a mask: NumPy calls the matrix method, which has no such keyword (matrix.any() got an unexpected keyword argument 'keepdims'), or with an out (Cannot construct a dtype from an array).

SystemError

A U array 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

arr NDArray

Input array (a C# number is NumPy's Python number: see the remarks).

values NDArray

Values to append: an array, a C# array (its own dtype), or a C# number, bool or string (NumPy's Python scalar). Shape must match arr on all dimensions except axis when axis is given; otherwise it is flattened.

axis int?

Axis along which to append. null (default) flattens both arr and values to 1-D before concatenation.

Returns

NDArray

A new array with values appended to arr along axis: a plain array for numpy.char.chararray operands too (NumPy's np.concatenate drops 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

arr or values is null.

ValueError

A numpy.matrix operand 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

axis is 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

func1d Func<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] = res semantics), so a shape that cannot broadcast raises.

axis int

Axis of arr to slice along; negative counts from the end. The slice handed to func1d is one-dimensional with length arr.shape[axis].

arr NDArray

Input 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 asanyarray of it, so a TEXT SCALAR result (an element v[0] of a <U5 slice, np.sum of a StringDType slice) gives an array as wide as that first value (<U1 for '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.owndata is 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

func1d or arr is null.

AxisError

axis is out of bounds for arr'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.matrix operand 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

func1d Func<NDArray, object[], NDArray>

Applied as func1d(slice, args) to each 1-D slice.

axis int

Axis to slice along; negative counts from the end.

arr NDArray

Input array.

args object[]

Extra positional arguments forwarded to every func1d call.

Returns

NDArray

See the primary overload.

Remarks

Exceptions

ArgumentNullException

func1d or arr is null.

AxisError

axis is out of bounds for arr's rank.

ValueError

Any iteration dimension is zero.

ValueError

A numpy.matrix operand 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

func Func<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.

a NDArray

Input array.

axes NDAxis

NumPy's axes: one axis or a tuple of axes, applied in order (an int is NumPy's (axes,); () applies nothing and returns a itself; a repeat applies func again). Negative axes count from the end using a'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 func over every axis; same rank as a, sizes along axes reduced (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

func or a is null.

ValueError

func returns 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

func Func<NDArray, int, NDArray>

Called as func(current, axis); see the NDAxis form.

a NDArray

Input array.

axes int

The single axis to apply func over; 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

func or a is null.

ValueError

func returns 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

func Func<NDArray, int, NDArray>

Called as func(current, axis); see the NDAxis form.

a NDArray

Input array.

axes int[]

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

axes is null.

ArgumentNullException

func or a is null.

ValueError

func returns 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

start NDArray

The start, or with no stop the stop (np.arange(5) is [0, 5)). A C# number is the Python number it is written as (a float is a Python float, a ulong a Python int by its value); a NumPy scalar (np.float32(0.1)) or a 0-d array is itself.

stop NDArray

The stop (excluded), or null: then start is the stop and 0 the start.

step NDArray

The spacing, or null for 1 (np.arange(5, step: 2) is [0, 2, 4]).

dtype DType

The 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.

device string

Only "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 start nor stop given (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

device is 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

dtype has no NumSharp storage yet (datetime64, timedelta64).

arange(double)

Return evenly spaced values within a given interval.

public static NDArray arange(double stop)

Parameters

stop double

End 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

stop double

End of interval (exclusive).

dtype DType

The dtype of the output array (a Type, NPTypeCode, dtype string or DType — all convert implicitly).

device string

Target device. Only "cpu" and null are accepted (Array-API parity).

Returns

NDArray

Array of evenly spaced values from 0 to stop-1.

Remarks

Exceptions

ValueError

device is not "cpu"; the length is NaN or past npy_intp; or the array is past the byte limit.

TypeError

dtype is a text dtype, or bool with more than two elements.

NotSupportedException

dtype has 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

start double

Start of interval (inclusive).

stop double

End of interval (exclusive).

dtype DType

The dtype of the output array (a Type, NPTypeCode, dtype string or DType — all convert implicitly).

device string

Target device. Only "cpu" and null are accepted (Array-API parity).

Returns

NDArray

Array of evenly spaced values.

Remarks

Exceptions

ValueError

device is not "cpu"; the length is NaN or past npy_intp; or the array is past the byte limit.

TypeError

dtype is a text dtype, or bool with more than two elements.

OverflowError

start or start + 1 does not fit an integer dtype.

NotSupportedException

dtype has 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

start double

Start of interval (inclusive).

stop double

End of interval (exclusive).

step double

Spacing 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

step is zero (NumPy's ZeroDivisionError: 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

start double

Start of interval, a Python float. The interval includes this value.

stop double

End of interval, a Python float. The interval does not include this value.

step double

Spacing between values, a Python float. Default is 1.

dtype DType

The 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.

device string

Target device. Only "cpu" and null are 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

device is 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

step is zero (NumPy's ZeroDivisionError: float division by zero).

TypeError

dtype is a text dtype (arange() not supported for inputs with DType ...), or bool with more than two elements.

OverflowError

start or start + step does not fit an integer dtype (Python integer 300 out of bounds for int8).

NotSupportedException

dtype has no NumSharp storage yet (datetime64, timedelta64).

arange(int)

Return evenly spaced values within a given interval.

public static NDArray arange(int stop)

Parameters

stop int

End 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

start int

Start of interval (inclusive).

stop int

End of interval (exclusive).

step int

Spacing 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

step is zero (NumPy's ZeroDivisionError: division by zero).

arange(long)

Return evenly spaced values within a given interval.

public static NDArray arange(long stop)

Parameters

stop long

End 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

start long

Start of interval (inclusive), a Python int.

stop long

End of interval (exclusive), a Python int.

step long

Spacing 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

step is zero (NumPy's ZeroDivisionError: 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

stop float

End 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

start float

Start of interval (inclusive), a Python float (its exact float32 value).

stop float

End of interval (exclusive), a Python float.

step float

Spacing between values, a Python float. Default is 1.

Returns

NDArray

Array of evenly spaced float64 values: np.arange(0f, 1f, 0.1f)[3] is 0.30000000447034836, NumPy's np.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

step is zero (NumPy's ZeroDivisionError: float division by zero).

arange(ulong)

Return evenly spaced values within a given interval.

public static NDArray arange(ulong stop)

Parameters

stop ulong

End of interval (exclusive), a Python int (its exact value).

Returns

NDArray

Array of evenly spaced values: int64 while stop fits 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

start ulong

Start of interval (inclusive), a Python int.

stop ulong

End of interval (exclusive), a Python int.

step ulong

Spacing 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

step is 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

x NDArray

Input array.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

x NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x NDArray

Input array.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

x NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x NDArray

Input array.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

y NDArray

The y-coordinates (NumPy's x1).

x NDArray

The x-coordinates (NumPy's x2). If y.shape != x.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

The 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.matrix operand 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

x NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

lhs NDArray

An array to test for broadcasting.

rhs NDArray

An array to test for broadcasting.

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

ndArrays NDArray[]

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

shapes Shape[]

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

shapes int[][]

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

shape1 long[]

First shape to test.

shape2 long[]

Second shape to test.

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

a NDArray

Input array.

Returns

long

Index of the maximum value in the flattened array.

Remarks

Exceptions

ValueError

A numpy.char.chararray operand: 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

a NDArray

Input array (any dtype, fixed-width text included: compared as NumPy's STRING_argmax / UNICODE_argmax compare it).

axis NDAxis?

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).

out NDArray

If 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.

keepdims bool

If true, the reduced axis is left in the result with length one (with axis null, every axis: the shape (1,) * a.ndim).

Returns

NDArray

The int64 indices (a 0-d array for the flattened form without keepdims), or out.

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

axis is 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), or out does 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 StringDType line of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy's Cannot compare null that is not a nan-like value).

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

ValueError

A numpy.char.chararray operand without out: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; with out the indices are written.

ArgumentNullException

a is null.

TypeError

axis is 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; or out is a C# scalar converted to a 0-d array (output must be an array): the third positional parameter is out=, so np.argmax(a, 0, true) raises - write keepdims: true by 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

a NDArray

Input array (any dtype, fixed-width text included: compared as NumPy's STRING_argmax / UNICODE_argmax compare it).

axis int?

The axis, or null for the flattened array.

out NDArray

If 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.

keepdims bool

If true, the reduced axis is left in the result with length one (with axis null, every axis: the shape (1,) * a.ndim).

Returns

NDArray

The int64 indices (a 0-d array for the flattened form without keepdims), or out.

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

axis is 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), or out does 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 StringDType line of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy's Cannot compare null that is not a nan-like value).

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

ValueError

A numpy.char.chararray operand without out: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; with out the indices are written.

ArgumentNullException

a is null.

TypeError

axis is 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; or out is a C# scalar converted to a 0-d array (output must be an array): the third positional parameter is out=, so np.argmax(a, 0, true) raises - write keepdims: true by name.

argmin(NDArray)

Returns the index of the minimum value.

public static long argmin(NDArray a)

Parameters

a NDArray

Input array.

Returns

long

Index of the minimum value in the flattened array.

Remarks

Exceptions

ValueError

A numpy.char.chararray operand: 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

a NDArray

Input array (any dtype, fixed-width text included: compared as NumPy's STRING_argmin / UNICODE_argmin compare it).

axis NDAxis?

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).

out NDArray

If 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.

keepdims bool

If true, the reduced axis is left in the result with length one (with axis null, every axis: the shape (1,) * a.ndim).

Returns

NDArray

The int64 indices (a 0-d array for the flattened form without keepdims), or out.

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

axis is 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), or out does 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 StringDType line of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy's Cannot compare null that is not a nan-like value).

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

ValueError

A numpy.char.chararray operand without out: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; with out the indices are written.

ArgumentNullException

a is null.

TypeError

axis is 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; or out is a C# scalar converted to a 0-d array (output must be an array): the third positional parameter is out=, so np.argmin(a, 0, true) raises - write keepdims: true by 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

a NDArray

Input array (any dtype, fixed-width text included: compared as NumPy's STRING_argmin / UNICODE_argmin compare it).

axis int?

The axis, or null for the flattened array.

out NDArray

If 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.

keepdims bool

If true, the reduced axis is left in the result with length one (with axis null, every axis: the shape (1,) * a.ndim).

Returns

NDArray

The int64 indices (a 0-d array for the flattened form without keepdims), or out.

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

axis is 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), or out does 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 StringDType line of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy's Cannot compare null that is not a nan-like value).

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

ValueError

A numpy.char.chararray operand without out: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; with out the indices are written.

ArgumentNullException

a is null.

TypeError

axis is 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; or out is a C# scalar converted to a 0-d array (output must be an array): the third positional parameter is out=, so np.argmin(a, 0, true) raises - write keepdims: true by 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

a NDArray
kth NDArray
axis int?
kind string
order string

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ValueError

A numpy.char.chararray operand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.

ArgumentNullException

a is 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

a NDArray

Array to partition indirectly.

kth int

Element index to partition by; negative wraps from the end.

axis int?

Axis to partition along. -1 (default) = last axis; null flattens first (indices then address the flattened array).

kind string

Selection algorithm — only 'introselect' exists.

order string

Must stay null (no structured dtypes).

Returns

NDArray

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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ValueError

A numpy.char.chararray operand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.

ArgumentNullException

a is 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

a NDArray
kth int[]
axis int?
kind string
order string

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ValueError

A numpy.char.chararray operand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.

ArgumentNullException

a is 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

a NDArray

Array to sort.

axis int?

Axis to sort along; null sorts the flattened array.

kind string

The 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.

order object

Field names; any value is refused (no NumSharp dtype has fields).

stable bool?

True asks for the stable kind; cannot be combined with kind.

descending bool?

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 with kind.

Returns

NDArray

A fresh, C-contiguous int64 array of indices.

Exceptions

ValueError

An unknown kind, kind given with stable or descending, or an order; or a numpy.matrix operand 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 StringDType array sorted descending (unsupported sort kind).

ValueError

A StringDType line of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy's Cannot compare null that is not a nan-like value, raised after the lines before it were sorted).

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

argwhere(NDArray)

Find the indices of array elements that are non-zero, grouped by element.

public static NDArray argwhere(NDArray a)

Parameters

a NDArray

Input 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) where N is the number of non-zero elements. Each row contains the coordinates of one non-zero element. Result dtype is int64. 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). A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.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

a NDArray

Input array (NumPy's keyword a; a C# scalar converts to a 0-d array).

decimals int

Number of decimal places to round to (default 0). Half is rounded to even; a negative value rounds to positions left of the decimal point.

out NDArray

A 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); out itself 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.matrix operand 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

nd NDArray

Source array.

copy bool

When true (default) the data is copied as described above; when false the 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's subok=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's np.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), as np.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

nd is null.

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

buffer np.MemoryView

A np.MemoryView over an array.

copy bool

When true (default) the source storage is cloned; when false the storage is shared (alias).

Returns

NDArray

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

array Array
dtype DType
ndmin int

Specifies 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.

copy bool

Always copies if the array is larger than 1-d.

order char

Memory layout: 'C' (row-major, default), 'F' (column-major), 'A'/'K' (resolved from source).

Returns

NDArray

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

value string

The text.

Returns

NDArray

A 0-d U array, marked an explicit ARRAY (NumSharp.NDArray.IsExplicitZeroDimArray): NumPy's ndarray, not an np.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

value is 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

value string

The text.

dtype DType

A string dtype ("U", "U5", "S", "c", np.str_, np.bytes_) or null to discover.

Returns

NDArray

A 0-d S/U array, 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

value is 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's int() / 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

strArray string[]

The values. A null entry is Python's None, which NumPy would only store in an object array, 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 U array.

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

strArray is 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

a NDArray

Input array.

max_line_width int?

Inserts newlines if text is longer than this. Defaults to the current linewidth.

precision int?

Floating point precision. Defaults to the current precision.

suppress_small bool?

Represent numbers very close to zero as zero. Defaults to the current option.

separator string

Inserted between elements (default " ").

prefix string

Used to align/wrap the output; its content is not included.

threshold int?

Total number of elements which trigger summarization.

edgeitems int?

Number of items at the beginning and end of each dimension in summary.

sign char?

'-', '+', or ' '.

floatmode string

One of "fixed", "unique", "maxprec", "maxprec_equal".

suffix string

Used to wrap the output; its content is not included.

Returns

string

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

a1 NDArray

First input array (NumPy's keyword a1).

a2 NDArray

Second input array (NumPy's keyword a2).

equal_nan bool

When 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) is false whenever the array contains a NaN. When true, 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_nan and two different arrays of one shape (NumPy's isnan has 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 no equal loop, is False; empty arrays are True). A StringDType operand compares through its own == (NumPy's NA rules: two different NA objects raise its TypeError) and, with equal_nan, its isnan (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

a1 NDArray

First input array.

a2 NDArray

Second input array.

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 StringDType operands 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

arr NDArray

The array to represent (NumPy's keyword arr).

max_line_width int?

The line width at which the text wraps; null keeps the current linewidth print option (75 by default).

precision int?

Floating point precision; null keeps the current precision print option (8 by default).

suppress_small bool?

Represent numbers very close to zero as zero; null keeps the current suppress print option.

Returns

string

The repr text of arr.

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

arr is 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

ary NDArray

Array to be divided into sub-arrays.

indices_or_sections int

The number of sections (sizes differ by at most one).

axis int

The axis along which to split, default is 0.

Returns

NDArray[]

The sub-arrays, views into ary. A numpy.char.chararray operand 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

ary is null.

IndexError

axis is out of range ("tuple index out of range": NumPy's Ntotal = ary.shape[axis] runs first).

ValueError

indices_or_sections is 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

ary NDArray

Array to be divided into sub-arrays.

indices int[]

The split points along axis: [2, 3] gives ary[: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.

axis int

The axis along which to split, default is 0.

Returns

NDArray[]

indices.Length + 1 sub-arrays, views into ary. A numpy.char.chararray operand 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

ary is null, or indices is (checked in that order, before the axis).

IndexError

axis is out of range ("tuple index out of range"; a 0-d array refuses every axis).

ValueError

A numpy.matrix operand 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

ary NDArray

Array to be divided into sub-arrays.

indices long[]

The split points along axis: [2, 3] gives ary[: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.

axis int

The axis along which to split, default is 0.

Returns

NDArray[]

indices.Length + 1 sub-arrays, views into ary. A numpy.char.chararray operand 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

ary is null, or indices is (checked in that order, before the axis).

IndexError

axis is out of range ("tuple index out of range"; a 0-d array refuses every axis).

ValueError

A numpy.matrix operand 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

a NDArray
max_line_width int?
precision int?
suppress_small bool?

Returns

string

Remarks

array<T>(IEnumerable<T>)

Creates a Vector NDArray from given data.

public static NDArray array<T>(IEnumerable<T> data) where T : unmanaged

Parameters

data IEnumerable<T>

The enumeration of data to create NDArray from.

Returns

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The type of given array, must be compliant to numpy's supported dtypes.

Remarks

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

data IEnumerable<T>

The enumeration to read. It is enumerated once, and at most size items are taken from it (MoveNext is called size times when it holds that many).

size int

The number of items to read, and the result's length.

Returns

NDArray

A fresh 1-D array of size elements.

Type Parameters

T

The element type, one of NumSharp's dtypes; the result's dtype.

Remarks

See array<T>(IEnumerable<T>, long), which this overload calls.

Exceptions

ValueError

data holds fewer than size items (NumPy's text, iterator too short: Expected 5 but iterator had only 2 items.), or size is negative (negative dimensions are not allowed).

NullReferenceException

data is 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

data IEnumerable<T>

The enumeration to read. It is enumerated once, and at most size items are taken from it (MoveNext is called size times when it holds that many).

size long

The number of items to read, and the result's length.

Returns

NDArray

A fresh 1-D array of size elements.

Type Parameters

T

The 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

data holds fewer than size items (NumPy's text, iterator too short: Expected 5 but iterator had only 2 items.), or size is negative (negative dimensions are not allowed).

NullReferenceException

data is 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

scalar T

The scalar value.

Returns

NDArray

A 0-dimensional NDArray containing the scalar value.

Type Parameters

T

The 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

data T[,,,,,,,,,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,,,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[,]

The array to create NDArray from.

dtype DType

The 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 from T, the data will be cast.

Returns

NDArray

An NDArray with the data cast to the specified dtype.

Type Parameters

T

The 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

data T[,]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[]

The array to create NDArray from.

Returns

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The type of given array, must be compliant to numpy's supported dtypes.

Remarks

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

data T[]

The array to create NDArray from.

dtype DType

The 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 from T, the data will be cast.

Returns

NDArray

An NDArray with the data cast to the specified dtype.

Type Parameters

T

The 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

data T[]

The array to create NDArray from.

copy bool

If 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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The 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

data T[][]

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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The type of given array, must be compliant to numpy's supported dtypes.

Remarks

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

data T[][][]

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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The type of given array, must be compliant to numpy's supported dtypes.

Remarks

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

data T[][][][]

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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The type of given array, must be compliant to numpy's supported dtypes.

Remarks

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

data T[][][][][]

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

NDArray

An NDArray with the data and shape of the given array.

Type Parameters

T

The type of given array, must be compliant to numpy's supported dtypes.

Remarks

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

a np.MemoryView

A np.MemoryView over an array. Null is Python's None, as for the object overload: C# binds a bare np.asanyarray(null, dtype) HERE (a np.MemoryView is the more specific parameter), so the port of NumPy's np.asanyarray(None, dtype) must mean the same.

dtype DType

The requested dtype; null keeps the source's.

order char?

'C', 'F', 'A' or 'K'; null is 'K'.

device string

Null or "cpu".

copy bool?

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", or copy false when a copy is needed.

NotSupportedException

a is null and dtype is null (NumPy's object array).

TypeError

a is null and dtype is an integer (or decimal) 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

a object

Input 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.

dtype DType

The requested dtype; null infers it from a.

order char?

'C', 'F', 'A' or 'K' (either case); null is NumPy's None, 'K': the operand's own layout is kept.

device string

Null or "cpu" (the Array-API device; NumPy has no other).

copy bool?

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: a itself when it is an array whose dtype and layout satisfy the request (and copy is not true), else a new array — of a'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: order is not one of C, F, A, K (order must be one of 'C', 'F', 'A', or 'K' (got 'X')); device is not "cpu"; copy is 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; a numpy.matrix operand whose result cannot be a matrix (shape too large to be a matrix.).

NotSupportedException

a is null and dtype is null (NumPy's object array).

TypeError

a is null and dtype is an integer (or decimal) dtype: Python's int(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

a NDArray

Input ndarray. A C# literal (np.asarray(1000, np.int8), whose 0-d array is marked NumSharp.NDArray.WasPythonLiteral) is NumPy's Python scalar: with a dtype it is packed with NumPy's range checks into a new array, not cast.

dtype DType

Requested dtype. null keeps the input dtype.

order char?

'C' (row-major), 'F' (column-major), 'A' (any contiguous), 'K' (keep); null (NumPy's None, the default) is 'K'. 'A'/'K' never force a copy on layout grounds.

copy bool?

Tri-state: null = copy only if needed (default), true = always copy, false = never copy (raises if a copy would be required).

like NDArray

Reference array for array-function dispatch — accepted for NumPy parity but has no observable effect in NumSharp.

device string

Target device. Only "cpu" and null are accepted.

Returns

NDArray

NDArray with the requested dtype and memory layout. Returns a when no copy is needed. A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.concatenate), which drops the class.

Remarks

Exceptions

NotSupportedException

a is null (Python's None) and dtype is null: NumPy builds an object array, a dtype NumSharp does not have. With a dtype, None is the 0-d array of its setitem value (NaN, nan+nanj, False, 'None', a StringDType NA object).

ValueError

An unsupported device (NumPy's Device not understood. Only "cpu" is allowed, but received: ...).

ArgumentException

copy is false and a copy (or a C# literal's or None'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, or None into an integer (or decimal) 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

a np.MemoryView

A np.MemoryView over an array.

dtype DType

Requested dtype. null keeps the source dtype.

order char?

'C', 'F', 'A', or 'K'; null (NumPy's None, the default) is 'K'.

copy bool?

Tri-state copy: null = if-needed, true = always, false = never (raises).

like NDArray

Reference for array-function dispatch — accepted for parity, no effect.

device string

Only "cpu" or null.

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

a is null.

ValueError

An unsupported device.

ArgumentException

copy is false and 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

a np.MemoryView

A np.MemoryView over an array.

dtype string

The requested dtype as NumPy's dtype string (parsed as np.dtype(string) does).

order char?

'C', 'F', 'A', or 'K'; null (NumPy's None, the default) is 'K'.

copy bool?

Tri-state copy: null = if-needed, true = always, false = never (raises).

like NDArray

Reference for array-function dispatch — accepted for parity, no effect.

device string

Only "cpu" or null.

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

a is null.

TypeError

dtype is not a dtype string NumPy understands.

ValueError

An unsupported device.

ArgumentException

copy is false and 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

a string

The text.

Returns

NDArray

A 0-d U array.

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

a is 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

a string[]

The values.

ndim int

Kept for source compatibility; a string vector is always 1-D.

Returns

NDArray

The U array.

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

a is null.

NotSupportedException

An entry is null (an object array 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

a NDArray

Input data. No copy is performed if the input is already an ndarray matching the requested dtype/order.

dtype DType

By default, the data-type is inferred from the input data.

order char?

'C' (row-major), 'F' (column-major), 'A' (any), 'K' (keep); null (NumPy's order=None, the default) is 'K', as NumPy hands None on to asarray.

Returns

NDArray

Array interpretation of a. A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.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 a contains NaN (Not a Number) or Inf (Infinity).

ArgumentNullException

a is 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

a T

The value.

Returns

NDArray

A new writeable 0-d array that owns its one element.

Type Parameters

T

The 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

T has 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

a T[]

The values (only their count and elements are read: a multi-dimensional C# array binds the NDArray form through its implicit conversion).

ndim int

Kept 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

T

The 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

a is null.

NotSupportedException

T has 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

a NDArray

Input array.

dtype DType

By default, the data-type is inferred from the input.

Returns

NDArray

Contiguous array of same shape and content as a, with type dtype if specified. A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.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

a np.MemoryView

A np.MemoryView over an array.

dtype DType

By 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

a is 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

a NDArray

Input array.

dtype DType

By default, the data-type is inferred from the input.

Returns

NDArray

The input a in Fortran, or column-major, order. A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.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

a np.MemoryView

A np.MemoryView over an array.

dtype DType

By 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

a is 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

x NDArray

Input array (a C# scalar converts to a 0-d array marked as the Python scalar it stands for).

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

The loop dtype (NumPy ufunc dtype=); only non-integer dtypes have a loop.

Returns

NDArray

The result of arcsin(NDArray, NDArray, NDArray, DType): out itself 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.matrix operand 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

x NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

data NDArray

Input array.

dtype DType

Data-type of the output. null keeps the input dtype; another dtype converts, which copies.

Returns

NDMatrix

data interpreted 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

data is null.

ValueError

More than two axes of data are longer than 1 (shape too large to be a matrix.).

IncorrectShapeException

data has more than two axes and one of extent 0 (NumPy's cannot 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

data Array

The array, with at most two axes after conversion.

dtype DType

Data-type of the output, or null for the discovered one.

Returns

NDMatrix

A new matrix.

Remarks

Exceptions

ArgumentNullException

data is null.

ValueError

More than two axes (matrix must be 2-dimensional), or a ragged list.

NotSupportedException

A list holding strings, null or 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

data object

The value.

dtype DType

Data-type of the output, or null for the discovered one.

Returns

NDMatrix

The matrix: a view for an NDArray, new memory for everything else.

Remarks

Exceptions

ArgumentNullException

data is null.

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

data string

Matrix string such as "1 2; 3 4". Each token is one Python literal.

dtype DType

Data-type of the output. null infers it from the values.

Returns

NDMatrix

A new matrix of shape (rows, columns); (1, 0) float64 for an empty string.

Remarks

Exceptions

ArgumentNullException

data is null.

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 as nan).

SyntaxError

A token is not Python syntax.

NotSupportedException

A token is a string, None or ..., 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

nd NDArray

Input NDArray of size 1.

Returns

object

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

arr Array

Input array of size 1.

Returns

object

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

arr ArraySlice<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

arr IArraySlice

Input 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

nd NDArray

Input 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

arr Array

Input 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

x NDArray

The 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.

dtype DType

The target dtype — a DType, a C# Type, an NPTypeCode or a dtype string ("f4") convert implicitly; null is NumPy's dtype=None, the default float64.

copy bool

True (the default) always returns a new array; false returns x ITSELF when its dtype already is dtype, and a new array otherwise (a cast must copy).

device string

NumPy's Array-API device: null or "cpu"; anything else is NumPy's ValueError.

Returns

NDArray

x cast to dtype with the unsafe rule (a float into an int truncates), in x's own layout (the method's order='K'); x itself for a satisfied copy: false. A subclass operand (numpy.matrix) keeps its class, as NumPy's x.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

x is null: NumPy's Input should be a NumPy array or scalar. It is a <class 'NoneType'> instead.

ValueError

device is 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

x NDArray

Input array (a C# scalar converts to a 0-d array marked as the Python scalar it stands for).

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

The loop dtype (NumPy ufunc dtype=); only non-integer dtypes have a loop.

Returns

NDArray

The result of arctan(NDArray, NDArray, NDArray, DType): out itself 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.matrix operand 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

y NDArray

The y-coordinates (NumPy's positional x1).

x NDArray

The x-coordinates (NumPy's positional x2); broadcast against y.

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

The loop dtype (NumPy ufunc dtype=); only non-integer dtypes have a loop.

Returns

NDArray

The result of arctan2(NDArray, NDArray, NDArray, NDArray, DType): out itself 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.matrix operand 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

x NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

arr NDArray

Returns

NDArray

An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. A numpy.char.chararray operand 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

arys NDArray[]

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.chararray operand gives chararrays over the results (NumPy creates them as the subclass).

Remarks

Exceptions

ArgumentNullException

arys is 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

arys object

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

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

arys object[]

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

arys is null.

atleast_2d(NDArray)

View inputs as arrays with at least two dimensions.

public static NDArray atleast_2d(NDArray arr)

Parameters

arr NDArray

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.chararray operand 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

arys NDArray[]

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.chararray operand gives chararrays over the results (NumPy creates them as the subclass).

Remarks

Exceptions

ArgumentNullException

arys is null.

atleast_2d(object)

View inputs as arrays with at least two dimensions.

public static NDArray atleast_2d(object arys)

Parameters

arys object

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

atleast_2d(params object[])

View inputs as arrays with at least two dimensions.

public static NDArray[] atleast_2d(params object[] arys)

Parameters

arys object[]

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

arys is null.

atleast_3d(NDArray)

View inputs as arrays with at least three dimensions.

public static NDArray atleast_3d(NDArray arr)

Parameters

arr NDArray

The 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.chararray operand 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

arr is null.

atleast_3d(params NDArray[])

View inputs as arrays with at least three dimensions.

public static NDArray[] atleast_3d(params NDArray[] arys)

Parameters

arys NDArray[]

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.chararray operand gives chararrays over the results (NumPy creates them as the subclass).

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

arys is 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

arys object

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

atleast_3d(params object[])

View inputs as arrays with at least three dimensions.

public static NDArray[] atleast_3d(params object[] arys)

Parameters

arys object[]

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

arys is 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

a NDArray

The values to average.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

weights NDArray

The weights, or null for equal weights (the mean): of a's shape, or of the averaged axes' extents in the order of axis (NumPy transposes an unsorted tuple's weights to the axes' order; then axis is required). A numpy.matrix of weights beside a plain operand computes as a plain array, where NumPy returns a matrix (its weight sum is the matrix method).

returned bool

NumPy'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);.

keepdims bool

Keep 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.matrix operand gives the matrix method's answer - the scalar without an axis, otherwise a matrix that keeps the averaged axes with length 1), and with returned the 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

a is 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: StringDType beside a number or beside S.

ValueError

A numpy.matrix operand 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 axis argument); weights not of the averaged axes' extents (Shape of weights must be consistent with shape of a along specified axis.).

TypeError

A numpy.matrix operand with keepdims: true: NumPy calls the matrix method, which has no such keyword. The text names that method, as in matrix.sum() got an unexpected keyword argument 'keepdims' for np.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

a NDArray

The values to average.

axis int[]

The axes as NumPy's tuple, or null for None.

weights NDArray

The weights, or null for equal weights (the mean): of a's shape, or of the averaged axes' extents in the order of axis (NumPy transposes an unsorted tuple's weights to the axes' order; then axis is required). A numpy.matrix of weights beside a plain operand computes as a plain array, where NumPy returns a matrix (its weight sum is the matrix method).

returned bool

NumPy'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);.

keepdims bool

Keep 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.matrix operand gives the matrix method's answer - the scalar without an axis, otherwise a matrix that keeps the averaged axes with length 1), and with returned the 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

a is 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: StringDType beside a number or beside S.

ValueError

A numpy.matrix operand 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 axis argument); weights not of the averaged axes' extents (Shape of weights must be consistent with shape of a along specified axis.).

TypeError

A numpy.matrix operand with keepdims: true: NumPy calls the matrix method, which has no such keyword. The text names that method, as in matrix.sum() got an unexpected keyword argument 'keepdims' for np.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

a NDArray

The values to average.

axis NDAxis?

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).

weights NDArray

The weights, or null for equal weights (the mean): of a's shape, or of the averaged axes' extents in the order of axis (NumPy transposes an unsorted tuple's weights to the axes' order; then axis is required). A numpy.matrix of weights beside a plain operand computes as a plain array, where NumPy returns a matrix (its weight sum is the matrix method).

returned bool

NumPy'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);.

keepdims bool

Keep 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.matrix operand gives the matrix method's answer - the scalar without an axis, otherwise a matrix that keeps the averaged axes with length 1), and with returned the 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

a is 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: StringDType beside a number or beside S.

ValueError

A numpy.matrix operand 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 axis argument); weights not of the averaged axes' extents (Shape of weights must be consistent with shape of a along specified axis.).

TypeError

A numpy.matrix operand with keepdims: true: NumPy calls the matrix method, which has no such keyword. The text names that method, as in matrix.sum() got an unexpected keyword argument 'keepdims' for np.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

M double

Number 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 M is 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

M is 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

number BigInteger

The 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.

base int

The radix, 2–36 inclusive. Digits above 9 use uppercase A–Z.

padding int

Number 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-base representation of number.

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

base is 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

num BigInteger

The 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.

width int?

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 num is negative and width is 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

width is smaller than the number of bits required to represent num.

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

x NDArray

1-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 actual ndarray of a non-integer dtype).

weights NDArray

Optional 1-D array of weights, same length as x, cast to float64. When present the result is a weighted sum per bin instead of a count.

minlength int

Minimum length of the output array. Must be non-negative.

Returns

NDArray

A 1-D array: int64 counts when weights is null, otherwise float64 weighted 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

x is 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

x is 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

x1 NDArray

First input array.

x2 NDArray

Second input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Returns

NDArray

Result. This is a scalar if both x1 and x2 are scalars.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x NDArray

Input array. Only integer and boolean types are handled.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Output 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.matrix operand 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

x NDArray

Input array (a C# scalar converts to a 0-d array marked as the Python scalar it stands for).

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

The 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): out itself 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.matrix operand 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

x1 NDArray

Value operand (integer / bool / char only).

x2 NDArray

Shift-count operand (integer / bool / char only).

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

The 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): out itself 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.matrix operand 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

x NDArray

Only integer and boolean types are handled.

out NDArray
where NDArray
dtype DType

Returns

NDArray

Result. This is a scalar if x is a scalar.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x1 NDArray

First input array.

x2 NDArray

Second input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Returns

NDArray

Result. This is a scalar if both x1 and x2 are scalars.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x1 NDArray

Value operand (integer / bool / char only).

x2 NDArray

Shift-count operand (integer / bool / char only).

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

The 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): out itself 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.matrix operand 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

x1 NDArray

First input array.

x2 NDArray

Second input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Returns

NDArray

Result. This is a scalar if both x1 and x2 are scalars.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

M double

Number 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 M is 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

M is 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

arrays object

Nested "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[], jagged int[][], …) 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.matrix operand 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

obj NDArray

Input 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

obj NDArray[]

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

obj NDArray[][]

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

obj ITuple

A 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

obj string

Matrix string such as "A, B; C, D".

ldict IDictionary<string, NDArray>

Local name → array map, consulted first (NumPy's ldict).

gdict IDictionary<string, NDArray>

Global name → array map, consulted when a name is absent from ldict (NumPy's gdict). 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

nd1 NDArray

The first operand.

nd2 NDArray

The second operand.

Returns

np.Broadcast

The broadcast object of the two operands.

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

arrays NDArray[]

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

arrays NDListArray[]

The list arrays (NumPy's sequence of operands); the object borrows them.

Returns

np.Broadcast

The broadcast object over the list arrays.

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

lhs NDArray

An array to broadcast.

rhs NDArray

An array to broadcast.

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

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

ndArrays NDArray[]

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

shapes Shape[]

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 bare int (→ (n,)), an int[]/ long[] (e.g. a.shape), or an explicit new Shape(...) all bind. No argument at all returns the scalar shape () (NumPy's empty-tuple result).

Returns

Shape

The broadcast shape. A scalar shape () when shapes is 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 the np.empty it 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

from UnmanagedStorage

The UnmanagedStorage to broadcast.

against UnmanagedStorage

The 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

from does not broadcast to against one 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

from UnmanagedStorage

The UnmanagedStorage to broadcast.

against NDArray

The 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

from does not broadcast to against one 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

from UnmanagedStorage

The NDArray to broadcast.

against Shape

The 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 against is negative: NumPy's all elements of broadcast shape must be non-negative, raised before the broadcast check.

IncorrectShapeException

from does not broadcast to against one 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

from NDArray

The NDArray to broadcast.

against UnmanagedStorage

The 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

from does not broadcast to against one 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

from NDArray

The NDArray to broadcast.

against NDArray

The 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

from does not broadcast to against one 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

from NDArray

The NDArray to broadcast.

against Shape

The 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 against is negative: NumPy's all elements of broadcast shape must be non-negative, raised before the broadcast check.

IncorrectShapeException

from does not broadcast to against one 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

from Shape

The shape that is to be broadcasted

against UnmanagedStorage

The shape that'll be used to broadcast from shape

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

from does not broadcast to against one 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

from Shape

The shape that is to be broadcasted

against NDArray

The shape that'll be used to broadcast from shape

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

from does not broadcast to against one 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

from Shape

The shape that is to be broadcasted

against Shape

The shape that'll be used to broadcast from shape

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 against is negative: NumPy's all elements of broadcast shape must be non-negative, raised before the broadcast check.

IncorrectShapeException

from does not broadcast to against one 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

from DType

Data type to cast from.

to DType

Data type to cast to.

casting NPY_CASTING

The casting level.

Returns

bool

True if cast can occur according to the casting rule.

Exceptions

TypeError

to or from is 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

from DType

Data type to cast from (any spelling that converts to DType).

to DType

Data type to cast to.

casting string

Controls 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

to or from is null (NumPy's None: "did not understand one of the types; 'None' not accepted"), or casting is null ("casting must be str, not NoneType"). NumPy converts to and casting while it parses the arguments and from_ 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

from NDArray

The array whose dtype is cast, by its own descriptor (for a string array: class and width); null is NumPy's None.

to DType

Data type to cast to.

casting string

The casting rule (see can_cast(DType, DType, string)).

Returns

bool

True if the array's dtype can be cast to to under casting.

Exceptions

TypeError

A null argument (NumPy's texts, in NumPy's order: to, casting, then from_), or from is the 0-d array a bare C# number became: NumPy 2's NEP 50 refusal (NumSharp.np.PythonNumberRefusal()), after the to and casting checks.

ValueError

casting is 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

from NDArray

Array to cast from: arrays are judged by their dtype, never by value (NEP 50).

to NPTypeCode

Data type to cast to.

casting string

Controls 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

from is null.

TypeError

from is the 0-d array a bare C# number became (a bool, an integer primitive, float, double or 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

casting is not one of NumPy's five casting names.

NotSupportedException

to is String: a storage lane names neither the string class nor its width (pass a DType such as np.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

from NPTypeCode

Data type to cast from.

to NPTypeCode

Data type to cast to.

casting string

Controls 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

value object

The 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.

to NPTypeCode

Data type to cast to; Empty is NumPy's None.

casting string

The casting rule (see can_cast(DType, DType, string)).

Returns

bool

True if the source's dtype casts to to under casting.

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 null to, 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 casting name, raised before the source is looked at (NumPy parses it with the arguments).

NotSupportedException

to is 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

from string

The dtype string to cast from; null is NumPy's None.

to DType

Data type to cast to.

casting string

The 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, then from_), or a from string NumPy cannot parse: NumPy replaces the parser's error with did not understand one of the types; 'None' not accepted for from_ (a bad to string keeps the parser's own error, raised while the argument converts).

ValueError

An unknown casting name.

NotSupportedException

from is 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

from Type

CLR type to cast from.

to Type

CLR type to cast to.

casting string

Controls 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

x NDArray

The values whose cube-roots are required.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

x NDArray

Input data.

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

The loop dtype (NumPy's dtype=): x must cast to it under same_kind, so a float input with an integer dtype is refused. null keeps 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 dtype names another. This is a scalar if x is a scalar.

Remarks

Exceptions

TypeError

A dtype the input cannot reach under same_kind (Cannot cast ufunc 'ceil' input from dtype('float64') to dtype('int64') with casting rule 'same_kind'; NumPy raises UFuncTypeError).

ValueError

A numpy.matrix operand 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

a NDArray

The index array (see choose(NDArray, object[], NDArray, string)).

choices NDArray

An array whose outermost dimension enumerates the choices.

out NDArray

Optional destination whose shape must equal the broadcast result shape.

mode string

"raise" (default), "wrap" or "clip".

Returns

NDArray

A fresh C-contiguous array, or out when 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

a or choices is null.

IncorrectShapeException

The choices and a do 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

choices is 0-d, a cannot be safe-cast to int64, or out has the wrong shape.

ValueError

choices has length 0 along its first axis, an index is out of range under mode="raise", or mode is not a known clip mode.

ValueError

A numpy.matrix operand 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

a NDArray

The index array (see choose(NDArray, object[], NDArray, string)).

choices NDArray[]

The choice arrays.

out NDArray

Optional destination whose shape must equal the broadcast result shape.

mode string

"raise" (default), "wrap" or "clip".

Returns

NDArray

A fresh C-contiguous array, or out when given.

Remarks

Scoped by [NDScoped], with the same reclaimed set as the object[] overload.

Exceptions

ArgumentNullException

a, choices or a choice is null.

IncorrectShapeException

The choices and a do 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

choices is empty, an index is out of range under mode="raise", or mode is not a known clip mode.

TypeError

a cannot be safe-cast to int64, or out has the wrong shape.

ValueError

A numpy.matrix operand 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

a NDArray

The index array. Converted to int64 under the "safe" casting rule (bool and the signed/unsigned integers up to uint32 are accepted; uint64, float, complex and decimal are rejected with a TypeError).

choices object[]

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, while bool, char, Half, decimal and every NDArray are strong. All choices are broadcast against each other and against a.

out NDArray

Optional 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 out itself. When null (default) a fresh array is allocated with the choices' common dtype.

mode string

How 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 against a.

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

choices is empty ("0-length sequence."), an index is out of range under mode="raise" ("invalid entry in choice array"), or mode is not a known clip mode (NumPy's two clip-mode texts).

TypeError

a cannot be safe-cast to int64, or out has the wrong shape ("choose: invalid shape for output array.").

ArgumentNullException

a, choices or a choice entry is null.

IncorrectShapeException

The choices and a do 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.matrix operand 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

a NDArray

Array containing elements to clip. It broadcasts with the bounds, out and where.

a_min NDArray

Minimum 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_max NDArray

Maximum 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.

out NDArray

The 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). out must 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).

dtype DType

The 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.

min NDArray

NumPy 2.x keyword alias for a_min; see the remarks for how it combines with the positional bounds.

max NDArray

NumPy 2.x keyword alias for a_max; see the remarks for how it combines with the positional bounds.

where NDArray

NumPy's ufunc where= mask (a bool array, broadcast with the other operands). Only the True positions are computed and written. The other positions of out keep their contents; without out they 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 (out when 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 / max keyword: a_min and a_max are the bounds, a null one is None. NumPy raises "missing 1 required positional argument" for np.clip(a, 1); here that call clips from below only, as np.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's np.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 / max keyword is given while exactly one of a_min / a_max is 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 calls np.positive, which has no bool loop.

ValueError

A min / max keyword is given together with both positional bounds ("Passing min or max keyword argument when a_min and a_max are provided is forbidden."). Or out is read-only (checked before every ufunc argument). Or the operands do not broadcast together, or out would have to be stretched (NumPy's two iterator texts).

TypeError

A dtype the inputs cannot reach, or an out the result cannot be cast into, under the same_kind rule (NumPy's UFuncTypeError texts, naming the routed ufunc).

ArgumentException

A where that 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.matrix operand 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

tup NDArray[]

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.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.concatenate), which drops the class.

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

tup is null, or one of its entries is (the parameter is then named tup[i]).

ValueError

tup is 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

arrays NDArray[]

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() is numpy.float16, the array_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

arrays NDArray[]

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

arrays is 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

types NPTypeCode[]

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

types is 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

condition NDArray

1-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"). If len(condition) < a.shape[axis], only the first len(condition) positions along axis are considered; if longer, any True beyond a.shape[axis] raises IndexOutOfRangeException.

a NDArray

Source array.

axis int?

Axis along which to slice. null (default) flattens a first.

out NDArray

Optional destination. When supplied, shape must match the natural output and out.dtype must be safely castable to a.dtype; values are written via copyto(NDArray, NDArray, string, NDArray) with unsafe casting and the method returns out itself (matches NumPy's out= dispatch via PyArray_TakeFrom).

Returns

NDArray

A copy of a without the slices along axis for which condition is false. Dtype matches a (or out's dtype when supplied). A numpy.char.chararray operand 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_Compress chain — 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

condition or a is null.

ValueError

condition is not 1-D.

AxisError

axis is out of range for a's rank (rank 1 for a 0-d a, which NumPy ravels first).

ValueError

A numpy.matrix operand 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

arrays NDArray[]

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

axis int?

The axis along which the arrays will be joined. If null, arrays are flattened before use. Default is 0.

out NDArray

If provided, the destination to place the result. Cannot be used together with dtype.

dtype DType

If provided, the result array will have this dtype. Cannot be used together with out.

casting string

Controls 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.matrix operand 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

arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

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

arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

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

arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)

public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concat((NDArray, NDArray, NDArray, NDArray, NDArray), int)

public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concat((NDArray, NDArray, NDArray, NDArray), int)

public static NDArray concat((NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concat((NDArray, NDArray, NDArray), int)

public static NDArray concat((NDArray, NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concat((NDArray, NDArray), int)

public static NDArray concat((NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray Lhs, NDArray Rhs)
axis int

Returns

NDArray

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

arrays NDArray[]

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

axis int?

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.

out NDArray

If provided, the destination to place the result. The shape must be correct, matching what would have been returned with no out argument. Cannot be used together with dtype.

dtype DType

If provided, the result array will have this dtype. Cannot be used together with out.

casting string

Controls what kind of data casting may occur. One of "no", "equiv", "safe", "same_kind" (default), or "unsafe".

Returns

NDArray

The concatenated array (out itself when given).

Remarks

Exceptions

ArgumentNullException

arrays or one of its elements is null.

ArgumentException

An unknown casting name; both out and dtype.

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=None ravels it into one element instead).

AxisError

axis is 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) - or out has 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 dtype with text that does not parse as that number (the string route, in NDArray.Multiarray.cs, formats numbers into a text result and parses text into a numeric one).

ValueError

A numpy.matrix operand 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

arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

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

arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

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

arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)

public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concatenate((NDArray, NDArray, NDArray, NDArray, NDArray), int)

public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray, NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concatenate((NDArray, NDArray, NDArray, NDArray), int)

public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray, NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concatenate((NDArray, NDArray, NDArray), int)

public static NDArray concatenate((NDArray, NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray, NDArray, NDArray)
axis int

Returns

NDArray

concatenate((NDArray, NDArray), int)

public static NDArray concatenate((NDArray, NDArray) arrays, int axis = 0)

Parameters

arrays (NDArray Lhs, NDArray Rhs)
axis int

Returns

NDArray

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

x NDArray

Input array.

out NDArray

A location into which the result is stored (must be the same shape; returned as-is).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): selects the loop and its output dtype.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x NDArray

Input array.

out NDArray

A location into which the result is stored (must be the same shape; returned as-is).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=). Masked-off slots keep the prior contents of out.

dtype DType

Explicit 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) — EXCEPT bool, which NumPy has no loop for and therefore resolves to the int8 loop (values 0/1); for Complex the imaginary sign is flipped.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

a NDArray

The first one-dimensional input sequence (a 0-d array is one element, NumPy's ndmin=1).

v NDArray

The second one-dimensional input sequence (likewise); it is the one reversed, after the swap that makes the longer sequence the data.

mode string

'full' (the default: every overlap, len(a) + len(v) - 1 points), '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 of a and v.

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 unknown mode (Use one of 'valid', 'same', or 'full' for convolve/correlate mode when its first letter names a mode, else mode must be one of 'valid', 'same', or 'full' (got 'x') with the argument in Python's repr), object too deep for desired array for an operand of two or more dimensions (a numpy.matrix operand included, as in NumPy), or — for a fixed-width string operand, after every check above — function not available for this data type.

UnicodeEncodeError

A mode holding a lone surrogate (CPython's UTF-8 encoding error, raised before the mode is read).

TypeError

A null mode (NumPy's None): convolve/correlate mode not understood. A StringDType operand (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 StringDType operand 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

a NDArray

Input data.

order char

Controls 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.

subok bool

True to keep the class of a subclass object (NumPy's array(a, order=order, subok=True, copy=True)): the copy of a numpy.char.chararray is a chararray that owns its data, the copy of a numpy.matrix a matrix. False (the default, as in NumPy) returns a plain array whatever a is — 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

a is null.

ValueError

order is 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

x1 NDArray

Values to change the sign of.

x2 NDArray

The sign of x2 is copied to x1. If shapes differ they must broadcast to a common shape.

out NDArray

A location into which the result is stored (NumPy ufunc out=).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

dst NDArray

The array into which values are copied (written in place).

src NDArray

The array from which values are copied. It broadcasts to dst's shape; leading axes of extent 1 beyond dst'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's PyArray_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's None: NumPy's 0-d OBJECT array, castable only under casting='unsafe', where it stores NaN / nan+nanj / False / 'None' / a StringDType NA object, or raises int(None)'s TypeError for an integer destination.

casting string

Which casts from src's dtype to dst's are allowed: "no", "equiv", "safe", "same_kind" (the default) or "unsafe".

where NDArray

A bool mask broadcast to dst's shape: elements are written only where it is true. null (the default) is NumPy's where=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

casting is null: "casting must be str, not NoneType".

ValueError

casting is not one of the five names ("casting must be one of 'no', 'equiv', 'safe', 'same_kind', 'unsafe' (got '…')"); dst is read-only ("assignment destination is read-only"); src does not broadcast to dst ("could not broadcast input array from shape (4,) into shape (3,)"); or where does not ("could not broadcast where mask from shape (2,) into shape (3,)") — NumPy's ValueError texts.

ArgumentException

where is 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's where= check raises.

InvalidCastException

The cast from src's dtype to dst's is not allowed under casting: "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); a None source under any rule but 'unsafe' ("Cannot cast scalar from dtype('O') to …").

TypeError

A None source (src null) under casting='unsafe' into an integer or decimal destination with an element to convert: Python's int(None).

ArgumentNullException

dst is null.

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

dst NDArray

The array into which the value is copied.

src BigInteger

The integer.

casting string

See copyto(NDArray, NDArray, string, NDArray).

where NDArray

See copyto(NDArray, NDArray, string, NDArray).

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

See copyto<T>(NDArray, T, string, NDArray).

ValueError

See copyto(NDArray, NDArray, string, NDArray).

ArgumentException

See copyto(NDArray, NDArray, string, NDArray).

InvalidCastException

See copyto<T>(NDArray, T, string, NDArray).

ArgumentNullException

dst is null.

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

dst NDArray

The array into which the text is copied.

src string

The text (not null).

casting string

See copyto(NDArray, NDArray, string, NDArray).

where NDArray

See copyto(NDArray, NDArray, string, NDArray).

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

dst or src is null.

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

See copyto(NDArray, NDArray, string, NDArray).

ArgumentException

See copyto(NDArray, NDArray, string, NDArray).

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

dst NDArray

The array into which the value is copied.

src T

The value.

casting string

See copyto(NDArray, NDArray, string, NDArray).

where NDArray

See copyto(NDArray, NDArray, string, NDArray).

Type Parameters

T

The C# scalar type. Pass an NDArray (0-d or not) for NumPy's ndarray semantics: NDArray.Scalar(1000L) into int8 wraps to -24 like np.array(1000), while the literal 1000 raises 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 ulong past MaxValue into an integer other than uint32/uint64: "Python int too large to convert to C long" (the LP64 text NumSharp pins).

TypeError

casting is "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; or casting is null.

NotSupportedException

T is an unmanaged type with no NumPy counterpart (for example DateTime).

ValueError

See copyto(NDArray, NDArray, string, NDArray).

ArgumentException

See copyto(NDArray, NDArray, string, NDArray).

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

dst is null.

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

x NDArray

A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, each column a single observation of all those variables (see rowvar).

y NDArray

An additional set of variables and observations, same shape as x.

rowvar bool

If 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.

dtype DType

Data-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

x is 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 / dtype can reach (Corrcoef(NDArray, NDArray, bool, DType) lists them).

IncorrectShapeException

Numeric variables with different observation counts.

TypeError

Text that cov's mean refuses.

DTypePromotionError

StringDType variables without dtype.

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

a NDArray

First one-dimensional input sequence.

v NDArray

Second one-dimensional input sequence (complex-conjugated internally).

mode string

'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 a and v.

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 mode when its first letter names a mode, else mode must be one of 'valid', 'same', or 'full' (got 'x') with the argument in Python's repr); then object of too small depth for desired array (a 0-d operand) or object 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 mode holding a lone surrogate (CPython's UTF-8 encoding error, raised before the mode is read).

TypeError

A null mode (NumPy's None): convolve/correlate mode not understood, before any operand check. A StringDType operand: NumPy's legacy-only descriptor refusal, or Python's error from the first product of the OBJECT fallback.

NotSupportedException

A StringDType operand 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

x NDArray

Input array in radians.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x NDArray

Input array.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

a NDArray

The 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

a is 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

a NDArray

The array for which to count non-zeros (any dtype; a text element counts when non-empty).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

keepdims bool

If 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 without keepdims.

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

a is 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

a NDArray

The array for which to count non-zeros (any dtype; a text element counts when non-empty).

axis int[]

The axes as NumPy's tuple, or null for None.

keepdims bool

If 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 without keepdims.

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

a is 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

a NDArray

The array for which to count non-zeros (any dtype; a text element counts when non-empty).

axis NDAxis?

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-d a takes the integer axis 0 or -1 (the sum's rule) and the empty tuple.

keepdims bool

If 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 without keepdims.

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

a is 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

m NDArray

A 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).

y NDArray

An additional set of variables and observations, same form as m.

rowvar bool

If 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.

bias bool

Default normalization (false) is by (N - 1) (unbiased). If true, normalization is by N. Overridden by ddof.

ddof int?

If not null, overrides the default implied by bias. ddof=1 returns the unbiased estimate even when weights are given; ddof=0 returns the simple average.

fweights NDArray

1-D array of integer frequency weights (number of times each observation is repeated).

aweights NDArray

1-D array of observation vector weights (relative importance of each observation).

dtype DType

Data-type of the result. By default the result has at least float64 precision.

Returns

NDArray

The covariance matrix of the variables.

Remarks

Exceptions

ArgumentNullException

m is null.

ValueError

m or y has more than 2 dimensions; text variables (or a text dtype request) whose m and y have different observation counts (concatenate's text); a negative weight; text that does not parse into a numeric dtype; a StringDType request over no observations (add.reduce's "no identity").

IncorrectShapeException

Numeric variables of m and y with 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 StringDType text by the count).

RuntimeError

A weight array that is multidimensional or does not have one weight per observation.

DTypePromotionError

StringDType variables without dtype (result_type(m, y, float64)), or a StringDType request with weights.

TypeError

An integer or bool dtype: NumPy's in-place X -= 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

a NDArray

Components of the first vector(s).

b NDArray

Components of the second vector(s).

axisa int

Axis of a that defines the vector(s). By default, the last axis.

axisb int

Axis of b that defines the vector(s). By default, the last axis.

axisc int

Axis of the result containing the cross product vector(s). By default, the last axis.

axis int?

If given, the single axis of a, b and the result that defines the vector(s). Overrides axisa/axisb/axisc.

Returns

NDArray

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.broadcast text (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 (axisc against 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

a is 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

a NDArray

Input array (NumPy's keyword a).

axis int?

Axis along which the cumulative product is computed. The default (None) is to compute the cumprod over the flattened array.

dtype DType

Type 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.

out NDArray

Alternate 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 out is 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); a read-only out (output array is read-only); text that a numeric dtype must parse that does not parse.

AxisError

axis is 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

out does not have the result's shape: NumPy's text for the path its accumulate takes (parity QA-31): NpyIter's operands 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

a NDArray

Input array (NumPy's keyword a).

axis int?

Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

dtype DType

Type 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.

out NDArray

Alternate 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 out is 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); a read-only out (output array is read-only); text a numeric loop must parse that does not parse.

AxisError

axis is 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); a StringDType input concatenates.

IncorrectShapeException

out does not have the result's shape: NumPy's text for the path its accumulate takes (parity QA-31): NpyIter's operands 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

x NDArray

Input array (NumPy's positional-only x); a 0-d input is read as 1-D (NumPy's atleast_1d).

axis int?

Axis along which the cumulative product is computed (negative counts from the end). null (NumPy's None, 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.

dtype DType

Type of the returned array and of the accumulator; null follows cumprod(NDArray, int?, DType, NDArray)'s rule (an integer narrower than int64 multiplies as int64, uint8 as uint64, bool as int64).

out NDArray

Alternate output array; with include_initial it must be one longer along axis than the input. It is returned.

include_initial bool

Prepend 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 out was given (then out itself).

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

x is null.

ValueError

axis is null and the input has two or more dimensions ("For arrays which have more than one dimension axis argument is required."), or out's shape does not fit (NumPy's iterator text).

AxisError

axis is out of bounds for the (at least 1-D) input.

IndexError

axis is out of bounds while out and include_initial are 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

x NDArray

Input array (NumPy's positional-only x); a 0-d input is read as 1-D (NumPy's atleast_1d).

axis int?

Axis along which the cumulative sum is computed (negative counts from the end). null (NumPy's None, 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.

dtype DType

Type of the returned array and of the accumulator; null follows cumsum(NDArray, int?, DType, NDArray)'s rule (an integer narrower than int64 sums as int64, uint8 as uint64, bool as int64).

out NDArray

Alternate output array; with include_initial it must be one longer along axis than the input. It is returned.

include_initial bool

Prepend 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 out was given (then out itself).

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

x is null.

ValueError

axis is null and the input has two or more dimensions ("For arrays which have more than one dimension axis argument is required."), or out's shape does not fit (NumPy's iterator text).

AxisError

axis is out of bounds for the (at least 1-D) input.

IndexError

axis is out of bounds while out and include_initial are 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

dtype DType

A datetime64 or timedelta64 descriptor (any spelling that converts to DType, e.g. "M8[s]").

Returns

(string unit, int count)

The (unit, count) tuple NumPy 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

x NDArray

Angles in degrees.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

x NDArray

Angle in radians.

out NDArray
where NDArray
dtype DType

The 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

x is 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

arr NDArray

Input array.

obj NDArray

A 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) or bool[] (a mask) converts implicitly, and a C# integer binds delete(NDArray, long, int?), which calls this form.

axis int?

The axis to delete along; null deletes from the flattened array.

Returns

NDArray

A fresh array without the selected sub-arrays (F-ordered when arr is). A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_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

arr or obj is null.

ValueError

A boolean obj is not 1-D or its length differs from the axis length (NumPy's boolean array argument obj to delete must be one dimensional and match the axis length of 6; a C# true is a 0-d mask).

IndexError

obj's dtype is neither boolean nor integer — text, a float, complex, decimal — whatever its size (NumPy's keep[obj,] = False: arrays used as indices must be of integer (or boolean) type).

IndexOutOfRangeException

An index is outside [-N, N).

ValueError

A numpy.matrix operand 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

arr NDArray

Input array.

obj Slice

The positions to remove, as a slice (new Slice(1, 4) is NumPy's slice(1, 4)).

axis int?

The axis to delete along; null (default) flattens arr first and returns a 1-D result.

Returns

NDArray

A fresh array without the sliced positions (F-ordered when arr is). A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_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

arr or obj is null.

AxisError

axis is out of bounds.

ArgumentException

A slice step of zero.

ValueError

A numpy.matrix operand 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

arr NDArray

Input array.

obj long

The position to remove; negative counts from the end. Every C# integer type binds here.

axis int?

The axis to delete along; null (default) flattens arr first and returns a 1-D result.

Returns

NDArray

A fresh array without the position (F-ordered when arr is). A numpy.char.chararray operand 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

arr is null.

AxisError

axis is out of bounds.

IndexOutOfRangeException

obj is outside [-N, N) (NumPy's index 7 is out of bounds for axis 0 with size 6).

ValueError

A numpy.matrix operand 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

v NDArray

If v is 2-D, return a copy of its k-th diagonal. If v is 1-D, return a 2-D array with v on the k-th diagonal.

k int

Diagonal in question. Use k > 0 for diagonals above the main diagonal, and k < 0 for diagonals below the main diagonal.

Returns

NDArray

The extracted diagonal or constructed diagonal array. A numpy.char.chararray operand 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

v is not 1- or 2-dimensional — Input must be 1- or 2-d. (NumPy's ValueError).

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

n int

The size, along each dimension, of the arrays for which the returned indices can be used.

ndim int

The number of dimensions. Default 2.

Returns

NDArray<long>[]

ndim index arrays, each arange(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

arr NDArray

Array, at least 2-D, whose dimensions must all be of equal length.

Returns

NDArray<long>[]

Index arrays addressing arr's main diagonal.

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

arr is null.

ArgumentException

input array must be at least 2-d when ndim < 2, or All dimensions of input must be of equal length when the shape is not hyper-cubic (both NumPy ValueErrors, 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

v NDArray

Input data, which is flattened (in C order) and set as the k-th diagonal of the output.

k int

Diagonal to set; 0, the default, corresponds to the "main" diagonal, a positive (negative) k giving the number of the diagonal above (below) the main.

Returns

NDArray

The 2-D output array of shape (n, n) where n = v.size + |k|. Always a freshly allocated, C-contiguous, writeable array. A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_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.matrix operand 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

a NDArray

Source array. Must have at least 2 dimensions.

offset int

Offset of the diagonal from the main diagonal. Positive values refer to diagonals above the main, negative below. Default 0.

axis1 int

First axis of the 2-D sub-array. Default 0.

axis2 int

Second axis of the 2-D sub-array. Default 1.

Returns

NDArray

A read-only view sharing storage with a. Shape: a.shape with axis1 and axis2 removed and the diagonal appended as the last axis. A numpy.char.chararray operand 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

a is null.

ValueError

a has 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

a NDArray

Input array (must be at least one dimensional).

n int

The number of times values are differenced. If zero, the input is returned as-is. Must be non-negative.

axis int

The axis along which the difference is taken; default is the last axis. Negative axes count from the end.

prepend object

Value(s) to prepend to a along axis prior to differencing. Scalars expand to length 1 along the axis. null means "not supplied" (NumPy's np._NoValue).

append object

Value(s) to append to a along axis prior to differencing. Scalars expand to length 1 along the axis. null means "not supplied".

Returns

NDArray

The n-th differences. The shape matches the (optionally prepend/append-extended) input except along axis where the size shrinks by n. The dtype is preserved (boolean input yields boolean output via not_equal).

Remarks

Exceptions

ValueError

A numpy.matrix operand 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 n above 0: NumPy's subtract has no string loop, so its first a[1:] - a[:-1] refuses whatever the size.

ValueError

a is 0-D ("diff requires input that is at least one dimensional").

AxisError

axis is out of range for a's rank.

ArgumentNullException

a is null.

digitize(NDArray, NDArray, bool)

Return the indices of the bins to which each value in input array x belongs.

rightbins orderreturned index i satisfies
falseincreasingbins[i-1] <= x < bins[i]
trueincreasingbins[i-1] < x <= bins[i]
falsedecreasingbins[i-1] > x >= bins[i]
truedecreasingbins[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

x NDArray

Input array to be binned. May have any shape; the result has the same shape.

bins NDArray

1-D monotonic (increasing or decreasing) array of bin edges.

right bool

Whether 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

x or bins is null.

IncorrectTypeException

x is complex (x may not be complex, checked first).

ValueError

bins is 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

bins does not cast 'safely' to float64 (text, StringDType included, or complex; NumPy's TypeError text).

TypeError

A StringDType x: 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

x1 NDArray
x2 NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x1 NDArray

Dividend array.

x2 NDArray

Divisor 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): the loop computes in this dtype.

Returns

(NDArray Lhs, NDArray Rhs)

(quotient, remainder). Both are scalars if x1 and x2 are scalars.

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.matrix operand 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's ufunc 'divmod' not supported for the input types, ... (parity QA-27); under a real dtype, an input or an out the loop cannot reach by a same_kind cast (NumPy's UFuncTypeError texts); a bool or complex dtype (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

a NDArray

Lhs, First argument.

b NDArray

Rhs, Second argument.

out NDArray

Output argument. Unlike a ufunc's out, np.dot's is STRICT (its new_array_for_sum in common.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.matrix operand 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 aligned ValueError 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

ary NDArray

Array to be divided into sub-arrays.

indices_or_sections int

If 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.chararray operand 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

ary has fewer than three dimensions ("dsplit only works on arrays of 3 or more dimensions"; NumPy raises the text as a ValueError) - a numpy.matrix always 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

ary is 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

ary NDArray

Array to be divided into sub-arrays.

indices int[]

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.chararray operand 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

ary has fewer than three dimensions ("dsplit only works on arrays of 3 or more dimensions"; NumPy raises the text as a ValueError) - a numpy.matrix always does.

ArgumentNullException

indices is null (checked after the rank).

NullReferenceException

ary is 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

tup NDArray[]

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.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.concatenate), which drops the class.

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

tup is null.

ValueError

tup is empty ("need at least one array to concatenate").

NullReferenceException

An entry of tup is 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

dtype DType

The 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.

align bool

NumPy's align=; no effect on a non-structured dtype.

copy bool

NumPy's copy=: a fresh copy when dtype is a class singleton (any other descriptor comes back as itself, as in NumPy).

metadata IReadOnlyDictionary<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

dtype itself (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

sctype NDScalarType

The scalar class ((NDScalarType)np.float64, an element of np.floating.subclasses(), integer, ...), or null — NumPy's None, the default float64 descriptor (NumSharp.np.DefaultTypeDescr).

align bool

NumPy's align=; no effect on a non-structured dtype.

copy bool

NumPy's copy=: a fresh copy of the class singleton instead of the singleton.

metadata IReadOnlyDictionary<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 copy or metadata asks for one.

Exceptions

TypeError

sctype is abstract — NumPy's texts, verbatim: Converting 'np.integer' or 'np.signedinteger' to a dtype is not allowed, Converting np.inexact or np.floating to a dtype not allowed (also for np.number), Converting np.unsignedinteger to a dtype is not allowed, Converting np.complex to a dtype is not allowed., Converting np.character to a dtype is not allowed, Converting np.generic to a dtype is not allowed. (also for 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

typecode NPTypeCode

The storage code.

align bool

NumPy's align=; no effect on a non-structured dtype.

copy bool

NumPy's copy=: a fresh copy of the class singleton instead of the singleton.

metadata IReadOnlyDictionary<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 copy or metadata asks for one.

Exceptions

ArgumentException

typecode is Empty.

NotSupportedException

typecode has 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

dtype string

Any 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's None: the default float64 descriptor (NumSharp.np.DefaultTypeDescr).

align bool

NumPy'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.

copy bool

NumPy's copy=: return a fresh copy instead of the shared builtin singleton. Only a singleton is copied (NumPy tests fields 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.

metadata IReadOnlyDictionary<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's PyDict_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" keeps byteorder == '>', isnative == false) and for every datetime64/timedelta64 descriptor — or a fresh copy when copy or metadata asks for one. An explicit host byte order is read as native ("<f8" is the float64 singleton on a little-endian host), as NumPy's parser reads it. A null string gives the float64 singleton (NumPy's np.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's repr), 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 as invalid 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

type Type

The C# element type, or null — NumPy's None, the default float64 descriptor (NumSharp.np.DefaultTypeDescr).

align bool

NumPy's align=; no effect on a non-structured dtype (see dtype(string, bool, bool, IReadOnlyDictionary<string, object>)).

copy bool

NumPy's copy=: a fresh copy of the class singleton instead of the singleton.

metadata IReadOnlyDictionary<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 copy or metadata asks for one.

Exceptions

NotSupportedException

type is 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

ary NDArray

Input array (flattened before differencing).

to_end object

Number(s) to append to the end of the returned differences. null means none. Cast to ary's dtype under the same_kind casting rule.

to_begin object

Number(s) to prepend to the beginning of the returned differences. null means none. Cast to ary's dtype under the same_kind casting rule.

Returns

NDArray

1-D array of consecutive differences (input dtype), optionally bracketed by to_begin and to_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

ary is null.

TypeError

to_begin or to_end cannot be cast to ary's dtype under same_kind: NumPy's dtype of to_begin must be compatible with input ary under the same_kind rule. (parity QA-08).

TypeError

ary is boolean (NumPy's boolean-subtract TypeError).

TypeError

ary holds 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 the to_begin / to_end checks, 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

operands object[]

Alternating NDArray and subscript list, optionally closed by a lone output list. A subscript list is an int[], or an object[] mixing integers with Ellipsis where NumPy writes Ellipsis.

Returns

NDArray

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

subscripts string

Comma-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.

operands NDArray[]

The arrays the subscripts label, in order.

Returns

NDArray

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

subscripts string

The subscripts string, as for einsum(string, params NDArray[]) ("ij,jk->ik").

operands NDArray[]

The arrays the subscripts label, in order.

out NDArray

Where the calculation would be deposited. Its RANK is validated now.

dtype DType

Forces the accumulation dtype.

order char

Memory layout of the result — 'C', 'F', 'A' or 'K', in either case (NumPy's order converter).

casting string

Casting rule — "no", "equiv", "safe", "same_kind" or "unsafe", spelled exactly.

optimize object

false (the default), true, "greedy" or "optimal". NumPy also takes a precomputed contraction path; that is not modelled, because nothing plans one yet.

Returns

NDArray

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

subscripts is null.

TypeError

casting is null (casting must be str, not NoneType); an optimize NumPy does not understand; an operand that cannot reach the loop dtype, or a result that cannot reach out's dtype, under casting; text outside the view path.

ValueError

No operand; an order letter or a casting name NumPy refuses, with its texts; malformed subscripts; an out of 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 before order, casting and out, as NumPy's einsum plans first.

IndexError

An explicit path, or an ellipsis, naming an operand that is not there (np.einsum_path's pop 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

operands object[]

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

subscripts is 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 optimize NumPy 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

subscripts string

The einsum subscripts, e.g. "ij,jk,kl->il".

operands NDArray[]

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

subscripts is 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 optimize NumPy 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

subscripts string

The einsum subscripts, e.g. "ij,jk,kl->il".

operands NDArray[]

The arrays the subscripts label — only their SHAPES are read.

optimize object

false/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

subscripts is 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 optimize NumPy 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

shape Shape

The dimensions: an int (2), a tuple ((2, 3)), an int[] / long[] or a Shape (all convert implicitly). Only the dimensions are read: the layout comes from order, as NumPy's shape is a tuple of ints — a Shape taken from a transposed view gives a C-ordered array unless order says 'F'.

dtype DType

The 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.

order char

'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.

device string

Null 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: order is not one of C, F, A, K (order must be one of 'C', 'F', 'A', or 'K' (got 'X')); device is not "cpu" (Device not understood. Only "cpu" is allowed, but received: gpu); order is 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

dtype names 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

prototype NDArray

The shape and data-type of prototype define these same attributes of the returned array.

dtype DType

Overrides 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.

order char

Memory layout: 'C', 'F', 'A' (F when prototype is F-contiguous and not C-contiguous, else C) or 'K' (the default: prototype's axis order, kept also for a shape of the same rank), in either case.

shape Shape?

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.

device string

Target device. Only "cpu" and null are 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.chararray operand 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

order is 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; device is neither null nor "cpu" (NumPy's Device not understood. Only "cpu" is allowed, but received: ...); a negative dimension in shape (negative dimensions are not allowed); a numpy.matrix operand 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

x1 NDArray

Input array.

x2 NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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

x1 NDArray

Input array.

x2 object

Scalar or array-like value.

Returns

NDArray<bool>

Output array of bools.

equal(object, NDArray)

Return (x1 == x2) element-wise with scalar on left.

public static NDArray<bool> equal(object x1, NDArray x2)

Parameters

x1 object

Scalar or array-like value.

x2 NDArray

Input array.

Returns

NDArray<bool>

Output array of bools.

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

expr NDExpr

Expression with embedded array leaves, or with positional Input(int) leaves that operands fills. 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 x

A repeated NDArray reference becomes ONE iterator operand. Text operands (S, U and StringDType arrays, and a C# string, which is NumPy's str) 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 call
operands NDArray[]

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).

out NDArray

Optional 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 with dtype. Pass it by name: the second position is operands.

where NDArray

Optional 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 out keep their prior contents (and without out the unmasked slots of the fresh result are left uninitialised, exactly as NumPy's ufuncs leave them). It broadcasts with the inputs and out but never stretches a provided out, and must be a boolean array. NOT supported on a reduction tree (a masked reduction is a different operation).

dtype DType

Optional 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) equals np.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 with out (which already fixes the result dtype).

casting string

The cast rule enforced when a caller out has a different dtype than the resolved result ('no'/'equiv'/'safe'/'same_kind'/'unsafe'); default (null) is NumPy's ufunc same_kind. With no out it only validates the string.

order char

The 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 out keeps 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 dtype if 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

out is not reachable from the result dtype under casting (NumPy's UFuncTypeError text).

ArgumentException

Both dtype and out were given; where is not a boolean array (NumPy's verbatim "Cannot cast … to dtype('bool') according to the rule 'safe'"); or operands is empty.

ValueError

A read-only out; casting is not a legal rule, or order is 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 Where with text branches, a bare text leaf), a reduction of text other than Any / 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, Cast to a number and the numpy.strings factories compute on text.

TypeError

A text node NumPy refuses (a comparison of S with U or of text with a number, a numpy.strings function over the wrong class, IsNaN of S / U), with NumPy's UFuncTypeError text.

OverflowError

A Cast of text to an integer whose parsed value is out of the target's range (NumPy's OverflowError).

ArgumentNullException

expr is null, or an entry of operands is.

NotSupportedException

dtype, a non-'K' order, or a where mask 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

a NDArray

Input value.

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.

Returns

NDArray

e**x element-wise (an integer or bool input computes in its float tier), or out itself 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.matrix operand 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

a NDArray

Input array.

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): selects the loop; the input must be same_kind-castable to it.

Returns

NDArray

2**x element-wise (an integer or bool input computes in its float tier), or out itself 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.matrix operand 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

a NDArray

The array.

axis NDAxis

NumPy's axis (required, no None): one position (0, -1) or a tuple of positions ((0, 3) or new[] { 0, 3 }), each in the result's rank a.ndim + Count; negative positions count from the end of the result. An empty tuple inserts nothing. A List<int> needs .ToArray().

Returns

NDArray

A NEW view of a with the new axes (an empty tuple included, NumPy's a.reshape(shape)): it shares memory with a. A numpy.matrix operand gives a plain array (NumPy converts it with asarray first); a numpy.char.chararray operand 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

a is null, or axis was converted from a null int[] (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

a NDArray

The array.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

Returns

NDArray

A NEW view of a with the new axes (an empty tuple included, NumPy's a.reshape(shape)): it shares memory with a. A numpy.matrix operand gives a plain array (NumPy converts it with asarray first); a numpy.char.chararray operand 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

a is null, or axis was converted from a null int[] (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

a NDArray

The array.

axis int[]

The axes as NumPy's tuple (not null).

Returns

NDArray

A NEW view of a with the new axes (an empty tuple included, NumPy's a.reshape(shape)): it shares memory with a. A numpy.matrix operand gives a plain array (NumPy converts it with asarray first); a numpy.char.chararray operand 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

axis is null (expand_dims has no None).

ArgumentNullException

a is null, or axis was converted from a null int[] (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

a NDArray

Input array.

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): selects the loop; the input must be same_kind-castable to it.

Returns

NDArray

exp(x) - 1 element-wise, accurate near zero, or out itself 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.matrix operand 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

condition NDArray

Array whose nonzero / True entries indicate the elements of arr to extract. May be any dtype (treated as truthy via NumPy's "nonzero" semantics). May be any shape — it is ravel'd before alignment with arr.

arr NDArray

Input array. May be any shape; it is ravel'd.

Returns

NDArray

Rank-1 NDArray of values from arr where the corresponding ravel'd condition entry is truthy. Dtype matches arr. A numpy.char.chararray operand 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

N int

Number of rows in the output.

M int?

Number of columns in the output. If None, defaults to N.

k int

Index 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.

dtype DType

Data-type of the returned array.

order char

Memory layout: 'C' (row-major, default) or 'F' (column-major).

device string

Target device. Only "cpu" and null are 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

order is 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); N or M is negative (negative dimensions are not allowed); or the dtype's setitem refuses the Python int 1 (a StringDType(coerce=False)).

ValueError

device is neither null nor "cpu" (NumPy's Device 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

x NDArray

Input array. Any dtype EXCEPT complex — fabs(NDArray, NDArray, NDArray, DType) has no complex loop (use absolute(NDArray, NDArray, NDArray, DType) for the complex magnitude).

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

a NDArray

Array whose diagonal is to be filled; it is modified in place.

val object

Value(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's int() / float() / complex(); into S / U its str()), an object[] or collection (a Python list) item by item the same way, an NDArray or typed C# array by an unsafe cast. null is Python's None: NaN (NumPy's positive NPY_NAN) for a float array, nan+nanj for complex, False for bool, 'None' (truncated) for S / U, a StringDType's NA object or 'None'.

wrap bool

For 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), or underlying array is read-only — all verbatim NumPy ValueError texts.

ArgumentNullException

a is null.

TypeError

val is null (None), or a list holds one, and a is an integer (or decimal) array — Python's int(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 (None included); 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_types DType[]

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_types DType[]

The dtypes of the arrays. Null counts as none.

scalar_types DType[]

The dtypes of the scalars. Null counts as none.

Returns

DType

See find_common_type(NPTypeCode[], NPTypeCode[]).

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_types NPTypeCode[]

The dtypes of the arrays. Null counts as none.

scalar_types NPTypeCode[]

The dtypes of the scalars. Null counts as none.

Returns

DType

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is 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_types NPTypeCode[]

The dtypes of the arrays. Null counts as none.

scalar_types Type[]

The dtypes of the scalars. Null counts as none.

Returns

DType

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is 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

involvedTypes string[]

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_types string[]

The dtypes of the arrays. Null counts as none.

scalar_types string[]

The dtypes of the scalars. Null counts as none.

Returns

DType

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is 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_types Type[]

The dtypes of the arrays. Null counts as none.

Returns

DType

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is 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_types Type[]

The dtypes of the arrays. Null counts as none.

scalar_types NPTypeCode[]

The dtypes of the scalars. Null counts as none.

Returns

DType

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is 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_types Type[]

The dtypes of the arrays. Null counts as none.

scalar_types Type[]

The dtypes of the scalars. Null counts as none.

Returns

DType

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is 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

dtype DType

The 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

dtype is null (NumPy 2.5's dtype 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

dtype NDScalarType

The scalar class.

Returns

finfo

The limits.

Exceptions

TypeError

dtype is null (NumPy 2.5's dtype 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 for int, whose NumPy class is int64). An abstract class is data type dtype('O') not compatible with finfo: NumPy's finfo retries a value that converts to no dtype with the dtype of its TYPE, and the type of a class is Python's type, an object dtype — so even np.finfo(np.floating) names dtype('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

dtype string

A 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

dtype is null (NumPy 2.5's dtype 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

x NDArray

Array to be rounded.

out NDArray

A 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 under same_kind (a float→int out raises, matching NumPy); the same instance is returned. If null, a freshly allocated array is returned.

Returns

NDArray

The element-wise truncation of x (or out).

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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); a read-only out.

TypeError

Text or complex input, which trunc has no loop for.

TypeError

An out the result does not reach under same_kind.

ArgumentException

An out the result does not broadcast into.

NullReferenceException

x is 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

a NDArray

Returns

np.FlatIterator

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

a NDArray

The array to iterate over.

writeable bool

Open the operand readwrite so assignments through the ref reach the array. A read-only broadcast view (stride-0) is rejected with NumPy's verbatim message. (Like np.nditer<T>, this is a caller contract, not a C# read-only guarantee — the iterator is never buffered, so assigning through the ref always writes physically.)

Returns

np.FlatRefIter<T>

Type Parameters

T

Must be EXACTLY the array's element type — no conversion or casting is performed, because a ref cannot convert. A mismatch throws rather than reinterpreting the bytes (cast first with a.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

a NDArray

Input data.

Returns

NDArray<long>

1-D NDArray<TDType> of long (NumPy intp) containing the indices of elements of a.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

m NDArray

Input array.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

Returns

NDArray

A view of m with the entries of the selected axes reversed: it shares memory with m (a write through it changes m) and is read-only when m is. A numpy.char.chararray operand gives a chararray view, and a 0-d one its element: the read-only stand-in of NumPy's Python str / 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

m is 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-d m has no axis to name.

ValueError

An axis is named twice (repeated axis); a numpy.matrix operand 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

m NDArray

Input array.

axis int[]

The axes as NumPy's tuple, or null for None.

Returns

NDArray

A view of m with the entries of the selected axes reversed: it shares memory with m (a write through it changes m) and is read-only when m is. A numpy.char.chararray operand gives a chararray view, and a 0-d one its element: the read-only stand-in of NumPy's Python str / 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

m is 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-d m has no axis to name.

ValueError

An axis is named twice (repeated axis); a numpy.matrix operand 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

m NDArray

Input array.

axis NDAxis?

NumPy's axis: null (None, the default) flips every axis; one axis (0, -1) flips that axis; a tuple ((0, 2) or new[] { 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 m with the entries of the selected axes reversed: it shares memory with m (a write through it changes m) and is read-only when m is. A numpy.char.chararray operand gives a chararray view, and a 0-d one its element: the read-only stand-in of NumPy's Python str / 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

m is 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-d m has no axis to name.

ValueError

An axis is named twice (repeated axis); a numpy.matrix operand 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

m NDArray

Input array, must be at least 2-D.

Returns

NDArray

A view of m with 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. A numpy.char.chararray operand 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 m is less than 2-d ("Input must be >= 2-d.").

ValueError

A numpy.matrix operand 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

m NDArray

Input array, must be at least 1-D.

Returns

NDArray

A view of m with 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. A numpy.char.chararray operand 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 m is less than 1-d ("Input must be >= 1-d.").

ValueError

A numpy.matrix operand 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

x1 NDArray

The bases (any dtype; promoted to the float loop).

x2 NDArray

The exponents (any dtype; promoted to the float loop).

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x1 NDArray

The bases.

x2 object

The exponents (scalar or array-like).

Returns

NDArray

The bases in x1 raised to the exponents in x2 at float64/complex128 precision.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x NDArray

Input array

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

The loop dtype (NumPy's dtype=): x must cast to it under same_kind, so a float input with an integer dtype is refused. null keeps 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 dtype names another. This is a scalar if x is a scalar.

Remarks

Exceptions

TypeError

A dtype the input cannot reach under same_kind (Cannot cast ufunc 'floor' input from dtype('float64') to dtype('int64') with casting rule 'same_kind'; NumPy raises UFuncTypeError).

ValueError

A numpy.matrix operand 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

x1 NDArray

Dividend array.

x2 NDArray

Divisor array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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's No 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

x1 NDArray

Dividend array.

x2 object

Scalar or array-like divisor.

Returns

NDArray

y = floor(x1/x2).

Exceptions

ValueError

A numpy.matrix operand 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

x1 NDArray

First operand. If shapes differ they must broadcast to a common shape.

x2 NDArray

Second operand. If shapes differ they must broadcast to a common shape.

out NDArray

A 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.

where NDArray

Boolean mask (NumPy ufunc where=): only mask-true elements are computed/written; masked-off out slots keep prior contents. Must be a bool array.

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.

Returns

NDArray

The element-wise NaN-ignoring maximum (or out when supplied). A scalar if both inputs are scalars.

Remarks

Exceptions

TypeError

out is not same_kind-castable (NumPy-verbatim text).

ArgumentException

where is not bool, or the shapes do not broadcast (NumPy-verbatim texts).

ValueError

A numpy.matrix operand 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

x1 NDArray

First operand. If shapes differ they must broadcast to a common shape.

x2 NDArray

Second operand. If shapes differ they must broadcast to a common shape.

out NDArray

A 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.

where NDArray

Boolean mask (NumPy ufunc where=): only mask-true elements are computed/written; masked-off out slots keep prior contents. Must be a bool array.

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.

Returns

NDArray

The element-wise NaN-ignoring minimum (or out when supplied). A scalar if both inputs are scalars.

Remarks

Exceptions

TypeError

out is not same_kind-castable (NumPy-verbatim text).

ArgumentException

where is not bool, or the shapes do not broadcast (NumPy-verbatim texts).

ValueError

A numpy.matrix operand 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

x1 NDArray

Dividend array.

x2 NDArray

Divisor array; broadcasts against x1.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): computation runs in this dtype.

Returns

NDArray

The truncated remainders, or out itself when given.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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's No 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

x1 NDArray
x2 object

Returns

NDArray

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

x object

The value. A Half formats as np.float16 and a float as np.float32, each with its OWN shortest digits (0.1f prints '0.1', not float64's '0.10000000149011612'); a double as np.float64; anything else converts like Python's float(x) to a float64 — a C# integer or BigInteger (a Python int, correctly rounded), a bool, a char (NumSharp's Char dtype, NumPy's np.uint16: its number), a decimal, a 0-d NDArray (its element; a 0-d text array parsed as a float literal).

precision int?

The most digits to print after the point (with fractional false: significant digits); null prints the digits unique asks 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.99999 at precision 2 is '2.').

unique bool

True: the shortest digits that read back as the value, cut at precision. False: the value's exact digits to precision, which is then required.

fractional bool

True: precision and min_digits count digits after the point; false: all significant digits.

trim string

Trailing 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.

sign bool

Print '+' before a non-negative value.

pad_left int?

Pad with spaces on the left until the integer part (with its sign) has this many characters.

pad_right int?

Pad with spaces on the right until the fraction has this many characters.

min_digits int?

The fewest digits to print in unique mode (zeros pad it); counted like precision.

Returns

string

The text; an infinity is 'inf' / '-inf' ('+inf' with sign), 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); fractional false with precision 0 (precision must be greater than 0 if fractional=False); min_digits above 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); unique false without a precision (in non-unique mode precision must be supplied); an x that 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

x object

The 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).

precision int?

The most digits to print after the point; null prints the digits unique asks for. In unique mode a rounding that carries through 9s prints fewer digits (0.0995 at precision 1 is '1.e-01').

unique bool

True: the shortest digits, cut at precision; false: the exact digits to precision, which is then required.

trim string

As 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').

sign bool

Print '+' before a non-negative value.

pad_left int?

Pad with spaces on the left until the integer part (one digit and the sign) has this many characters.

exp_digits int?

The fewest exponent digits (default 2; at most 5 are honoured; 0 prints no exponent digit for exponent 0: '1.5e+').

min_digits int?

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_digits above a positive precision; a 0-d text array that spells no float.

TypeError

A bad trim; unique false without a precision; an x that 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

x NDArray

Input 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 of x's shape and returned as-is; either slot may be null (NumPy's (None, e)), default allocates both.

where NDArray

Boolean mask (NumPy ufunc where=): with outputs supplied, only mask-true elements are written and masked-off slots keep their prior contents.

dtype DType

NumPy'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 of x; an F-contiguous input yields F-contiguous outputs. Each is a 0-d scalar when x is 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

buffer np.MemoryView

A np.MemoryView over a C-contiguous array.

dtype DType

Data-type of the returned array; null is float64. Any dtype reads the array's bytes, whatever the array's own dtype.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Start 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-native dtype, 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

buffer is null.

NotSupportedException

dtype has 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

buffer np.MemoryView

A np.MemoryView over a C-contiguous array.

dtype NPTypeCode

Data-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized np.str_, refused.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Start 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

buffer is 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

buffer np.MemoryView

A np.MemoryView over a C-contiguous array.

dtype string

The 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's None).

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Start 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

dtype spells NEP 55 StringDType ("T"): NumPy's cannot create an OBJECT array from memory buffer; or the texts of frombuffer(byte[], DType, long, long).

NotSupportedException

dtype names no dtype (np.dtype's data 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

buffer is 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

segment ArraySegment<byte>

The array segment to interpret. A default segment (no array) is an empty buffer, as NumPy's b'' is.

dtype DType

Data-type of the returned array; null is float64.

count long

Number 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

dtype has 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

segment ArraySegment<byte>

The array segment to interpret (a default segment is an empty buffer).

dtype NPTypeCode

Data-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized np.str_, refused.

count long

Number 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

buffer byte[]

The bytes (a C# byte[] is mutable, NumPy's bytearray: the result is writeable).

dtype DType

Data-type of the returned array; null is float64 (NumPy's default).

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Start 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-native dtype ('>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 55 StringDType, 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 negative count that leaves a partial item); buffer is smaller than requested size.

ArgumentNullException

buffer is null (checked after the dtype, as NumPy asks for the buffer after its descriptor checks).

NotSupportedException

dtype has 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

buffer byte[]

The bytes (writable: the result is writeable).

dtype NPTypeCode

Data-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.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Start 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 type before the buffer is read.

ArgumentNullException

buffer is 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

buffer byte[]

The bytes (writable: the result is writeable).

dtype string

The 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's None).

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Start 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

dtype spells NEP 55 StringDType ("T"): NumPy's cannot create an OBJECT array from memory buffer; or the texts of frombuffer(byte[], DType, long, long).

NotSupportedException

dtype names no dtype (np.dtype's data 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

buffer is 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

address nint

Pointer to the start of the buffer.

byteLength long

Total length of the buffer in bytes.

dtype DType

Data-type of the returned array; null is float64.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Byte offset into the buffer. Default is 0.

dispose Action

Optional 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 dispose a 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 through dispose when the last array over it is released. An empty result with dispose is a fresh empty array, and the memory is released at once through it. For a non-native dtype, 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 request dispose is not called: the caller still owns the memory.

ArgumentNullException

address is null.

NotSupportedException

dtype has 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

address nint

Pointer to the start of the buffer.

byteLength long

Total length of the buffer in bytes.

dtype NPTypeCode

Data-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized np.str_, refused.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Byte offset into the buffer. Default is 0.

dispose Action

Optional 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

address is 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

memory Memory<byte>

The memory to interpret; it bounds the buffer (the bytes of an array behind it past its end are never read).

dtype DType

Data-type of the returned array; null is float64.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Byte 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

dtype has 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

memory Memory<byte>

The memory to interpret.

dtype NPTypeCode

Data-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized np.str_, refused.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Byte 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

buffer ReadOnlySpan<byte>

The bytes.

dtype DType

Data-type of the returned array; null is float64.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Start 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

dtype has 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

buffer ReadOnlySpan<byte>

The bytes.

dtype NPTypeCode

Data-type of the returned array: a storage lane; Empty is float64, and String is NumPy's unsized np.str_, refused.

count long

Number of items to read. A negative number reads every whole item after offset.

offset long

Start 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

address void*

Pointer to the start of the buffer.

byteLength long

Total length of the buffer in bytes.

dtype DType

Data-type of the returned array. Default is float64.

count long

Number of items to read. -1 means all data.

offset long

Byte offset into the buffer. Default is 0.

dispose Action

Optional cleanup action called when NDArray is disposed.

Returns

NDArray

1-dimensional NDArray viewing/owning the memory.

Exceptions

ValueError

See frombuffer(nint, long, DType, long, long, Action).

ArgumentNullException

address is 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

address void*

Pointer to the start of the buffer.

byteLength long

Total length of the buffer in bytes.

dtype NPTypeCode

Data-type of the returned array, as a storage lane.

count long

Number of items to read. -1 means all data.

offset long

Byte offset into the buffer. Default is 0.

dispose Action

Optional cleanup action called when NDArray is disposed.

Returns

NDArray

1-dimensional NDArray viewing/owning the memory.

Exceptions

ValueError

See frombuffer(nint, long, NPTypeCode, long, long, Action).

ArgumentNullException

address is 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

array TSource[]

The source array to reinterpret: its bytes are the buffer (pinned while an array over it lives).

dtype DType

Target data-type. Default (null) preserves the source type - a NumSharp extension: NumPy's frombuffer of an ndarray reads float64.

count long

Number of items of target dtype. A negative number reads every whole item.

offset long

Byte offset. Default is 0.

Returns

NDArray

1-dimensional NDArray viewing the array as the target dtype.

Type Parameters

TSource

Source 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

array is null.

NotSupportedException

dtype has 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

array TSource[]

The source array to reinterpret (pinned while an array over it lives).

dtype NPTypeCode

Target data-type: a storage lane; Empty preserves the source type, and String is NumPy's unsized np.str_, refused.

count long

Number of items of target dtype. A negative number reads every whole item.

offset long

Byte offset. Default is 0.

Returns

NDArray

1-dimensional NDArray viewing the array as the target dtype.

Type Parameters

TSource

Source element type.

Exceptions

ValueError

The texts of frombuffer(byte[], DType, long, long).

ArgumentNullException

array is 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

stream Stream

The 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.

dtype DType

Element type (default float64).

count long

Elements to read; negative (default -1) reads to the end.

sep string

Separator between items of a text file. Empty (default) reads binary.

offset long

Bytes to skip from the stream's position first. Binary only.

like NDArray

Accepted for NumPy's signature; no effect.

Returns

NDArray

The 1-D array of the elements read.

Exceptions

ArgumentNullException

stream is null.

UnicodeEncodeError

sep holds a lone surrogate.

TypeError

sep is null, or an offset with a text separator.

OSError

An offset before the start of the stream ([Errno 22] Invalid argument).

ValueError

As fromfile(string, DType, long, string, long, NDArray).

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

file string

A file name.

dtype DType

Element 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 through CDOUBLE_scan). A non-native byte order ('>i4') reads big-endian binary data into a native array.

count long

Elements to read; negative (default -1) reads the whole file.

sep string

Separator 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.

offset long

Bytes to skip from the file's current position first. Binary files only.

like NDArray

Reference 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

file is null.

UnicodeEncodeError

sep holds a lone surrogate.

TypeError

sep is null (NumPy's sep=None: fromfile() argument 4 must be str, not None), or an offset with 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

sep holds a NUL; a StringDType (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

function Func<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's lambda 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.

shape Shape

The output shape, which also sets each grid's shape: a tuple ((2, 3)), an int[] / long[] or a Shape.

dtype DType

The grids' dtype (NumPy's dtype=float default): null is float64; pass np.int64 for integer coordinates.

Returns

NDArray

Whatever function returns — usually an array of shape; 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 before function runs, as NumPy's np.indices raises it.

TypeError

function is null ('NoneType' object is not callable, raised after the grids are built, as in NumPy).

Exception

Whatever function throws, 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

iter IEnumerable

Any 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.

dtype DType

The result's dtype — NumPy's required argument; null is NumPy's None, the default float64 (not a dtype inferred from the items).

count long

How 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

iter is 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 item int() ... not 'list' into an integer dtype, must be real number, not list / only 0-dimensional arrays can be converted to Python scalars into complex).

ValueError

dtype is an unsized text dtype ("U", "S": Must specify length when using variable-size data-type.); fewer items than a non-negative count (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

func Delegate

The scalar function to broadcast (any supported arity; may return a tuple for multi-output).

nin int

Declared input count. Validated against the delegate's parameter count (C# knows the arity), unlike NumPy where it DEFINES the count.

nout int

Declared output count. Validated against the delegate's return (1, or its ValueTuple arity).

Returns

Vectorized

A Vectorized applying func element-wise; use Call(params NDArray[]) or CallMany(params NDArray[]).

Remarks

Exceptions

ArgumentNullException

func is null.

ValueError

nin or nout disagrees 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

string byte[]

The text's bytes.

dtype DType

Element type of the result (default float64).

count long

Elements to read; negative reads all of them.

sep string

Separator between numbers; null or empty is the removed binary mode.

like NDArray

Accepted for NumPy's signature; no effect.

Returns

NDArray

The 1-D array.

Exceptions

ArgumentNullException

string is null.

UnicodeEncodeError

sep holds a lone surrogate.

ValueError

As fromstring(string, DType, long, string, NDArray).

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

string string

The text (NumPy's str argument: read as its UTF-8 bytes).

dtype DType

Element 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 with PyOS_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.

count long

Elements to read; negative (default -1) reads all of them. With a count, the result ALWAYS has count elements (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).

sep string

Separator 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.

like NDArray

Reference 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

string is null (NumPy's None is a TypeError: a bytes-like object is required, not 'NoneType').

UnicodeEncodeError

string or sep holds 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); a StringDType (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

shape Shape

The dimensions: an int (2), a tuple ((2, 3)), an int[] / long[] or a Shape (all convert implicitly). Only the dimensions are read: the layout comes from order, as NumPy's shape is a tuple of ints.

fill_value object

Fill 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# int is int32, where NumPy's Python int is int64).

dtype DType

The 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 from fill_value (an array fill value gives its own dtype).

order char

'C' (row-major, the default) or 'F' (column-major), in either case: NumPy's empty(shape, dtype, order) layout, so 'A' and 'K' are refused.

device string

Null or "cpu" (the Array-API device; NumPy has no other).

Returns

NDArray

A new, owned, writeable array of shape's dimensions with fill_value cast 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: order is not one of C, F, A, K; device is not "cpu"; order is A or K (only 'C' or 'F' order is permitted); a negative dimension; fill_value is null and dtype is a StringDType(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 numeric dtype.

NotSupportedException

fill_value is null (Python's None) and dtype is null: NumPy builds an object array there, a dtype NumSharp does not have.

TypeError

fill_value is null and dtype is an integer (or decimal) dtype, for a non-empty shape: Python's int(None), raised by NumPy's copyto(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

a NDArray

The shape and data-type of a define these same attributes of the returned array.

fill_value object

Fill value: a scalar, or an array (an NDArray of rank ≥ 1, a C# array) that broadcasts into the result.

dtype DType

Overrides the data type of the result, or null for a's.

order char

Memory layout: 'C', 'F', 'A' (F when a is F-contiguous and not C-contiguous, else C) or 'K' (the default: a's axis order, kept also for a shape of the same rank), in either case.

shape Shape?

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.

device string

Target device. Only "cpu" and null are accepted (Array-API parity; NumPy's is keyword-only).

Returns

NDArray

Array of fill_value with the requested shape and type. A numpy.char.chararray operand 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

order is 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; device is neither null nor "cpu" (NumPy's Device not understood. Only "cpu" is allowed, but received: ...); a negative dimension in shape (negative dimensions are not allowed); a numpy.matrix operand whose result cannot be a matrix (shape too large to be a matrix.).

ValueError

A numpy.char.chararray operand 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

None into a non-empty integer (or decimal) 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

x1 NDArray

First input array (integer dtype).

x2 NDArray

Second input array (integer dtype); broadcasts against x1.

out NDArray

A location into which the result is stored (NumPy ufunc out=); returned as-is.

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=); masked-off slots keep their prior value.

dtype DType

Explicit 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, or out cannot take the loop dtype.

ArgumentException

where is non-boolean, or out does not broadcast.

ValueError

A numpy.matrix operand 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

start NDArray

The 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).

stop NDArray

The final value(s) of the sequence, unless endpoint is False. In that case num + 1 values are spaced over the interval in log-space, of which all but the last are returned. No element may be zero.

num long

Number of samples to generate. Default 50. Must be non-negative.

endpoint bool

If True (default) stop is the last sample; otherwise it is excluded.

dtype DType

The 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's dt = 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.

axis int

The 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 to axis (for number ends a 1-D array of num samples).

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

start or stop is null.

ValueError

An end holds a zero (Geometric sequence cannot include zero, NumPy's first check), or num is negative.

DTypePromotionError

A StringDType dtype (no common DType with the ends).

TypeError

An S or U dtype (sign has no string loop).

IncorrectShapeException

The ends do not broadcast.

AxisError

axis is out of range for the result (NumPy's verbatim destination: message).

get_printoptions()

Return the current print options as a dictionary (NumPy's np.get_printoptions).

public static IReadOnlyDictionary<string, object> get_printoptions()

Returns

IReadOnlyDictionary<string, object>

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

f NDArray

Input array (samples of a scalar function).

spacing object

Optional 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 (a List<T>, or an object[] passed as an object: as an object[] 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 float32 f stays float32); a Half, char or decimal is a NumPy scalar and a 0-d NDArray an array, both strong (a float64 0-d step computes a float32 f in float64, rounded once).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

edge_order int

Boundary difference order, 1 (default) or 2.

Returns

np.GradientResult

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

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray

Input array (samples of a scalar function).

spacing object

Optional 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 (a List<T>, or an object[] passed as an object: as an object[] 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 float32 f stays float32); a Half, char or decimal is a NumPy scalar and a 0-d NDArray an array, both strong (a float64 0-d step computes a float32 f in float64, rounded once).

axis int[]

The axes as NumPy's tuple, or null for None.

edge_order int

Boundary difference order, 1 (default) or 2.

Returns

np.GradientResult

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

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray

Input array (samples of a scalar function).

spacing object

Optional 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 (a List<T>, or an object[] passed as an object: as an object[] 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 float32 f stays float32); a Half, char or decimal is a NumPy scalar and a 0-d NDArray an array, both strong (a float64 0-d step computes a float32 f in float64, rounded once).

axis NDAxis?

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_order int

Boundary difference order, 1 (default) or 2.

Returns

np.GradientResult

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

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
spacing0 object
spacing1 object
axis int

The axis (NumPy's axis=k; a negative value counts from the end).

edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
spacing0 object
spacing1 object
axis int[]

The axes as NumPy's tuple, or null for None.

edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
spacing0 object
spacing1 object
axis NDAxis?
edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
spacing0 object
spacing1 object
spacing2 object
axis int

The axis (NumPy's axis=k; a negative value counts from the end).

edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
spacing0 object
spacing1 object
spacing2 object
axis int[]

The axes as NumPy's tuple, or null for None.

edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
spacing0 object
spacing1 object
spacing2 object
axis NDAxis?
edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
varargs object[]
axis int

The axis (NumPy's axis=k; a negative value counts from the end).

edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
varargs object[]
axis int[]

The axes as NumPy's tuple, or null for None.

edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

f NDArray
varargs object[]
axis NDAxis?
edge_order int

Returns

np.GradientResult

Exceptions

ArgumentNullException

f is null.

AxisError

An axis is outside [-f.ndim, f.ndim-1].

ValueError

A repeated axis; edge_order > 2; an axis is shorter than edge_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

f is 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 and edge_order = 2 it has a gradient, as in NumPy.

TypeError

A str or None step (Python's own 2. * ax_dx refuses 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 BigInteger step 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

x1 NDArray

Input array.

x2 NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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

x1 NDArray

Input array.

x2 object

Scalar or array-like value.

Returns

NDArray<bool>

Output array of bools.

greater(object, NDArray)

Return (x1 > x2) element-wise with scalar on left.

public static NDArray<bool> greater(object x1, NDArray x2)

Parameters

x1 object

Scalar or array-like value.

x2 NDArray

Input array.

Returns

NDArray<bool>

Output array of bools.

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

x1 NDArray

Input array.

x2 NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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

x1 NDArray

Input array.

x2 object

Scalar or array-like value.

Returns

NDArray<bool>

Output array of bools.

greater_equal(object, NDArray)

Return (x1 >= x2) element-wise with scalar on left.

public static NDArray<bool> greater_equal(object x1, NDArray x2)

Parameters

x1 object

Scalar or array-like value.

x2 NDArray

Input array.

Returns

NDArray<bool>

Output array of bools.

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

M double

Number 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 M is 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

M is 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

M double

Number 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 M is 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

M is 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

x1 NDArray

Input values; the sign of each element selects the branch (negative → 0, positive → 1, zero → x2, NaN → NaN).

x2 NDArray

The value of the function where x1 is 0. If shapes differ they must broadcast to a common shape. NOT interchangeable with x1 — heaviside is not commutative.

out NDArray

A location into which the result is stored (joins the broadcast without being stretched, same_kind-castable from the loop dtype; returned as-is).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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 both x1 and x2 are 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.matrix operand 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

a NDArray

Input data; the histogram is computed over the flattened array.

bins NDArray

The explicit bin edges (must increase monotonically).

range (double, double)?

Ignored when explicit edges are given (accepted for signature parity).

density bool?

When true, return the probability density instead of raw counts. null (NumPy's None, the default) is false.

weights NDArray

Optional 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 weights over data: NumPy's UFuncTypeError Cannot 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

a is 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

a NDArray

Input data.

bins double[]

The explicit bin edges.

range (double, double)?

Ignored when explicit edges are given.

density bool?

When true, return the probability density instead of raw counts. null (NumPy's None, the default) is false.

weights NDArray

Optional 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 weights over data: NumPy's UFuncTypeError Cannot 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

a is 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

a NDArray

Input data; the histogram is computed over the flattened array.

bins int

Number of equal-width bins (default 10).

range (double, double)?

Optional (lower, upper) outer edges; defaults to (a.min(), a.max()).

density bool?

When true, return the probability density (count / total / bin_width) whose integral over the range is 1, instead of raw counts. null (NumPy's None, the default) is false.

weights NDArray

Optional per-sample weights of the same shape as a; each sample then contributes its weight instead of 1, and hist.dtype follows weights.

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

a is 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

a NDArray

Input data; the histogram is computed over the flattened array.

bins string

The estimator name.

range (double, double)?

Optional (lower, upper) outer edges; also constrains the data the estimator sees.

density bool?

When true, return the probability density instead of raw counts. null (NumPy's None, the default) is false.

weights NDArray

Weighted 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

weights is supplied together with an estimator name.

ArgumentNullException

a is 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

x NDArray

The x coordinates, shape (N,).

y NDArray

The y coordinates, shape (N,).

bins NDArray

Shared 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.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (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

x is 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

x NDArray

The x coordinates, shape (N,).

y NDArray

The y coordinates, shape (N,).

bins NDArray[]

Per-dimension edge arrays.

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (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

x is 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

x NDArray

The x coordinates, shape (N,).

y NDArray

The y coordinates, shape (N,).

bins double[]

Shared bin edges (more than 2 entries).

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (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

x is 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

x NDArray

The x coordinates, shape (N,).

y NDArray

The y coordinates, shape (N,).

bins int

Number of equal-width bins along both dimensions (default 10).

range (double, double)?[]

Optional per-dimension (lower, upper) outer edges ([[xmin,xmax],[ymin,ymax]]).

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (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

x is 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

x NDArray

The x coordinates, shape (N,).

y NDArray

The y coordinates, shape (N,).

bins int[]

Per-dimension bin counts [nx, ny].

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (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

x is 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

x NDArray

The x coordinates, shape (N,).

y NDArray

The y coordinates, shape (N,).

bins object[]

Per-dimension spec, each entry an int count or an edge array.

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (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

x is 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

a NDArray

Input data (only its dtype/emptiness matters here).

bins NDArray

The explicit bin edges (must increase monotonically; dtype preserved).

range (double, double)?

Ignored when explicit edges are given (accepted for signature parity).

weights NDArray

Ignored 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

a is 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

a NDArray

Input data.

bins double[]

The explicit bin edges.

range (double, double)?

Ignored when explicit edges are given.

weights NDArray

Ignored 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

a is 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

a NDArray

Input data; the histogram is computed over the flattened array.

bins int

Number of equal-width bins (default 10).

range (double, double)?

Optional (lower, upper) outer edges; defaults to (a.min(), a.max()).

weights NDArray

Unused 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

a is 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

a NDArray

Input data; the histogram is computed over the flattened array.

bins string

The estimator name.

range (double, double)?

Optional (lower, upper) outer edges; also constrains the data the estimator sees.

weights NDArray

Weighted 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

bins is not a known estimator, or the range is invalid.

TypeError

weights is supplied (unsupported for estimators).

ArgumentNullException

a is 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

sample NDArray

An (N, D) array of N points in D-dimensional space.

bins NDArray[]

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 bins gives a count).

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (N,) per-point weights.

Returns

np.HistogramddResult

A np.HistogramddResult carrying H and 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

sample is 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

sample NDArray

An (N, D) array of N points in D-dimensional space.

bins int

Number 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.

density bool?

When true, return the probability density (count / total / bin_volume). null (NumPy's None, the default) is false.

weights NDArray

Optional (N,) per-point weights.

Returns

np.HistogramddResult

A np.HistogramddResult carrying H and 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

sample is 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

sample NDArray

An (N, D) array of N points in D-dimensional space.

bins int[]

Per-dimension bin counts (length must equal D).

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (N,) per-point weights.

Returns

np.HistogramddResult

A np.HistogramddResult carrying H and 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

sample is 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

sample NDArray

An (N, D) array of N points in D-dimensional space.

bins object[]

Per-dimension spec: each entry an int count, an NDArray / double[] edge array.

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (N,) per-point weights.

Returns

np.HistogramddResult

A np.HistogramddResult carrying H and 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

sample is 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

sample NDArray[]

D coordinate arrays, each of length N.

bins NDArray[]

Per-dimension edge arrays.

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (N,) per-point weights.

Returns

np.HistogramddResult

A np.HistogramddResult carrying H and 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

sample NDArray[]

D coordinate arrays, each of length N.

bins int

Number of equal-width bins along every dimension (default 10).

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (N,) per-point weights.

Returns

np.HistogramddResult

A np.HistogramddResult carrying H and 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

sample NDArray[]

D coordinate arrays, each of length N.

bins int[]

Per-dimension bin counts (length must equal D).

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (N,) per-point weights.

Returns

np.HistogramddResult

A np.HistogramddResult carrying H and 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

sample NDArray[]

D coordinate arrays, each of length N.

bins object[]

Per-dimension spec: each entry an int count or an edge array.

range (double, double)?[]

Optional per-dimension outer edges.

density bool?

When true, return the probability density. null (NumPy's None, the default) is false.

weights NDArray

Optional (N,) per-point weights.

Returns

np.HistogramddResult

A np.HistogramddResult carrying H and 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

ary NDArray

Array to be divided into sub-arrays.

indices_or_sections int

If 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.chararray operand 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentException

ary is 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

ary is 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

ary NDArray

Array to be divided into sub-arrays.

indices int[]

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.chararray operand 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentException

ary is 0-d ("hsplit only works on arrays of 1 or more dimensions"; NumPy raises the text as a ValueError).

ArgumentNullException

indices is null (checked after the rank).

NullReferenceException

ary is 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

tup NDArray[]

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.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.concatenate), which drops the class.

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

tup is null.

ValueError

tup is 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

tup NDArray[]

The arrays (NumPy's sequence): the same shape along all but the second axis, except 1-D arrays, which can be any length.

dtype DType

The result dtype handed to np.concatenate, or null for the arrays' promoted dtype.

casting string

The 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.matrix operand 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

tup is null.

ValueError

tup is empty ("need at least one array to concatenate"); a numpy.matrix result of more than two long axes.

InvalidCastException

An array that does not cast to dtype under casting (np.concatenate's refusal with NumPy's text; NumPy's type is TypeError, pinned in OpenBugs.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

x1 NDArray

Leg of the triangle(s).

x2 NDArray

Leg of the triangle(s). If shapes differ they must broadcast to a common shape.

out NDArray

A location into which the result is stored (joins the broadcast without being stretched, same_kind-castable from the loop dtype; returned as-is).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x NDArray

Argument 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

x is null.

IncorrectTypeException

x is Complex — I₀ has no complex loop (NumPy's TypeError("i0 not supported for complex values")).

OverflowException

x is Decimal and I₀ overflows the decimal range (double→decimal bridge limit).

ValueError

x is text and an element does not parse as a float (NumPy's x.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

n int

Number of rows (and columns) in n x n output.

dtype DType

Data-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_type DType

The 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_type is 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_type NDScalarType

The scalar class (NumPy's keyword name).

Returns

iinfo

The limits.

Exceptions

ArgumentNullException

int_type is null.

ValueError

The class's kind is not 'i' or 'u' — NumPy's text, which names the kind of np.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's iinfo retries a value that converts to no dtype with the dtype of its TYPE, and the type of a class is Python's type, 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_type string

A dtype string ("int32", "i8", "uint8"); null is NumPy's None, which np.dtype reads as the default float64 (so NumPy's Invalid 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

val NDArray

Input array.

Returns

NDArray

For a COMPLEX input: a float64 VIEW onto the imaginary lane — it SHARES memory with val and is writeable, so np.imag(z)[i] = x writes through to z[i]'s imaginary part (reproducing NumPy's z.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.matrix operand 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

dimensions Shape

The shape of the grid: a tuple ((2, 3)), an int[] / long[] (an array's shape), 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.

dtype DType

Element 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).

sparse bool

NumPy's sparse: return the per-axis arrays instead of the dense grid (each a VIEW of its arange, flags.owndata False 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 dtype refuses, 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

a NDArray

First input array.

b NDArray

Second input array.

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.matrix operand 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

arr NDArray

Input array.

obj NDArray

A 0-d or 1-D integer index array (negative from the end, N appends), 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.

values NDArray

The values to insert, cast to arr's dtype and broadcast to the insertion slot; a C# number is NumPy's Python scalar (range-checked: 300 into int8 is NumPy's OverflowError), a string is parsed by a numeric array, null is Python's None (NaN, nan+nanj, False, 'None' or a StringDType NA object, converted after the index checks).

axis int?

The axis to insert along; null inserts into the flattened array.

Returns

NDArray

A fresh array with the values inserted (F-ordered when arr is). A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_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

arr or obj is null.

ValueError

obj is 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 with array(values, dtype=arr.dtype): could not convert string to float); a numpy.matrix operand 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 text obj of 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 obj of 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

arr NDArray

Input array.

obj Slice

The insertion positions, as a slice (new Slice(1, 3) is NumPy's slice(1, 3)).

values NDArray

The 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).

axis int?

The axis to insert along; null inserts into the flattened array.

Returns

NDArray

A fresh array with the values inserted (F-ordered when arr is). A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_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

arr or obj is 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; a numpy.matrix operand 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

arr NDArray

Input array.

obj long

The insertion position; negative counts from the end, N appends. Every C# integer type binds here.

values NDArray

The 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).

axis int?

The axis to insert along; null inserts into the flattened array.

Returns

NDArray

A fresh array with the values inserted (F-ordered when arr is). A numpy.char.chararray operand 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

arr is null.

IndexOutOfRangeException

obj is 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.matrix operand 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

x NDArray

The x-coordinates at which to evaluate the interpolated values (any shape; the result has the same shape).

xp NDArray

The x-coordinates of the data points — 1-D, must be increasing unless period is given.

fp NDArray

The y-coordinates of the data points, same length as xp (float or complex).

left NDArray

Value returned for x < xp[0]; null (NumPy's None) means fp[0]. Any number NumPy's float() takes: a C# double or int (a Python float / int), a Complex for a complex fp (a Python complex), a NumPy scalar, a 0-d array. Ignored when period is given.

right NDArray

Value returned for x > xp[-1]; null means fp[-1]. As left. Ignored when period is given.

period double?

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

fp or xp is not 1-D (object too deep for desired array / object of too small depth for desired array), xp is empty, the lengths differ, or period is 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

x is 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

ar1 NDArray

Input array (flattened if not already 1-D).

ar2 NDArray

Input array (flattened if not already 1-D).

assume_unique bool

If 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_indices bool

If True, also return the indices of the first occurrences of the common values in ar1 and ar2 (NumPy sorts with the stable 'mergesort' here).

Returns

np.Intersect1dResult

An np.Intersect1dResult: the values (it converts implicitly to NDArray), and with return_indices comm1 / 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 S text beside U text, and a byte is not ASCII (in the order of the unique values).

DTypePromotionError

A StringDType operand beside a class the concatenation finds no common DType with (a number, bool, S bytes): NumPy's verbatim promotion text.

ValueError

A NEP 55 StringDType array whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy's Cannot 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

x NDArray

Only integer and boolean types are handled.

out NDArray
where NDArray
dtype DType

Returns

NDArray

Result. This is a scalar if x is a scalar.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

a NDArray

Input array to compare with b

b NDArray

Input array to compare with a.

rtol double

The relative tolerance parameter(see Notes)

atol double

The absolute tolerance parameter(see Notes)

equal_nan bool

Whether to compare NaN's as equal. If True, NaN's in a will be considered equal to NaN's in b in the output array.

Returns

NDArray<bool>

Returns a boolean array of where a and b are equal within the given tolerance.If both a and b are 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

x NDArray

Input 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

x is null.

iscomplexobj(NDArray)

Return True if x is a complex type or an array of complex numbers.

public static bool iscomplexobj(NDArray x)

Parameters

x NDArray

Input 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

x is 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

dtype DType

The descriptor to test.

kind DType

The descriptor whose class counts as a match.

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

dtype is null.

TypeError

kind is 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

dtype DType

The descriptor to test.

kinds DType[]

The dtypes whose classes count as a match.

Returns

bool

True when dtype's class is the class of any entry.

Exceptions

ArgumentNullException

dtype or kinds is 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

dtype DType

The dtype (any spelling: a DType, Type, NPTypeCode or dtype string).

kind NDScalarType

The scalar class.

Returns

bool

True when the dtype's scalar class is kind itself.

Remarks

A StringDType dtype is the StringDType class (NumPy 2.5.2), which no scalar class is: False.

Exceptions

ArgumentNullException

dtype is null.

TypeError

kind is null or Python's built-in str (NumPy's _preprocess_dtype texts).

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

dtype DType

The dtype (any spelling).

kinds object[]

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

dtype or kinds is 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

dtype DType
kind string

Returns

bool

Examples

np.isdtype(NPTypeCode.Int32, "integral")      // True
np.isdtype(typeof(double), "real floating")   // True
np.isdtype(np.int32, "numeric")               // True

Remarks

Exceptions

ValueError

kind argument is a string, but '…' is not a known kind name. — verbatim NumPy.

TypeError

kind is 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

dtype DType

The descriptor to test.

kinds string[]

The category names (see isdtype(DType, string)).

Returns

bool

True when dtype is under any of the categories.

Exceptions

ArgumentNullException

dtype or kinds is 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

dtype NDScalarType

The scalar class tested.

kind DType

The dtype (any spelling).

Returns

bool

True when dtype is kind'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 dtype is Python's built-in str (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

dtype NDScalarType

The scalar class tested.

kind NDScalarType

The 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

dtype NDScalarType

The scalar class.

kinds object[]

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

kinds is null.

TypeError

dtype is 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

dtype NDScalarType

The scalar class.

kind string

One 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

dtype or kind is null (NumPy's texts for None).

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

dtype NDScalarType

The scalar class.

kinds string[]

The kind names.

Returns

bool

True when the class belongs to at least one kind.

Exceptions

ArgumentNullException

kinds is null.

TypeError

dtype or 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

dtype string
kind string

Returns

bool

isdtype(string, params string[])

isdtype(DType, params string[]) for a dtype STRING.

public static bool isdtype(string dtype, params string[] kinds)

Parameters

dtype string
kinds string[]

Returns

bool

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

a NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

a NDArray

Input array.

Returns

bool

True iff a is 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, so isfortran is False for it — this reports column-major MEMORY ORDER, not mere F-contiguity (use a.flags.f_contiguous for 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

a is 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

element NDArray

Input array.

test_elements NDArray

The values against which to test each value of element. Flattened before use.

assume_unique bool

If 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 element or lies in test_elements.

invert bool

If True, the values in the returned array are inverted, as if calculating element not in test_elements. Default is False.

kind string

The algorithm to use: null (auto), "sort", or "table". Every path gives the same membership, except under assume_unique with 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, or kind='table' over a set whose range is 2**63 - 1 or 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 S text holding a byte that is not ASCII into U (see DefaultEngine.IsinText).

NotSupportedException

A StringDType set whose NA object is a sequence, held by an NA cell (NumPy broadcasts the comparison against it; see DefaultEngine.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

a NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

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.matrix operand 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

a NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x NDArray

The input array.

out NDArray

A 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. If null, 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.matrix operand 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

x NDArray

The input array.

out NDArray

A 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. If null, 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.matrix operand 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

x NDArray

Input 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

x is 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

x NDArray

Input 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

x is null.

isscalar(object)

Returns true incase of a number, bool or string. If null, returns false.

public static bool isscalar(object element)

Parameters

element object

Any 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's isscalar(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: np.issctype was removed in the NumPy 2.0 release. Use issubclass(rep, np.generic) instead.). New code writes NumPy 2's test, np.generic.subclasscheck(rep).

public static bool issctype(object rep)

Parameters

rep object

The object to check: a DType (what np.int32 is), an NPTypeCode or a C# Type. Anything else, null included, is not a scalar type.

Returns

bool

True when rep names a NumSharp storage type: every dtype except Empty. The string classes count, as in NumPy 1.x, where np.issctype(np.str_), np.issctype(np.dtype('S3')) and np.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

arg1 DType

The dtype tested; null is NumPy's None, i.e. float64.

arg2 DType

The 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

arg1 DType

The dtype tested (NumPy's dtype(arg1).type is the class compared); null is NumPy's None, i.e. float64.

arg2 NDScalarType

The scalar class, usually an abstract one (integer, floating, ...); null is float64.

Returns

bool

True when arg1's scalar class is arg2 or 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 converting arg1.

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

arg1 DType

The dtype tested; null is NumPy's None, i.e. float64.

arg2 string

A 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

arg2 is not a dtype string (data type 'integer' not understood, NumPy's text for its TypeError). 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

arg1 NDScalarType

The scalar class tested; null is NumPy's None, i.e. float64.

arg2 DType

The dtype (any spelling: a DType, Type, NPTypeCode or dtype string); null is float64.

Returns

bool

True when arg1 is arg2'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 converting arg2.

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

arg1 NDScalarType

The class tested; a DType also converts here (its scalar class). Null is NumPy's None, i.e. float64.

arg2 NDScalarType

The class tested against; null is NumPy's None, i.e. float64.

Returns

bool

True when arg2 is arg1 or 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

arg1 NPTypeCode

The storage code tested.

arg2 NPTypeCode

The 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

arg1 NPTypeCode

The storage code tested.

arg2 string

A dtype string; null is NumPy's None, i.e. float64.

Returns

bool

True when both name the same dtype class.

Exceptions

TypeError

arg2 is not a dtype string (NumPy's data type 'x' not understood).

NotSupportedException

arg1 has no dtype class, or arg2 names 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

arg1 string

A dtype string; null is NumPy's None, i.e. float64.

arg2 string

A 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

arg1 Type

The C# element type tested; null is NumPy's None, i.e. float64.

arg2 string

A dtype string; null is float64.

Returns

bool

True when both name the same dtype class.

Exceptions

TypeError

arg2 is not a dtype string (NumPy's data type 'x' not understood).

NotSupportedException

arg1 is no dtype's element type, or arg2 names 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

arg1 Type

The first C# element type.

arg2 Type

The second C# element type.

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: np.issubsctype was removed in the NumPy 2.0 release. Use np.issubdtype instead.). New code writes issubdtype(NPTypeCode, NPTypeCode), which this delegates to.

public static bool issubsctype(NPTypeCode arg1, NPTypeCode arg2)

Parameters

arg1 NPTypeCode

The dtype to check; a DType such as np.int32 converts implicitly.

arg2 NPTypeCode

The 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

y object

Input object.

Returns

bool

true if the object is iterable, false otherwise.

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's iter(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

args object[]

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 product a[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

M double

Number of points in the output window. If zero or less, an empty array is returned.

beta double

Shape parameter for the window. As beta grows the window narrows; beta == 0 is 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 M is 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

M is 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

a NDArray

First input array.

b NDArray

Second input array.

Returns

NDArray

A fresh, writeable, C-contiguous array. The result dtype follows NumPy's multiply promotion (NEP50). If b is 0-d the result is the element-wise a * b (which is itself the degenerate Kronecker product). A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_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

a or b is null.

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

a is 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

x1 NDArray

First input array (integer dtype).

x2 NDArray

Second input array (integer dtype); broadcasts against x1.

out NDArray

A location into which the result is stored (NumPy ufunc out=); returned as-is.

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=); masked-off slots keep their prior value.

dtype DType

Explicit 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, or out cannot take the loop dtype.

ArgumentException

where is non-boolean, or out does not broadcast.

ValueError

A numpy.matrix operand 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

x1 NDArray

Mantissa/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.

x2 NDArray

Integer 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 purely x1'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. x1 and x2 broadcast to a common shape.

out NDArray

A 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 float64 out.

where NDArray

Boolean mask (NumPy ufunc where=): only mask-true elements are written to out; masked-off slots keep their prior contents. Must be boolean and broadcast to the result shape.

dtype DType

NumPy's dtype=: the loop's float dtype (float16 / float32 / float64), or null for x1'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^x2 in x1's float tier (or dtype), 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.matrix operand 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 dtype the 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

x1 NDArray

Value operand (integer/bool/char only; bool promotes to int8).

x2 NDArray

Shift-count operand (integer/bool/char only).

out NDArray

A 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.

where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Optional 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 out when 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.matrix operand 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

x1 NDArray

Input array.

x2 NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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

x1 NDArray

Input array.

x2 object

Scalar or array-like value.

Returns

NDArray<bool>

Output array of bools.

less(object, NDArray)

Return (x1 < x2) element-wise with scalar on left.

public static NDArray<bool> less(object x1, NDArray x2)

Parameters

x1 object

Scalar or array-like value.

x2 NDArray

Input array.

Returns

NDArray<bool>

Output array of bools.

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

x1 NDArray

Input array.

x2 NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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

x1 NDArray

Input array.

x2 object

Scalar or array-like value.

Returns

NDArray<bool>

Output array of bools.

less_equal(object, NDArray)

Return (x1 <= x2) element-wise with scalar on left.

public static NDArray<bool> less_equal(object x1, NDArray x2)

Parameters

x1 object

Scalar or array-like value.

x2 NDArray

Input array.

Returns

NDArray<bool>

Output array of bools.

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

keys NDArray

Array whose first-axis sub-arrays are the sort keys.

axis int

Axis to sort along (default -1).

Returns

NDArray

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 StringDType key 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

keys NDArray[]

The k sort keys, all the same shape. Keys are only read.

axis int

Axis to sort along (default -1, the last axis).

Returns

NDArray

int64 index array of the keys' shape. A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.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 StringDType key 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, StringDType ones 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

start NDArray

The 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).

stop NDArray

The end value of the sequence, unless endpoint is false; then the sequence is all but the last of num + 1 evenly spaced samples, and the step changes. Broadcast against start.

num long

Number of samples to generate. Default is 50. Must be non-negative.

endpoint bool

If true, stop is the last sample (written exactly). Default is true.

dtype DType

The 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.

axis int

The axis in the result to store the samples (relevant only for array ends): 0 puts them first, -1 last.

device string

Target device. Only "cpu" and null are accepted (Array-API parity).

Returns

NDArray

The samples, shape (num, *broadcast(start, stop).shape) with the sample axis moved to axis. A numpy.matrix end gives a matrix, as NumPy's _array_converter.wrap does.

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

start or stop is null.

ValueError

A negative num (Number of samples, -1, must be non-negative.), checked first, as NumPy checks it; a device other 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

axis out of range for the result (destination: axis 3 is out of bounds for array of dimension 2).

TypeError

An integer dtype over 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

start object

The starting value: a number (a weak Python number), a NumPy scalar or array, or a list.

stop object

The end value (see linspace(NDArray, NDArray, long, bool, DType, int, string)).

num long

Number of samples to generate. Default is 50. Must be non-negative.

endpoint bool

If true, stop is the last sample. Default is true.

retstep bool

If true, the result also carries the step (step).

dtype DType

The type of the output array, or null for the computation dtype.

axis int

The axis in the result to store the samples (array ends).

device string

Target device. Only "cpu" and null are accepted.

Returns

np.LinspaceResult

The samples, and the step when retstep is 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

start or stop is null.

ValueError

A negative num, or a device other than "cpu"; a ragged list end.

DTypePromotionError

Ends with no inexact common dtype (text ends).

IncorrectShapeException

Ends that do not broadcast.

AxisError

axis out of range for the result.

TypeError

An integer dtype over 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

bytes byte[]
mmap_mode string

Memory-map mode for a .npy file: "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 .npz archive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).

allow_pickle bool

Whether 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 StringDType array, in a .npy file, an .npz member or a bare pickle file — without executing anything it names, and refuses every other pickle. Per NumPy it also lifts max_header_size.

fix_imports bool

Present for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.

encoding string

Present for NumPy parity; validated but otherwise unused. Must be "ASCII", "latin1" or "bytes".

max_header_size long

Reject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when allow_pickle is true.

Returns

object

An NDArray for a .npy file, or an NpzFile for a .npz archive — 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_pickle is false (NumPy's texts).

NotSupportedException

A pickle that is not NumPy's pickle of a StringDType array.

ValueError

Array can't be memory-mapped: Python objects in dtype. (a pickled file with a mmap_mode).

UnicodeError

A .npy pickle whose text is not UTF-8: NumPy's Unpickling 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

file Stream

Path to the file. The type is detected from its magic bytes, not its extension.

mmap_mode string

Memory-map mode for a .npy file: "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 .npz archive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).

allow_pickle bool

Whether 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 StringDType array, in a .npy file, an .npz member or a bare pickle file — without executing anything it names, and refuses every other pickle. Per NumPy it also lifts max_header_size.

fix_imports bool

Present for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.

encoding string

Present for NumPy parity; validated but otherwise unused. Must be "ASCII", "latin1" or "bytes".

max_header_size long

Reject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when allow_pickle is true.

Returns

object

An NDArray for a .npy file, or an NpzFile for a .npz archive — 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_pickle is false (NumPy's texts).

NotSupportedException

A pickle that is not NumPy's pickle of a StringDType array.

ValueError

Array can't be memory-mapped: Python objects in dtype. (a pickled file with a mmap_mode).

UnicodeError

A .npy pickle whose text is not UTF-8: NumPy's Unpickling 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

file string

Path to the file. The type is detected from its magic bytes, not its extension.

mmap_mode string

Memory-map mode for a .npy file: "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 .npz archive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).

allow_pickle bool

Whether 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 StringDType array, in a .npy file, an .npz member or a bare pickle file — without executing anything it names, and refuses every other pickle. Per NumPy it also lifts max_header_size.

fix_imports bool

Present for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.

encoding string

Present for NumPy parity; validated but otherwise unused. Must be "ASCII", "latin1" or "bytes".

max_header_size long

Reject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when allow_pickle is true.

Returns

object

An NDArray for a .npy file, or an NpzFile for a .npz archive — 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_pickle is false (NumPy's texts).

NotSupportedException

A pickle that is not NumPy's pickle of a StringDType array.

ValueError

Array can't be memory-mapped: Python objects in dtype. (a pickled file with a mmap_mode).

UnicodeError

A .npy pickle whose text is not UTF-8: NumPy's Unpickling 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

bytes byte[]
allow_pickle bool

Whether the file is trusted; see load(string, string, bool, bool, string, long).

max_header_size long

Reject headers larger than this.

Returns

NDArray

Exceptions

FormatException

The file is not a .npy file, or is malformed; or it holds a pickle (a StringDType array) and allow_pickle is false.

NotSupportedException

A pickle that is not NumPy's pickle of a StringDType array.

UnicodeError

A pickled text that is not UTF-8 (NumPy's Unpickling a python object failed text).

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

file Stream

An open, readable stream.

allow_pickle bool

Whether the file is trusted.

max_header_size long

Reject headers larger than this.

Returns

NDArray

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

file string

Path to a .npy file.

allow_pickle bool

Whether the file is trusted; see load(string, string, bool, bool, string, long).

max_header_size long

Reject headers larger than this.

Returns

NDArray

Exceptions

FormatException

The file is not a .npy file, or is malformed; or it holds a pickle (a StringDType array) and allow_pickle is false.

NotSupportedException

A pickle that is not NumPy's pickle of a StringDType array.

UnicodeError

A pickled text that is not UTF-8 (NumPy's Unpickling a python object failed text).

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

bytes byte[]
allow_pickle bool

Whether members are trusted.

max_header_size long

Reject 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

file Stream

A readable, seekable stream.

own_stream bool

When true, disposing the archive also disposes the stream.

allow_pickle bool

Whether members are trusted.

max_header_size long

Reject member headers larger than this.

Returns

NpzFile

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

file string

Path to a .npz archive.

allow_pickle bool

Whether members are trusted.

max_header_size long

Reject 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

lines IEnumerable<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.

dtype DType

The 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 a StringDType ('T', np.dtypes.StringDType(...)), which stores every field's text whole.

comments object

What 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.

delimiter string

The column separator, one character; null (default) splits on runs of whitespace and ignores leading whitespace.

converters object

Per-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 the usecols entries as given) to a parser. The parser's result is stored with the dtype's element setter (NumPy's PyArray_Pack).

skiprows int

Skip this many leading lines (blank lines and comments included; quotes are not honored while skipping).

usecols int[]

Which columns to read, in this order (negatives count from the end). Null reads all.

unpack bool

Transpose the result, so its columns unpack as separate arrays.

ndmin int

The minimum number of dimensions (0, 1 or 2); size-1 axes beyond it are squeezed.

encoding string

As for a TextReader: only "bytes" has an effect (a converter's input is the field's Latin-1 form).

max_rows int?

Read at most this many data rows after skiprows (blank and comment-only lines are not counted). Null reads all.

quotechar string

The 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 to ndmin (one row or one column gives a 1-D result, one value a 0-d one), transposed when unpack.

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

lines is null.

ValueError

NumPy's texts: an invalid ndmin, a negative skiprows / 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, comments that 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's str.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_comments meets 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

stream Stream

The 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).

dtype DType

The 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 a StringDType ('T', np.dtypes.StringDType(...)), which stores every field's text whole.

comments object

What 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.

delimiter string

The column separator, one character; null (default) splits on runs of whitespace and ignores leading whitespace.

converters object

Per-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 the usecols entries as given) to a parser. The parser's result is stored with the dtype's element setter (NumPy's PyArray_Pack).

skiprows int

Skip this many leading lines (blank lines and comments included; quotes are not honored while skipping).

usecols int[]

Which columns to read, in this order (negatives count from the end). Null reads all.

unpack bool

Transpose the result, so its columns unpack as separate arrays.

ndmin int

The minimum number of dimensions (0, 1 or 2); size-1 axes beyond it are squeezed.

encoding string

The 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_rows int?

Read at most this many data rows after skiprows (blank and comment-only lines are not counted). Null reads all.

quotechar string

The 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 to ndmin (one row or one column gives a 1-D result, one value a 0-d one), transposed when unpack.

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

stream is 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 negative skiprows / 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, comments that 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's str.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

reader TextReader

The 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).

dtype DType

The 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 a StringDType ('T', np.dtypes.StringDType(...)), which stores every field's text whole.

comments object

What 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.

delimiter string

The column separator, one character; null (default) splits on runs of whitespace and ignores leading whitespace.

converters object

Per-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 the usecols entries as given) to a parser. The parser's result is stored with the dtype's element setter (NumPy's PyArray_Pack).

skiprows int

Skip this many leading lines (blank lines and comments included; quotes are not honored while skipping).

usecols int[]

Which columns to read, in this order (negatives count from the end). Null reads all.

unpack bool

Transpose the result, so its columns unpack as separate arrays.

ndmin int

The minimum number of dimensions (0, 1 or 2); size-1 axes beyond it are squeezed.

encoding string

Text 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 past U+00FF fails 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_rows int?

Read at most this many data rows after skiprows (blank and comment-only lines are not counted). Null reads all.

quotechar string

The 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 to ndmin (one row or one column gives a 1-D result, one value a 0-d one), transposed when unpack.

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

reader is null.

ValueError

NumPy's texts: an invalid ndmin, a negative skiprows / 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, comments that 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's str.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

fname string

Path to the file, found and opened as NumPy's DataSource does: when nothing has that name, the name with .bz2, .gz, .xz or .lzma appended is tried, in that order; a name whose extension is exactly .gz is decompressed (.GZ is 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.

dtype DType

The 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 a StringDType ('T', np.dtypes.StringDType(...)), which stores every field's text whole.

comments object

What 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.

delimiter string

The column separator, one character; null (default) splits on runs of whitespace and ignores leading whitespace.

converters object

Per-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 the usecols entries as given) to a parser. The parser's result is stored with the dtype's element setter (NumPy's PyArray_Pack).

skiprows int

Skip this many leading lines (blank lines and comments included; quotes are not honored while skipping).

usecols int[]

Which columns to read, in this order (negatives count from the end). Null reads all.

unpack bool

Transpose the result, so its columns unpack as separate arrays.

ndmin int

The minimum number of dimensions (0, 1 or 2); size-1 axes beyond it are squeezed.

encoding string

The file's text encoding: any name Python's codecs.lookup resolves (aliases included: "utf-16le", "Windows-1252", "L1") for UTF-8 (utf-8-sig too), UTF-16 and UTF-32 (with or without a BOM; the BOM forms require one, CPython's UTF-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_rows int?

Read at most this many data rows after skiprows (blank and comment-only lines are not counted). Null reads all.

quotechar string

The 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 to ndmin (one row or one column gives a 1-D result, one value a 0-d one), transposed when unpack.

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

fname is null.

ValueError

NumPy's texts: an invalid ndmin, a negative skiprows / 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, comments that 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's str.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's unknown 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-32 file that does not start with a BOM; the undefined codec.

NotSupportedException

A .bz2, .xz or .lzma file (.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

x NDArray

Input value.

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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 out itself 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.matrix operand 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

x NDArray

Input value.

out NDArray

A 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.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

Explicit 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.matrix operand 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

x NDArray

Input value.

out NDArray

A 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.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

Explicit 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.matrix operand 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

x NDArray

Input value.

out NDArray

A 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.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

Explicit 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.matrix operand 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

x1 NDArray

First input array (a log-domain value).

x2 NDArray

Second input array. If shapes differ they must broadcast to a common shape.

out NDArray

A location into which the result is stored (joins the broadcast without being stretched, same_kind-castable from the loop dtype; returned as-is).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x1 NDArray

First input array (a log2-domain value).

x2 NDArray

Second input array. If shapes differ they must broadcast to a common shape.

out NDArray

A location into which the result is stored (NumPy ufunc out=).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x1 NDArray

Input array (any dtype; reduced to its truth value).

x2 NDArray

Input array (any dtype; reduced to its truth value).

out NDArray

A 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.

where NDArray

Boolean mask: only mask-true elements are written; masked-off out slots keep prior contents.

dtype DType

Validate-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). A numpy.char.chararray input gives a chararray VIEW of a text result (NumPy's array_wrap), a plain array of a result of another dtype; a chararray out comes back as a new chararray view of it.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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 dtype descriptor, or a text call NumPy's string loop refuses.

SystemError

A U operand holding a unit above U+10FFFF (NumPy's bool cast of the text).

TypeError

An out the bool result cannot be cast into.

ArgumentException

A where that is not bool, or a mask or out that 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

x NDArray

Input 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).

out NDArray

A location into which the result is stored; any numeric dtype; returned as-is.

where NDArray

Boolean mask: only mask-true elements are written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): non-bool raises the no-loop TypeError.

Returns

NDArray

The element-wise NOT of x's truth values (bool, or out).

Remarks

Exceptions

ValueError

A numpy.matrix operand 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 dtype descriptor.

TypeError

An out the bool result cannot be cast into, or a fixed-width text operand under dtype=bool (NumPy's input-cast refusal).

ArgumentException

A where that is not bool, or a mask or out that 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

x1 NDArray

Input array (any dtype; reduced to its truth value).

x2 NDArray

Input array (any dtype; reduced to its truth value).

out NDArray

A location into which the result is stored; any numeric dtype; returned as-is.

where NDArray

Boolean mask: only mask-true elements are written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): non-bool raises the no-loop TypeError.

Returns

NDArray

The element-wise OR of the operands' truth values (bool, or out). A numpy.char.chararray input gives a chararray VIEW of a text result (NumPy's array_wrap), a plain array of a result of another dtype; a chararray out comes back as a new chararray view of it.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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 dtype descriptor, or a text call NumPy's string loop refuses.

SystemError

A U operand holding a unit above U+10FFFF.

TypeError

An out the bool result cannot be cast into.

ArgumentException

A where that is not bool, or a mask or out that 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

x1 NDArray

Input array (any dtype; reduced to its truth value).

x2 NDArray

Input array (any dtype; reduced to its truth value).

out NDArray

A location into which the result is stored; any numeric dtype; returned as-is.

where NDArray

Boolean mask: only mask-true elements are written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): non-bool raises the no-loop TypeError.

Returns

NDArray

The element-wise XOR of the operands' truth values (bool, or out). A numpy.char.chararray input gives a chararray VIEW of a text result (NumPy's array_wrap), a plain array of a result of another dtype; a chararray out comes back as a new chararray view of it.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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 dtype descriptor, or a text call NumPy's string loop refuses.

SystemError

A U operand holding a unit above U+10FFFF.

TypeError

An out the bool result cannot be cast into.

ArgumentException

A where that is not bool, or a mask or out that 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

start double

base ** start is the starting value of the sequence.

stop double

base ** stop is the final value of the sequence, unless endpoint is False. In that case num + 1 values are spaced over the interval in log-space, of which all but the last are returned (so the step size changes when endpoint is False).

num long

Number of samples to generate. Default 50. Must be non-negative.

endpoint bool

If True (default) stop is the last sample; otherwise it is excluded.

base double

The 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.

dtype DType

The 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 to dtype — so an integer dtype TRUNCATES toward zero (NumPy's power(...).astype(dtype)), unlike linspace(NDArray, NDArray, long, bool, DType, int, string) which floors.

axis int

The axis in the result to store the samples. Relevant only for array-like inputs, which NumSharp's scalar logspace does not take, so it is a no-op here — but it is still validated against the 1-D output: only 0 and -1 are accepted (NumPy moveaxis destination), anything else raises AxisError with NumPy's verbatim "destination:" message.

Returns

NDArray

A 1-D array of num samples, 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 num is negative (NumPy's ValueError).

AxisError

If axis is 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

n int

The returned indices will be valid to access arrays of shape (n, n).

mask_func Func<NDArray, int, NDArray>

A function whose call signature is (arr, k) and which returns n-by-n masked arrays — e.g. triu(NDArray, int) or tril(NDArray, int).

k int

An optional argument passed through to mask_func.

Returns

NDArray<long>[]

The N index arrays of the locations where the mask function is non-zero.

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_func is 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

x1 NDArray

Lhs input array, scalars not allowed.

x2 NDArray

Rhs input array, scalars not allowed.

out NDArray

Where 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 under casting.

axes int[][]

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 with axis.

axis int?

Present for signature parity only. NumPy raises TypeError for any value, because matmul's signature has three DISTINCT core dimensions — use axes.

keepdims bool?

Present for signature parity only. NumPy raises TypeError for ANY value (True OR False), because its output has core dimensions. Modelled with a bool? sentinel so that, like NumPy's np._NoValue default, an explicit false also rejects.

dtype DType

Selects the LOOP: the product runs at this dtype, not merely the result.

casting string

Casting rule (default "same_kind", the ufunc default) gating BOTH the input→loop cast a dtype forces and the product→out cast.

order char

Memory layout of the result — 'C', 'F', 'A' or 'K', in either case (NumPy's order converter).

Returns

NDArray

The matrix product, or out when one is given (a text out receives each product as its scalar's str()).

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.matrix operand 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), keepdims or axis (NumPy's matmul refusals); a null casting (casting must be str, not NoneType).

ValueError

An order letter or a casting name NumPy refuses, with its texts.

INumSharpException

A read-only out (NumPy's ValueError "output array is read-only").

TypeError

A cast casting refuses (NumPy's UFuncTypeError text).

NullReferenceException

x1 or x2 is 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

data NDArray

The 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.

dtype DType

The dtype of the matrix, or null to keep the dtype of data.

copy bool

false returns a view of data (or data itself when it is a matrix) if no dtype conversion is needed.

Returns

NDMatrix

The matrix. With copy it 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

data is null.

ValueError

More than two axes of data are longer than 1 (shape too large to be a matrix.).

IncorrectShapeException

data has 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

data Array

The array, with at most two axes after conversion.

dtype DType

The dtype, or null for the element type (a typed array) or NumPy's discovered dtype (a list: C# integers are int64, as Python ints are).

copy bool

Accepted for signature parity; a C# array is always copied into new memory.

Returns

NDMatrix

A new matrix. Its flags.owndata is false, as in NumPy, where the matrix is a view of the array np.array built.

Remarks

Exceptions

ArgumentNullException

data is null.

ValueError

More than two axes (matrix must be 2-dimensional), or a ragged list (NumPy's inhomogeneous-shape text).

NotSupportedException

A list holding strings, null or 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

data object

The value.

dtype DType

The dtype, or null for the discovered one.

copy bool

Read for an NDArray only; every other value is converted into new memory.

Returns

NDMatrix

The matrix.

Remarks

Exceptions

ArgumentNullException

data is null (NumPy builds an object matrix holding None).

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

data string

The 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), or True / False.

dtype DType

The dtype, or null for 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.

copy bool

Accepted 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

data is null.

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, None or ... 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

x NDArray

Input array having shape (..., M, N) and whose two innermost dimensions form MxN matrices.

Returns

NDArray

An array containing the transpose for each matrix and having shape (..., N, M). A view is returned whenever possible. A numpy.char.chararray operand 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 x has fewer than 2 dimensions.

ValueError

A numpy.matrix operand 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

x1 NDArray

Matrix operand, at least 2-D. Leading axes broadcast.

x2 NDArray

Vector operand, at least 1-D. NOT conjugated.

out NDArray

Where to deposit the answer. Returned as-is when given.

axes int[][]

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.

axis int?

Present for signature parity only. NumPy raises TypeError for any value, because this signature's core dimensions are two DISTINCT ones — use axes.

keepdims bool

Present for signature parity only. NumPy raises TypeError when true, for the same reason.

dtype DType

Selects the LOOP: computation runs at this dtype, not merely the result.

casting string

NumPy's casting=: the rule each input's cast to the loop, and the answer's cast into out, is checked under - no, equiv, safe, same_kind (the default) or unsafe.

order char

NumPy'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 with out.

Returns

NDArray

The matrix-vector products (the operands' loop axes broadcast together), or out itself 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.matrix operand 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; an axes list without three entries; loop axes that do not broadcast together, or a read-only out or one the answer does not broadcast into (NumPy's gufunc iterator texts).

TypeError

axis with axes, or either given; a dtype with details beyond its class; text operands or a text dtype; keepdims.

AxisError

An axes entry of the wrong length, or an axis out of range.

TypeError

An input cannot be cast to the loop, or the answer into out, under casting (NumPy's UFuncTypeError text: Cannot cast ufunc 'matvec' input 0 from dtype('int32') to dtype('float64') with casting rule 'no').

ValueError

A casting or order name NumPy refuses (casting first).

IncorrectShapeException

Loop axes that do not broadcast.

NullReferenceException

x1 or x2 is 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

a NDArray

Input data. A NaN propagates (use nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

The 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 as True). 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, so np.max(a, 1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions, so the result broadcasts against a.

initial object

The 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 / float a 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 with where. null is NumPy's None: no initial value.

where NDArray

A bool mask broadcast against a: only the selected elements are reduced; an output with none selected keeps initial. The C# literals are NumPy's Python bools: true (which converts to a 0-d array) is NumPy's default where=True, no mask at all, and false selects nothing (it needs initial). Footgun: a 0-d bool ARRAY holding true is read the same way, where NumPy treats np.array(True) as a mask that needs initial (with initial both give NumPy's result). null is no mask.

Returns

NDArray

out itself when given; else a fresh array of a's dtype — 0-d (NumPy's read-only scalar) for a flat reduction without keepdims. A numpy.matrix operand gets the matrix method's answer: the scalar without an axis, else a row (1, N) or a column (N, 1); with a matrix out, 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

out is a C# scalar converted to a 0-d array (a bool, number, string, Half or char literal, as in np.max(a, 1, true)): NumPy's "return arrays must be of ArrayType", raised before any other argument is looked at. Also: initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (NumPy calls the matrix method, which has none of them; the first one passed, in that order, is matrix.max() got an unexpected keyword argument 'initial'), raised before anything is computed.

AttributeError

A numpy.matrix operand with a plain (non-matrix) out: NumPy's matrix method stores the maxima into it, then fails on out._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 than a; where without initial ("reduction operation 'maximum' does not have an identity, so to use a where mask one has to specify 'initial'"); an empty reduced axis without initial ("zero-size array to reduction operation maximum which has no identity"); an unconvertible initial (a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast against a (NumPy's "remapped shapes" text).

OverflowError

initial does not fit an integer loop ("Python integer 1000 out of bounds for int8").

ArgumentNullException

a is 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

a NDArray

Input data. A NaN propagates (use nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

The 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 as True). 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, so np.max(a, 1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions, so the result broadcasts against a.

initial object

The 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 / float a 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 with where. null is NumPy's None: no initial value.

where NDArray

A bool mask broadcast against a: only the selected elements are reduced; an output with none selected keeps initial. The C# literals are NumPy's Python bools: true (which converts to a 0-d array) is NumPy's default where=True, no mask at all, and false selects nothing (it needs initial). Footgun: a 0-d bool ARRAY holding true is read the same way, where NumPy treats np.array(True) as a mask that needs initial (with initial both give NumPy's result). null is no mask.

Returns

NDArray

out itself when given; else a fresh array of a's dtype — 0-d (NumPy's read-only scalar) for a flat reduction without keepdims. A numpy.matrix operand gets the matrix method's answer: the scalar without an axis, else a row (1, N) or a column (N, 1); with a matrix out, 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

out is a C# scalar converted to a 0-d array (a bool, number, string, Half or char literal, as in np.max(a, 1, true)): NumPy's "return arrays must be of ArrayType", raised before any other argument is looked at. Also: initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (NumPy calls the matrix method, which has none of them; the first one passed, in that order, is matrix.max() got an unexpected keyword argument 'initial'), raised before anything is computed.

AttributeError

A numpy.matrix operand with a plain (non-matrix) out: NumPy's matrix method stores the maxima into it, then fails on out._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 than a; where without initial ("reduction operation 'maximum' does not have an identity, so to use a where mask one has to specify 'initial'"); an empty reduced axis without initial ("zero-size array to reduction operation maximum which has no identity"); an unconvertible initial (a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast against a (NumPy's "remapped shapes" text).

OverflowError

initial does not fit an integer loop ("Python integer 1000 out of bounds for int8").

ArgumentNullException

a is 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

a NDArray

Input data. A NaN propagates (use nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).

axis NDAxis?

The axis to reduce (negative counts from the end); null reduces 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).

out NDArray

The 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 as True). 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, so np.max(a, 1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions, so the result broadcasts against a.

initial object

The 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 / float a 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 with where. null is NumPy's None: no initial value.

where NDArray

A bool mask broadcast against a: only the selected elements are reduced; an output with none selected keeps initial. The C# literals are NumPy's Python bools: true (which converts to a 0-d array) is NumPy's default where=True, no mask at all, and false selects nothing (it needs initial). Footgun: a 0-d bool ARRAY holding true is read the same way, where NumPy treats np.array(True) as a mask that needs initial (with initial both give NumPy's result). null is no mask.

Returns

NDArray

out itself when given; else a fresh array of a's dtype — 0-d (NumPy's read-only scalar) for a flat reduction without keepdims. A numpy.matrix operand gets the matrix method's answer: the scalar without an axis, else a row (1, N) or a column (N, 1); with a matrix out, 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

out is a C# scalar converted to a 0-d array (a bool, number, string, Half or char literal, as in np.max(a, 1, true)): NumPy's "return arrays must be of ArrayType", raised before any other argument is looked at. Also: initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (NumPy calls the matrix method, which has none of them; the first one passed, in that order, is matrix.max() got an unexpected keyword argument 'initial'), raised before anything is computed.

AttributeError

A numpy.matrix operand with a plain (non-matrix) out: NumPy's matrix method stores the maxima into it, then fails on out._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 than a; where without initial ("reduction operation 'maximum' does not have an identity, so to use a where mask one has to specify 'initial'"); an empty reduced axis without initial ("zero-size array to reduction operation maximum which has no identity"); an unconvertible initial (a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast against a (NumPy's "remapped shapes" text).

OverflowError

initial does not fit an integer loop ("Python integer 1000 out of bounds for int8").

ArgumentNullException

a is 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

x1 NDArray

First operand. If x1.shape != x2.shape they must broadcast to a common shape (the output shape).

x2 NDArray

Second operand. If shapes differ they must broadcast to a common shape.

out NDArray

A 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.

where NDArray

Boolean mask (NumPy ufunc where=): only mask-true elements are computed/written; masked-off out slots keep their prior contents. Must be a bool array (a non-bool mask raises NumPy's 'safe'-cast error).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.

Returns

NDArray

The element-wise maximum of x1 and x2 (or out when 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

out cannot be same_kind-cast from the loop dtype (NumPy-verbatim text).

ArgumentException

where is not bool, or the shapes do not broadcast (NumPy-verbatim texts).

ValueError

A numpy.matrix operand 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: 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.). New code names the dtype it wants.

public static DType maximum_sctype(NPTypeCode t)

Parameters

t NPTypeCode

The input scalar type; a DType such as np.int32 converts 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

a NDArray

First array (any layout; a null reference shares nothing).

b NDArray

Second array, under the same rules as a.

max_work long

Effort cap on the overlap solver, mirroring NumPy's max_work: 0 (the default) checks only the byte bounds — cheap and never raises; -1/-2 solve the collision exactly; a positive value caps the candidate search. Values below -2 are rejected.

Returns

bool

true when the arrays share memory OR the query cannot be decided within the cap — a false is therefore a GUARANTEE of no sharing, while a true is 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_work is 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

a NDArray

Array containing numbers whose mean is desired.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The dtype the sum is computed in and the mean returned in. null is NumPy's default: float64 for bool and integer input, float32 for float16 (with a float16 result), the input's own dtype otherwise.

out NDArray

The 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: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A 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# true literal is NumPy's default. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis without keepdims.

Remarks

Exceptions

ArgumentNullException

a is null.

AxisError

axis is 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

where is not a bool array (NumPy's TypeError text).

IncorrectShapeException

out or where does not broadcast.

TypeError

A C# scalar passed as out; NumPy's text refusals; a numpy.matrix operand with keepdims or where (matrix.mean() got an unexpected keyword argument 'keepdims').

AttributeError

A numpy.matrix operand 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

a NDArray

Array containing numbers whose mean is desired.

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The dtype the sum is computed in and the mean returned in. null is NumPy's default: float64 for bool and integer input, float32 for float16 (with a float16 result), the input's own dtype otherwise.

out NDArray

The 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: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A 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# true literal is NumPy's default. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis without keepdims.

Remarks

Exceptions

ArgumentNullException

a is null.

AxisError

axis is 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

where is not a bool array (NumPy's TypeError text).

IncorrectShapeException

out or where does not broadcast.

TypeError

A C# scalar passed as out; NumPy's text refusals; a numpy.matrix operand with keepdims or where (matrix.mean() got an unexpected keyword argument 'keepdims').

AttributeError

A numpy.matrix operand 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

a NDArray

Array containing numbers whose mean is desired.

axis NDAxis?

The axis to average over (negative counts from the end); null averages every element. Unlike np.sum, a 0-d array takes no axis (np.mean normalizes it first), unless where is 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).

dtype DType

The dtype the sum is computed in and the mean returned in. null is NumPy's default: float64 for bool and integer input, float32 for float16 (with a float16 result), the input's own dtype otherwise.

out NDArray

The 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: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A 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# true literal is NumPy's default. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis without keepdims.

Remarks

Exceptions

ArgumentNullException

a is null.

AxisError

axis is 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

where is not a bool array (NumPy's TypeError text).

IncorrectShapeException

out or where does not broadcast.

TypeError

A C# scalar passed as out; NumPy's text refusals; a numpy.matrix operand with keepdims or where (matrix.mean() got an unexpected keyword argument 'keepdims').

AttributeError

A numpy.matrix operand 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

a NDArray

The data (bool computes as its 0 / 1 values; text: see the exceptions).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

keepdims bool

Whether the reduced axes are kept with length one.

Returns

NDArray

The median (NaN for an empty slice); out itself 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

a is 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); an out that np.median's closing mean(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 out whose 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 _ureduce merges them into an explicit-product length; NumPy 2.4's -1 raised a reshape ValueError.)

TypeError

Text data or a text out: NumPy's closing mean refuses (its verbatim text). A NEP 55 StringDType array is sorted first (NumPy's partition of a StringDType line), then its mean's divide refuses the concatenated text.

ValueError

A StringDType array: a None-like NA in a line of two or more elements (the sort's Cannot compare null that is not a nan-like value), an empty reduced axis (the mean's add.reduce has no identity) or a read-only out.

TypeError

A numpy.char.chararray operand: NumPy's a.partition(kth, axis=...) is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the axes and keepdims' out are checked. With overwrite_input and 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

keepdims with an out NumPy cannot index: _ureduce's out[(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

a NDArray

The data (bool computes as its 0 / 1 values; text: see the exceptions).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

keepdims bool

Whether the reduced axes are kept with length one.

Returns

NDArray

The median (NaN for an empty slice); out itself 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

a is 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); an out that np.median's closing mean(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 out whose 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 _ureduce merges them into an explicit-product length; NumPy 2.4's -1 raised a reshape ValueError.)

TypeError

Text data or a text out: NumPy's closing mean refuses (its verbatim text). A NEP 55 StringDType array is sorted first (NumPy's partition of a StringDType line), then its mean's divide refuses the concatenated text.

ValueError

A StringDType array: a None-like NA in a line of two or more elements (the sort's Cannot compare null that is not a nan-like value), an empty reduced axis (the mean's add.reduce has no identity) or a read-only out.

TypeError

A numpy.char.chararray operand: NumPy's a.partition(kth, axis=...) is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the axes and keepdims' out are checked. With overwrite_input and 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

keepdims with an out NumPy cannot index: _ureduce's out[(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

a NDArray

The data (bool computes as its 0 / 1 values; text: see the exceptions).

axis NDAxis?

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.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

keepdims bool

Whether the reduced axes are kept with length one.

Returns

NDArray

The median (NaN for an empty slice); out itself 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

a is 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); an out that np.median's closing mean(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 out whose 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 _ureduce merges them into an explicit-product length; NumPy 2.4's -1 raised a reshape ValueError.)

TypeError

Text data or a text out: NumPy's closing mean refuses (its verbatim text). A NEP 55 StringDType array is sorted first (NumPy's partition of a StringDType line), then its mean's divide refuses the concatenated text.

ValueError

A StringDType array: a None-like NA in a line of two or more elements (the sort's Cannot compare null that is not a nan-like value), an empty reduced axis (the mean's add.reduce has no identity) or a read-only out.

TypeError

A numpy.char.chararray operand: NumPy's a.partition(kth, axis=...) is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the axes and keepdims' out are checked. With overwrite_input and 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

keepdims with an out NumPy cannot index: _ureduce's out[(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

x1 NDArray
x2 NDArray
x3 NDArray
indexing string
sparse bool
copy bool

Returns

np.MeshgridResult

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

x1 NDArray
x2 NDArray
indexing string
sparse bool
copy bool

Returns

np.MeshgridResult

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

xi NDArray[]

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.

indexing string

"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.

sparse bool

If true, grid i keeps the open-mesh shape (1, …, Ni, …, 1) instead of the full (N1, …, Nn) — these broadcast to the same dense result. Default false.

copy bool

If 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: a numpy.matrix input'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), a numpy.char.chararray input'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

xi is null, or one of its vectors is (the parameter is then named xi[i], after the indexing check).

ValueError

indexing is neither "xy" nor "ij" (Valid values for indexing are 'xy' and 'ij'.); a matrix grid of more than two axes longer than 1 (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

a NDArray

Input data. A NaN propagates (use nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer: the scalar without an axis, else a row or a column; with a matrix out, that out along an axis and a copy of its element without one.

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ..., the first one passed in that order).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

a NDArray

Input data. A NaN propagates (use nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer: the scalar without an axis, else a row or a column; with a matrix out, that out along an axis and a copy of its element without one.

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ..., the first one passed in that order).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

a NDArray

Input data. A NaN propagates (use nanmin(NDArray, NDAxis?, NDArray, bool, object, NDArray) to skip NaNs).

axis NDAxis?

The axis to reduce (negative counts from the end), or null for 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).

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims). A numpy.matrix operand gets the matrix method's answer: the scalar without an axis, else a row or a column; with a matrix out, that out along an axis and a copy of its element without one.

Remarks

Exceptions

TypeError

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ..., the first one passed in that order).

AttributeError

A numpy.matrix operand with a plain out, 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

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

value object

The value to check: a C# scalar (NumPy's Python scalar or NumPy scalar), a C# string (a Python str: <U of 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

value is null (NumPy's None is 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

x1 NDArray

First operand. If x1.shape != x2.shape they must broadcast to a common shape (the output shape).

x2 NDArray

Second operand. If shapes differ they must broadcast to a common shape.

out NDArray

A 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.

where NDArray

Boolean mask (NumPy ufunc where=): only mask-true elements are computed/written; masked-off out slots keep their prior contents. Must be a bool array (a non-bool mask raises NumPy's 'safe'-cast error).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.

Returns

NDArray

The element-wise minimum of x1 and x2 (or out when 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

out cannot be same_kind-cast from the loop dtype (NumPy-verbatim text).

ArgumentException

where is not bool, or the shapes do not broadcast (NumPy-verbatim texts).

ValueError

A numpy.matrix operand 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

typechars object

NumPy's "list of str or array_like", read as NumPy's (isinstance(t, str) and t) or asarray(t).dtype.char for t in typechars reads it:

  • a string: each character is a type character ("fd");
  • an NDArray: its elements along the first axis. A numeric array gives its dtype.char once per element (none for an empty first axis); a ONE-dimensional U / StringDType array gives its elements' TEXT, because NumPy's numpy.str_ elements are str (np.array(new[] { "d", "f" }) reads like "df"; a chararray's text after its rstrip()); an S array gives 'S' (bytes are no str);
  • 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 its dtype.char, a scalar its np.asarray(x).dtype.char (1.5 is '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.

typeset string

The characters the answer may be (default 'GDFgdf'). NumPy tests each type character with t in typeset, a SUBSTRING test, so a multi-character item counts when typeset contains it.

default char

The answer when no type character of typechars is in typeset.

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

typechars is not iterable, with Python's texts: 'NoneType' object is not iterable, 'int' object is not iterable, iteration over a 0-d array; or typeset is 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, whose str.index raises "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

x1 NDArray

Dividend array.

x2 NDArray

Divisor array; broadcasts against x1.

out NDArray

A location into which the result is stored (NumPy ufunc out=; returned as-is).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): computation runs in this dtype.

Returns

NDArray

The floored remainders, or out itself when given.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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's No 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

x1 NDArray
x2 float

Returns

NDArray

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

x NDArray

Input 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), default allocates both.

where NDArray

Optional boolean write mask; masked-off slots of BOTH provided outputs keep their prior contents.

dtype DType

Optional 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 x is 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

a NDArray

The array whose axes are reordered.

source NDAxis

The original positions of the axes to move: one axis or a tuple ((0, 1) or new[] { 0, 1 }), each distinct; negative positions count from the end.

destination NDAxis

The new positions, one per source axis, each distinct.

Returns

NDArray

A view of a with the moved axes (NumPy's a.transpose(order)): it shares memory with a. A numpy.matrix or numpy.char.chararray operand 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

a is null, or an axis argument was converted from a null int[] (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; source is checked whole before destination).

ValueError

An argument repeats an axis (repeated axis in source argument), the two have different lengths (source and destination arguments must have the same number of elements, checked after both are normalized), or a numpy.matrix operand'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

a NDArray

The array whose axes are reordered.

source int

The axis to move (NumPy's source; a negative value counts from the end).

destination int

The axis' new position (NumPy's destination).

Returns

NDArray

A view of a with the moved axes (NumPy's a.transpose(order)): it shares memory with a. A numpy.matrix or numpy.char.chararray operand 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

a is null, or an axis argument was converted from a null int[] (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; source is checked whole before destination).

ValueError

An argument repeats an axis (repeated axis in source argument), the two have different lengths (source and destination arguments must have the same number of elements, checked after both are normalized), or a numpy.matrix operand'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

a NDArray

The array whose axes are reordered.

source int[]

The axes to move, as NumPy's tuple (NumPy's source; not null).

destination int[]

Their new positions, as NumPy's tuple (NumPy's destination; not null).

Returns

NDArray

A view of a with the moved axes (NumPy's a.transpose(order)): it shares memory with a. A numpy.matrix or numpy.char.chararray operand 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

source or destination is null (moveaxis has no None).

ArgumentNullException

a is null, or an axis argument was converted from a null int[] (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; source is checked whole before destination).

ValueError

An argument repeats an axis (repeated axis in source argument), the two have different lengths (source and destination arguments must have the same number of elements, checked after both are normalized), or a numpy.matrix operand'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

x1 NDArray
x2 NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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

enabled bool

Whether kernels are allowed to use more than one thread.

max_threads int

Upper 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

x NDArray

Input data.

copy bool

Whether to create a copy of x (true, the default) or replace values in place (false). With false the returned array may be x itself (writes go through to shared memory).

nan object

Value(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 with 0.0. Cast same_kind into the real dtype, as NumPy's copyto casts it: text and complex fills are refused.

posinf object

Value(s) used to fill +Inf. null (default) fills with the largest finite value representable by x's (real) dtype.

neginf object

Value(s) used to fill -Inf. null (default) fills with the most negative finite value representable by x's (real) dtype.

Returns

NDArray

x with the non-finite values replaced. If copy=false this may be x itself. Integer/boolean/decimal inputs are returned unchanged (a copy when copy=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.matrix operand 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 copyto refusal (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

x is 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

a NDArray

Input data.

Returns

long

Index of the maximum value in the flattened array (NumPy intp = int64).

Remarks

Exceptions

ValueError

All-NaN slice encountered; or a StringDType line of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax's Cannot compare null that is not a nan-like value).

ValueError

A numpy.char.chararray operand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.

ArgumentNullException

a is 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

a NDArray

Input data.

axis NDAxis?

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.

out NDArray

If 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).

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one (with axis null the result has shape (1,) * a.ndim, like NumPy).

Returns

NDArray

Array of int64 indices (or a 0-d scalar for the flattened form); out when 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 StringDType line of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax's Cannot 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 StringDType cell (NumPy's MemoryError text).

ValueError

A numpy.char.chararray operand without out: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; with out the indices are written.

ArgumentNullException

a is 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

a NDArray

Input data.

axis int?

The axis, or null for the flattened array.

out NDArray

The output array, or null (see the NDAxis? form).

keepdims bool

Keep the reduced axis with length one.

Returns

NDArray

The int64 indices; out when 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 StringDType line of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax's Cannot 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 StringDType cell (NumPy's MemoryError text).

ValueError

A numpy.char.chararray operand without out: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; with out the indices are written.

ArgumentNullException

a is 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

a NDArray

Input data.

Returns

long

Index of the minimum value in the flattened array (NumPy intp = int64).

Remarks

Exceptions

ValueError

All-NaN slice encountered; or a StringDType line of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax's Cannot compare null that is not a nan-like value).

ValueError

A numpy.char.chararray operand: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks.

ArgumentNullException

a is 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

a NDArray

Input data.

axis NDAxis?

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.

out NDArray

If provided, the result is inserted into this array and the SAME instance is returned (NumPy semantics — see nanargmax(NDArray, int?, NDArray, bool)).

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one (with axis null the result has shape (1,) * a.ndim, like NumPy).

Returns

NDArray

Array of int64 indices (or a 0-d scalar for the flattened form); out when 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 StringDType line of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax's Cannot 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 StringDType cell (NumPy's MemoryError text).

ValueError

A numpy.char.chararray operand without out: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; with out the indices are written.

ArgumentNullException

a is 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

a NDArray

Input data.

axis int?

The axis, or null for the flattened array.

out NDArray

The output array, or null (see the NDAxis? form).

keepdims bool

Keep the reduced axis with length one.

Returns

NDArray

The int64 indices; out when 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 StringDType line of two or more elements that holds an NA whose NA object is neither a string nor NaN-like (np.argmax's Cannot 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 StringDType cell (NumPy's MemoryError text).

ValueError

A numpy.char.chararray operand without out: NumPy creates the int64 index result as the subclass (Can only create a chararray from string data.), after the argument checks; with out the indices are written.

ArgumentNullException

a is 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

a NDArray

Input array.

axis int?

Axis along which the cumulative product is computed. The default (None) is to compute the cumprod over the flattened array.

dtype DType

Type 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, unless a has an integer dtype with a precision less than that of the default platform integer, in which case the default platform integer is used.

out NDArray

Alternate 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 out is returned.

Returns

NDArray

A new array holding the result unless out is specified, in which case a reference to out is 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); a read-only out; text a numeric dtype cannot parse.

AxisError

axis is out of range.

TypeError

A text operand or request NumPy's loop resolution refuses.

IncorrectShapeException

out does 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

a NDArray

Input array.

axis int?

Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

dtype DType

Type 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, unless a has an integer dtype with a precision less than that of the default platform integer, in which case the default platform integer is used.

out NDArray

Alternate 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 out is returned.

Returns

NDArray

A new array holding the result 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 if axis is not None or a is 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); a read-only out; text a numeric loop cannot parse.

AxisError

axis is out of range.

TypeError

A text operand or request NumPy's loop resolution refuses.

IncorrectShapeException

out does 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

a NDArray

Array containing numbers whose maximum is desired.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.nanmax(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (for a flat reduction: shape (1,)*a.ndim).

initial object

The value every output starts from, or null; required with where. An output whose every selected element is NaN returns it (fmax skips NaN).

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array of a'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). A numpy.matrix operand 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 own np.nan; with a matrix out, 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 fmax reduction schedule — the vector op maxp inside each inner-loop call's vector section, the CRT fmax for its scalar tail — so a ±0 tie 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

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.max() got an unexpected keyword argument ...: NumPy's route ends in the matrix method, which has none of them).

AttributeError

A numpy.matrix operand with a plain out: the method stores the maxima of the NaN-replaced copy into it (an all-NaN slice as -inf), then fails on out._collapse.

ValueError

See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmax' in the texts); an empty reduction without initial raises (fmax has no identity; 'maximum' for a numpy.matrix operand, whose route reduces with the method) — it does not return NaN. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

a NDArray

Array containing numbers whose maximum is desired.

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.nanmax(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (for a flat reduction: shape (1,)*a.ndim).

initial object

The value every output starts from, or null; required with where. An output whose every selected element is NaN returns it (fmax skips NaN).

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array of a'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). A numpy.matrix operand 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 own np.nan; with a matrix out, 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 fmax reduction schedule — the vector op maxp inside each inner-loop call's vector section, the CRT fmax for its scalar tail — so a ±0 tie 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

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.max() got an unexpected keyword argument ...: NumPy's route ends in the matrix method, which has none of them).

AttributeError

A numpy.matrix operand with a plain out: the method stores the maxima of the NaN-replaced copy into it (an all-NaN slice as -inf), then fails on out._collapse.

ValueError

See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmax' in the texts); an empty reduction without initial raises (fmax has no identity; 'maximum' for a numpy.matrix operand, whose route reduces with the method) — it does not return NaN. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

a NDArray

Array containing numbers whose maximum is desired.

axis NDAxis?

The axis to reduce (negative counts from the end), or null for 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).

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.nanmax(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (for a flat reduction: shape (1,)*a.ndim).

initial object

The value every output starts from, or null; required with where. An output whose every selected element is NaN returns it (fmax skips NaN).

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array of a'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). A numpy.matrix operand 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 own np.nan; with a matrix out, 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 fmax reduction schedule — the vector op maxp inside each inner-loop call's vector section, the CRT fmax for its scalar tail — so a ±0 tie 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

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.max() got an unexpected keyword argument ...: NumPy's route ends in the matrix method, which has none of them).

AttributeError

A numpy.matrix operand with a plain out: the method stores the maxima of the NaN-replaced copy into it (an all-NaN slice as -inf), then fails on out._collapse.

ValueError

See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmax' in the texts); an empty reduction without initial raises (fmax has no identity; 'maximum' for a numpy.matrix operand, whose route reduces with the method) — it does not return NaN. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

a NDArray

The array whose mean is desired; any dtype and layout.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The 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).

out NDArray

NumPy's out=: the destination of the sum and the division (returned); for a float or complex input it must be inexact.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy'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 dtype or the input's dtype (float64 for an integer or bool input); a 0-d array for a flat reduction without keepdims. 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

AxisError

axis is outside a'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.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The array whose mean is desired; any dtype and layout.

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The 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).

out NDArray

NumPy's out=: the destination of the sum and the division (returned); for a float or complex input it must be inexact.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy'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 dtype or the input's dtype (float64 for an integer or bool input); a 0-d array for a flat reduction without keepdims. 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

AxisError

axis is outside a'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.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The array whose mean is desired; any dtype and layout.

axis NDAxis?

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).

dtype DType

The 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).

out NDArray

NumPy's out=: the destination of the sum and the division (returned); for a float or complex input it must be inexact.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy'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 dtype or the input's dtype (float64 for an integer or bool input); a 0-d array for a flat reduction without keepdims. 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

AxisError

axis is outside a'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.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The data (bool computes as its 0 / 1 values; text: see the exceptions).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

keepdims bool

Whether the reduced axes are kept with length one.

Returns

NDArray

The NaN-ignoring median; out itself when one is given. Over a NEP 55 StringDType array a median exists only for an all-NaN reduction: its NA object (a read-only 0-d StringDType array, NumPy's Python object), or np.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

a is 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 store out[...] = result (np.nanmedian's, after the computation): an out the 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). A StringDType array: 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.); keepdims over NumPy's Python-object result ('float' object is not subscriptable).

ValueError

A StringDType array: 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 into out (NumPy's setitem texts, e.g. cannot convert float NaN to integer).

NotSupportedException

A StringDType reduction along a long axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.apply_along_axis): NumSharp has no object dtype.

IndexError

Data that is not empty, under keepdims, with an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), 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

a NDArray

The data (bool computes as its 0 / 1 values; text: see the exceptions).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

keepdims bool

Whether the reduced axes are kept with length one.

Returns

NDArray

The NaN-ignoring median; out itself when one is given. Over a NEP 55 StringDType array a median exists only for an all-NaN reduction: its NA object (a read-only 0-d StringDType array, NumPy's Python object), or np.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

a is 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 store out[...] = result (np.nanmedian's, after the computation): an out the 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). A StringDType array: 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.); keepdims over NumPy's Python-object result ('float' object is not subscriptable).

ValueError

A StringDType array: 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 into out (NumPy's setitem texts, e.g. cannot convert float NaN to integer).

NotSupportedException

A StringDType reduction along a long axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.apply_along_axis): NumSharp has no object dtype.

IndexError

Data that is not empty, under keepdims, with an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), 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

a NDArray

The data (bool computes as its 0 / 1 values; text: see the exceptions).

axis NDAxis?

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.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

keepdims bool

Whether the reduced axes are kept with length one.

Returns

NDArray

The NaN-ignoring median; out itself when one is given. Over a NEP 55 StringDType array a median exists only for an all-NaN reduction: its NA object (a read-only 0-d StringDType array, NumPy's Python object), or np.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

a is 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 store out[...] = result (np.nanmedian's, after the computation): an out the 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). A StringDType array: 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.); keepdims over NumPy's Python-object result ('float' object is not subscriptable).

ValueError

A StringDType array: 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 into out (NumPy's setitem texts, e.g. cannot convert float NaN to integer).

NotSupportedException

A StringDType reduction along a long axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.apply_along_axis): NumSharp has no object dtype.

IndexError

Data that is not empty, under keepdims, with an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), 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

a NDArray

Array containing numbers whose minimum is desired.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.nanmin(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (for a flat reduction: shape (1,)*a.ndim).

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array of a's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN. A numpy.matrix operand gets NumPy's subclass route, as in nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with +inf and np.amin.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html. Per dtype:

  • float32 / float64 run NumPy's own fmin reduction schedule — the vector op minp inside each inner-loop call's vector section, the CRT fmin for its scalar tail (whose tie keeps -0 over +0) — so a ±0 tie 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

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out: the method stores the minima of the NaN-replaced copy into it (an all-NaN slice as +inf), then fails on out._collapse.

ValueError

See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmin' in the texts); an empty reduction without initial raises (fmin has no identity; 'minimum' for a numpy.matrix operand). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

a NDArray

Array containing numbers whose minimum is desired.

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.nanmin(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (for a flat reduction: shape (1,)*a.ndim).

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array of a's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN. A numpy.matrix operand gets NumPy's subclass route, as in nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with +inf and np.amin.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html. Per dtype:

  • float32 / float64 run NumPy's own fmin reduction schedule — the vector op minp inside each inner-loop call's vector section, the CRT fmin for its scalar tail (whose tie keeps -0 over +0) — so a ±0 tie 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

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out: the method stores the minima of the NaN-replaced copy into it (an all-NaN slice as +inf), then fails on out._collapse.

ValueError

See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmin' in the texts); an empty reduction without initial raises (fmin has no identity; 'minimum' for a numpy.matrix operand). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

a NDArray

Array containing numbers whose minimum is desired.

axis NDAxis?

The axis to reduce (negative counts from the end), or null for 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).

out NDArray

The array the result is written into and returned. Footgun: the third positional parameter, so np.nanmin(a, 1, true) raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (for a flat reduction: shape (1,)*a.ndim).

initial object

The value every output starts from, or null; required with where.

where NDArray

A bool mask of the elements to reduce, or null.

Returns

NDArray

out itself when given; else a fresh array of a's dtype (0-d for a flat reduction without keepdims). An all-NaN slice without an initial value is NaN. A numpy.matrix operand gets NumPy's subclass route, as in nanmax(NDArray, NDAxis?, NDArray, bool, object, NDArray) with +inf and np.amin.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html. Per dtype:

  • float32 / float64 run NumPy's own fmin reduction schedule — the vector op minp inside each inner-loop call's vector section, the CRT fmin for its scalar tail (whose tie keeps -0 over +0) — so a ±0 tie 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

out is a C# scalar ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; a numpy.matrix operand with keepdims: true, initial or where (matrix.min() got an unexpected keyword argument ...).

AttributeError

A numpy.matrix operand with a plain out: the method stores the minima of the NaN-replaced copy into it (an all-NaN slice as +inf), then fails on out._collapse.

ValueError

See max(NDArray, NDAxis?, NDArray, bool, object, NDArray) ('fmin' in the texts); an empty reduction without initial raises (fmin has no identity; 'minimum' for a numpy.matrix operand). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

ArgumentNullException

a is 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result; 50 or 50.0 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is null.

TypeError

A text q: NumPy divides it by 100 first, and divide has no text loop. Text data: NumPy's NaN test (isnan has no text loop), or the add.reduce refusal of np.nanmean for 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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a (its NaN-like NAs removed, the rest taking np.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 into out (NumPy's setitem texts, e.g. could not convert string to float: 'b').

NotSupportedException

A NEP 55 StringDType reduction along an axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

With weights of 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 an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), raised before the text refusals (isnan), q's rank and the method.

TypeError

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (NumPy divides it by 100 first, and divide has 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

out does 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result; 50 or 50.0 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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.

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is null.

TypeError

A text q: NumPy divides it by 100 first, and divide has no text loop. Text data: NumPy's NaN test (isnan has no text loop), or the add.reduce refusal of np.nanmean for 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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a (its NaN-like NAs removed, the rest taking np.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 into out (NumPy's setitem texts, e.g. could not convert string to float: 'b').

NotSupportedException

A NEP 55 StringDType reduction along an axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

With weights of 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 an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), raised before the text refusals (isnan), q's rank and the method.

TypeError

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (NumPy divides it by 100 first, and divide has 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

out does 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result; 50 or 50.0 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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.

axis NDAxis?

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.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is null.

TypeError

A text q: NumPy divides it by 100 first, and divide has no text loop. Text data: NumPy's NaN test (isnan has no text loop), or the add.reduce refusal of np.nanmean for 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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a (its NaN-like NAs removed, the rest taking np.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 into out (NumPy's setitem texts, e.g. could not convert string to float: 'b').

NotSupportedException

A NEP 55 StringDType reduction along an axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

With weights of 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 an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), raised before the text refusals (isnan), q's rank and the method.

TypeError

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (NumPy divides it by 100 first, and divide has 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

out does 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

a NDArray

Array containing numbers whose product is desired. If a is not an array, a conversion is attempted.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

np.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).

out NDArray

np.prod's out=: the destination, of the expected output shape (returned), or null.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

initial object

np.prod's initial=: the starting value of the product (a Python scalar), or null.

where NDArray

np.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 (out itself 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

axis is outside a's dimensions.

ValueError

A tuple that names an axis twice (duplicate value in 'axis').

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

Array containing numbers whose product is desired. If a is not an array, a conversion is attempted.

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

np.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).

out NDArray

np.prod's out=: the destination, of the expected output shape (returned), or null.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

initial object

np.prod's initial=: the starting value of the product (a Python scalar), or null.

where NDArray

np.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 (out itself 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

axis is outside a's dimensions.

ValueError

A tuple that names an axis twice (duplicate value in 'axis').

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

Array containing numbers whose product is desired. If a is not an array, a conversion is attempted.

axis NDAxis?

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).

dtype DType

np.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).

out NDArray

np.prod's out=: the destination, of the expected output shape (returned), or null.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

initial object

np.prod's initial=: the starting value of the product (a Python scalar), or null.

where NDArray

np.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 (out itself 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

axis is outside a's dimensions.

ValueError

A tuple that names an axis twice (duplicate value in 'axis').

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result; 0.5 or 1 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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 method linear's virtual index (n - 1) * q an integer that NumPy TAKES instead of interpolating (the data's own dtype and element: np.nanquantile(int_array, 1) is an int64).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is 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()'s minimum refusal otherwise). Text data: NumPy's NaN test (isnan has no text loop), or the add.reduce refusal of np.nanmean for 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a (its NaN-like NAs removed, the rest taking np.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 into out (NumPy's setitem texts, e.g. could not convert string to float: 'b').

NotSupportedException

A NEP 55 StringDType reduction along an axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

With weights of 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 an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), raised before the text refusals (isnan), q's rank and the method.

TypeError

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (its [0, 1] check refuses); text data (NumPy's NaN test: isnan has 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

out does 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result; 0.5 or 1 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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 method linear's virtual index (n - 1) * q an integer that NumPy TAKES instead of interpolating (the data's own dtype and element: np.nanquantile(int_array, 1) is an int64).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is 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()'s minimum refusal otherwise). Text data: NumPy's NaN test (isnan has no text loop), or the add.reduce refusal of np.nanmean for 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a (its NaN-like NAs removed, the rest taking np.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 into out (NumPy's setitem texts, e.g. could not convert string to float: 'b').

NotSupportedException

A NEP 55 StringDType reduction along an axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

With weights of 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 an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), raised before the text refusals (isnan), q's rank and the method.

TypeError

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (its [0, 1] check refuses); text data (NumPy's NaN test: isnan has 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

out does 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result; 0.5 or 1 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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 method linear's virtual index (n - 1) * q an integer that NumPy TAKES instead of interpolating (the data's own dtype and element: np.nanquantile(int_array, 1) is an int64).

axis NDAxis?

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.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is 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()'s minimum refusal otherwise). Text data: NumPy's NaN test (isnan has no text loop), or the add.reduce refusal of np.nanmean for 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a (its NaN-like NAs removed, the rest taking np.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 into out (NumPy's setitem texts, e.g. could not convert string to float: 'b').

NotSupportedException

A NEP 55 StringDType reduction along an axis whose row result NumPy stores in an OBJECT array (a None NA object picked by np.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

With weights of 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 an out NumPy cannot index: _ureduce's out[(Ellipsis,) + index_out] (empty data answers np.nanmean first), raised before the text refusals (isnan), q's rank and the method.

TypeError

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (its [0, 1] check refuses); text data (NumPy's NaN test: isnan has 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

out does 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

a NDArray

The array whose standard deviation is desired; any dtype and layout.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The 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).

out NDArray

NumPy's out=: the destination (returned); for a float or complex input it must be inexact.

ddof int

Delta degrees of freedom: the variance's divisor is N - ddof, where N is the number of non-NaN elements of each slice. Default 0.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy's where=: the bool mask of the elements to include, or null for all.

mean NDArray

NumPy's mean=: the mean to use instead of computing it, shaped as with keepdims=True, or null.

correction int?

NumPy's correction=, the Array-API name of ddof, or null; a non-zero ddof with 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

ValueError

A non-zero ddof with correction: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is outside a's dimensions (a 0-d array included).

TypeError

An integer or bool input with an integer dtype and an array result: NumPy's "Cannot cast ufunc 'sqrt' output ..." error, as np.std raises it.

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The array whose standard deviation is desired; any dtype and layout.

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The 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).

out NDArray

NumPy's out=: the destination (returned); for a float or complex input it must be inexact.

ddof int

Delta degrees of freedom: the variance's divisor is N - ddof, where N is the number of non-NaN elements of each slice. Default 0.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy's where=: the bool mask of the elements to include, or null for all.

mean NDArray

NumPy's mean=: the mean to use instead of computing it, shaped as with keepdims=True, or null.

correction int?

NumPy's correction=, the Array-API name of ddof, or null; a non-zero ddof with 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

ValueError

A non-zero ddof with correction: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is outside a's dimensions (a 0-d array included).

TypeError

An integer or bool input with an integer dtype and an array result: NumPy's "Cannot cast ufunc 'sqrt' output ..." error, as np.std raises it.

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The array whose standard deviation is desired; any dtype and layout.

axis NDAxis?

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).

dtype DType

The 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).

out NDArray

NumPy's out=: the destination (returned); for a float or complex input it must be inexact.

ddof int

Delta degrees of freedom: the variance's divisor is N - ddof, where N is the number of non-NaN elements of each slice. Default 0.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy's where=: the bool mask of the elements to include, or null for all.

mean NDArray

NumPy's mean=: the mean to use instead of computing it, shaped as with keepdims=True, or null.

correction int?

NumPy's correction=, the Array-API name of ddof, or null; a non-zero ddof with 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

ValueError

A non-zero ddof with correction: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is outside a's dimensions (a 0-d array included).

TypeError

An integer or bool input with an integer dtype and an array result: NumPy's "Cannot cast ufunc 'sqrt' output ..." error, as np.std raises it.

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

np.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).

out NDArray

np.sum's out=: the destination, of the expected output shape (returned), or null.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

initial object

np.sum's initial=: the starting value of the sum (a Python scalar), or null.

where NDArray

np.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 (out itself 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

axis is outside a's dimensions.

ValueError

A tuple that names an axis twice (duplicate value in 'axis').

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

np.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).

out NDArray

np.sum's out=: the destination, of the expected output shape (returned), or null.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

initial object

np.sum's initial=: the starting value of the sum (a Python scalar), or null.

where NDArray

np.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 (out itself 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

axis is outside a's dimensions.

ValueError

A tuple that names an axis twice (duplicate value in 'axis').

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.

axis NDAxis?

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).

dtype DType

np.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).

out NDArray

np.sum's out=: the destination, of the expected output shape (returned), or null.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

initial object

np.sum's initial=: the starting value of the sum (a Python scalar), or null.

where NDArray

np.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 (out itself 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

axis is outside a's dimensions.

ValueError

A tuple that names an axis twice (duplicate value in 'axis').

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The array whose variance is desired; any dtype and layout.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The 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).

out NDArray

NumPy's out=: the destination (returned); for a float or complex input it must be inexact.

ddof int

Delta degrees of freedom: the divisor is N - ddof. Default 0.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy's where=: the bool mask of the elements to include, or null for all.

mean NDArray

NumPy's mean=: the mean to use instead of computing it, shaped as with keepdims=True, or null.

correction int?

NumPy's correction=, the Array-API name of ddof, or null; a non-zero ddof with it raises.

Returns

NDArray

The variance, in dtype or 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 without keepdims. A slice with no degrees of freedom left (all NaN, or ddof at 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

ValueError

A non-zero ddof with correction: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is outside a's dimensions (a 0-d array included).

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The array whose variance is desired; any dtype and layout.

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The 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).

out NDArray

NumPy's out=: the destination (returned); for a float or complex input it must be inexact.

ddof int

Delta degrees of freedom: the divisor is N - ddof. Default 0.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy's where=: the bool mask of the elements to include, or null for all.

mean NDArray

NumPy's mean=: the mean to use instead of computing it, shaped as with keepdims=True, or null.

correction int?

NumPy's correction=, the Array-API name of ddof, or null; a non-zero ddof with it raises.

Returns

NDArray

The variance, in dtype or 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 without keepdims. A slice with no degrees of freedom left (all NaN, or ddof at 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

ValueError

A non-zero ddof with correction: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is outside a's dimensions (a 0-d array included).

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

a NDArray

The array whose variance is desired; any dtype and layout.

axis NDAxis?

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).

dtype DType

The 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).

out NDArray

NumPy's out=: the destination (returned); for a float or complex input it must be inexact.

ddof int

Delta degrees of freedom: the divisor is N - ddof. Default 0.

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

NumPy's where=: the bool mask of the elements to include, or null for all.

mean NDArray

NumPy's mean=: the mean to use instead of computing it, shaped as with keepdims=True, or null.

correction int?

NumPy's correction=, the Array-API name of ddof, or null; a non-zero ddof with it raises.

Returns

NDArray

The variance, in dtype or 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 without keepdims. A slice with no degrees of freedom left (all NaN, or ddof at 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 a with a non-inexact dtype: "If a is inexact, then dtype must be inexact"; or with a non-inexact out: "If a is inexact, then out must be inexact".

ValueError

A non-zero ddof with correction: "ddof and correction can't be provided simultaneously.". Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is outside a's dimensions (a 0-d array included).

TypeError

A numpy.matrix operand with keepdims: true, initial= or where=: 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

shape Shape

The dimensions. Only Dimensions is read: the strides come from strides or order. With a buffer, the one-dimensional shape -1 takes every whole element after offset. default(Shape) is NumPy's None and is refused.

dtype DType

The 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.

buffer object

The 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.

offset long

The 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 not ALIGNED).

strides long[]

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.

order char?

'C' or 'F' for the row-major or column-major strides; null (NumPy's None, the default) is 'C', 'A' and 'K' mean 'C' here, and lowercase is accepted. Ignored when strides is 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 base is the buffer's owner (an array) or a uint8 array over the whole buffer, writeable when the buffer is, and ALIGNED as 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

shape is default(Shape) (Use () not None as shape arguments); buffer is not a buffer (a bytes-like object is required, not 'list'); or the buffer is too small without strides (buffer is too small for requested array).

ValueError

order is invalid; strides has 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 negative offset puts 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), dtype has no storage yet (datetime64), or dtype is an UNSIZED string ('S', 'U', np.str_): NumPy builds a zero-width S0/U0 array here, which NumSharp's string buffers cannot hold. With a buffer and StringDType on either side: another dtype over a StringDType array's cells, a StringDType dtype 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

arr NDArray

Input array. Anything implicitly convertible to NDArray works (new[,] {{1, 2}, {3, 4}}, a scalar, …), matching NumPy's np.asarray(arr) coercion of array_like input.

Returns

np.NDEnumerate

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

arr NDArray

Returns

np.NDEnumerate<T>

Type Parameters

T

Must 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

a NDArray

Input array (NumPy's keyword a). A C# scalar converts to a 0-d array and a C# array to an array of its rank, so np.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

a is null (NumSharp has no object dtype for NumPy's np.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

shape int[]

Returns

np.NDIndex

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

shape long[]

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 one params overload, so NumPy's "ints, or a single tuple of ints" rule holds for free.

Returns

np.NDIndex

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

op NDArray

The array to iterate over.

flags string[]

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_flags string[]

Per-operand flags: readonly (default), readwrite, writeonly, allocate, no_broadcast, contig, aligned, nbo, copy, updateifcopy, no_subtype, arraymask, writemasked, overlap_assume_elementwise, virtual.

op_dtypes DType[]

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 satisfy casting in the read direction (and the write-back direction for a written operand), and it needs buffered, a copy / updateifcopy operand flag, or a read-only 0-d operand (copied automatically) — else NumPy's TypeError. A list whose length is not the operand count is NumPy's TypeError too.

order char

Iteration order: 'C', 'F', 'A' or 'K' (default).

casting string

Casting rule when making a copy or buffering: "no", "equiv", "safe" (default), "same_kind", "unsafe".

op_axes int[][]

Per-operand list of axes, mapping iterator dimensions to operand dimensions (-1 = newaxis).

itershape long[]

The desired shape of the iterator; a negative entry is deduced from the operands, and its length must equal the op_axes entries' (without op_axes it sets the rank).

buffersize long

Buffer 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 StringDType operand, or a StringDType request over another operand, without refs_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 StringDType copy or buffer transfer cannot allocate a string (NumPy's MemoryError texts).

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

op NDArray[]

The operands to iterate over together (they broadcast against each other); a null entry is an output the iterator allocates.

flags string[]

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_flags string[][]

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_dtypes DType[]

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 satisfy casting in the read direction (and the write-back direction for a written operand), and it needs buffered, a copy / updateifcopy operand flag, or a read-only 0-d operand (copied automatically) — else NumPy's TypeError. A list whose length is not the operand count is NumPy's TypeError too.

order char

Iteration order: 'C', 'F', 'A' or 'K' (default).

casting string

Casting rule when making a copy or buffering: "no", "equiv", "safe" (default), "same_kind", "unsafe".

op_axes int[][]

Per-operand list of axes, mapping iterator dimensions to operand dimensions (-1 = newaxis).

itershape long[]

The desired shape of the iterator; a negative entry is deduced from the operands, and its length must equal the op_axes entries' (without op_axes it sets the rank).

buffersize long

Buffer 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 StringDType operand, or a StringDType request over another operand, without refs_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 StringDType copy or buffer transfer cannot allocate a string (NumPy's MemoryError texts).

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

op NDArray

The array to iterate over.

writeable bool

Open the operand readwrite so assignments through the ref reach the array. Broadcast views are read-only and are rejected, with NumPy's message.

order char

Iteration order: 'K' (default, memory order — matches NumPy's np.nditer), 'C', 'F' or 'A'. See np.NDRefIter<T> for why the default is NOT logical C-order.

Returns

np.NDChunkIter<T>

Type Parameters

T

Must be EXACTLY the array's element type — no conversion or casting is performed, because a ref cannot 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

op NDArray

The array to iterate over.

writeable bool

Open the operand readwrite so assignments through the ref reach the array. Broadcast views are read-only and are rejected, with NumPy's message.

order char

Iteration order: 'K' (default, memory order — matches NumPy's np.nditer), 'C', 'F' or 'A'. See np.NDRefIter<T> for why the default is NOT logical C-order.

Returns

np.NDRefIter<T>

Type Parameters

T

Must be EXACTLY the array's element type — no conversion or casting is performed, because a ref cannot 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

nd NDArray
out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): selects the loop, so negative(bool, dtype: float64) is legal while plain negative(bool) raises (NumPy parity).

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

op NDArray

The array to iterate over.

axes int[][]

One integer list per nesting level; each is used as the op_axes for that level's iterator. Must have at least 2 entries, and no axis may appear in more than one entry.

flags string[]

Global iterator flags (see nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long)).

op_flags string[][]

Per-operand flags.

op_dtypes DType[]

Per-operand iteration dtypes.

order char

Iteration order ('C'/'F'/'A'/'K').

casting string

Casting rule.

buffersize long

Buffer 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); axes that 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

op NDArray[]

The array to iterate over.

axes int[][]

One integer list per nesting level; each is used as the op_axes for that level's iterator. Must have at least 2 entries, and no axis may appear in more than one entry.

flags string[]

Global iterator flags (see nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long)).

op_flags string[][]

Per-operand flags.

op_dtypes DType[]

Per-operand iteration dtypes.

order char

Iteration order ('C'/'F'/'A'/'K').

casting string

Casting rule.

buffersize long

Buffer 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); axes that 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

x1 NDArray

Values to find the next representable value of.

x2 NDArray

The direction where to look for the next representable value of x1. If shapes differ they must broadcast to a common shape.

out NDArray

A location into which the result is stored (NumPy ufunc out=).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

a NDArray

Input array.

Returns

NDArray<long>[]

Indices of elements that are non-zero.

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

x1 NDArray

Input array.

x2 NDArray

Input array.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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.chararray input (0-d, or 1-d with at most np.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 a where mask: 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

x1 NDArray

Input array.

x2 object

Scalar or array-like value.

Returns

NDArray<bool>

Output array of bools.

not_equal(object, NDArray)

Return (x1 != x2) element-wise with scalar on left.

public static NDArray<bool> not_equal(object x1, NDArray x2)

Parameters

x1 object

Scalar or array-like value.

x2 NDArray

Input array.

Returns

NDArray<bool>

Output array of bools.

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

shape Shape

The dimensions: an int (2), a tuple ((2, 3)), an int[] / long[] or a Shape (all convert implicitly). Only the dimensions are read: the layout comes from order, as NumPy's shape is a tuple of ints — a Shape taken from a transposed view gives a C-ordered array unless order says 'F'.

dtype DType

The 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.

order char

'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.

device string

Null 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 setitem converts 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: order is not one of C, F, A, K (order must be one of 'C', 'F', 'A', or 'K' (got 'X')); device is not "cpu" (Device not understood. Only "cpu" is allowed, but received: gpu); order is 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

dtype names 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

a NDArray

The shape and data-type of a define these same attributes of the returned array.

dtype DType

Overrides the data type of the result, or null for a's.

order char

Memory layout: 'C', 'F', 'A' (F when a is F-contiguous and not C-contiguous, else C) or 'K' (the default: a's axis order, kept also for a shape of the same rank), in either case.

shape Shape?

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.

device string

Target device. Only "cpu" and null are 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. A numpy.char.chararray operand 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

order is 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; device is neither null nor "cpu" (NumPy's Device not understood. Only "cpu" is allowed, but received: ...); a negative dimension in shape (negative dimensions are not allowed); a numpy.matrix operand whose result cannot be a matrix (shape too large to be a matrix.).

ValueError

A numpy.char.chararray operand 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

a is 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

a NDArray

First input vector. Input is flattened if not already 1-dimensional.

b NDArray

Second input vector. Input is flattened if not already 1-dimensional.

out NDArray

A location into which the result is stored. Its shape must be (a.size, b.size). Returned as-is when given. NumPy computes outer as a single multiply, so out follows 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

a or b is null.

TypeError

Operands the multiply has no loop for (text with numbers, two texts).

ValueError

A read-only out.

TypeError

An out the product does not reach under same_kind.

ArgumentException

An out the 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

a NDArray

Input array. Must be a boolean or integer dtype (float/complex/decimal raise); read in logical order for any memory layout.

axis int?

Axis to pack along. null (NumPy None) packs the C-order flattened array and returns a 1-D result.

bitorder string

"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; null is treated as "big".

Returns

NDArray

A uint8 array with the packed bits — same ndim as a (except axis=null ⇒ 1-D), F-contiguous iff a is.

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

a is null.

ValueError

bitorder is neither a "big" nor "little" prefix.

TypeError

a is not a boolean/integer dtype.

AxisError

axis is out of bounds for a's rank.

ValueError

A numpy.matrix operand 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

array NDArray

The array to pad.

pad_width IDictionary<int, object>

The per-axis widths, read in the dictionary's order (a later key for the same axis wins).

mode np.PadFunc

The callable that writes each vector's pad area in place.

kwargs object

Passed to mode unchanged.

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

array NDArray

The array to pad.

pad_width IDictionary<int, object>

The per-axis widths, read in the dictionary's order (a later key for the same axis wins).

mode string

The pad mode, as for the other overloads.

constant_values object

The fill of 'constant'.

end_values object

The ends of 'linear_ramp'.

stat_length object

The window of the statistic modes.

reflect_type string

'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_pairs does).

pad(NDArray, int, PadFunc, object)

public static NDArray pad(NDArray array, int pad_width, np.PadFunc mode, object kwargs = null)

Parameters

array NDArray
pad_width int
mode np.PadFunc
kwargs object

Returns

NDArray

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

array NDArray
pad_width int
mode string
constant_values object
end_values object
stat_length object
reflect_type string

Returns

NDArray

Remarks

pad(NDArray, int[,], PadFunc, object)

public static NDArray pad(NDArray array, int[,] pad_width, np.PadFunc mode, object kwargs = null)

Parameters

array NDArray
pad_width int[,]
mode np.PadFunc
kwargs object

Returns

NDArray

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

array NDArray
pad_width int[,]
mode string
constant_values object
end_values object
stat_length object
reflect_type string

Returns

NDArray

pad(NDArray, int[], PadFunc, object)

public static NDArray pad(NDArray array, int[] pad_width, np.PadFunc mode, object kwargs = null)

Parameters

array NDArray
pad_width int[]
mode np.PadFunc
kwargs object

Returns

NDArray

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

array NDArray
pad_width int[]
mode string
constant_values object
end_values object
stat_length object
reflect_type string

Returns

NDArray

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

array NDArray
pad_width (int AxisA, int AxisB)
mode np.PadFunc
kwargs object

Returns

NDArray

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

array NDArray
pad_width (int AxisA, int AxisB)
mode string
constant_values object
end_values object
stat_length object
reflect_type string

Returns

NDArray

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

a NDArray
kth NDArray
axis int?
kind string
order string

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

TypeError

A numpy.char.chararray operand: NumPy's a.partition(kth, axis=...) is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the argument checks.

ArgumentNullException

a is 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

a NDArray

Array to be partitioned.

kth int

Element index to partition by; negative wraps from the end.

axis int?

Axis to partition along. -1 (default) = last axis; null flattens first.

kind string

Selection algorithm — only 'introselect' exists, exactly like NumPy; anything else raises NumPy's verbatim ValueError.

order string

Structured-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

NDArray

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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

TypeError

A numpy.char.chararray operand: NumPy's a.partition(kth, axis=...) is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the argument checks.

ArgumentNullException

a is 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

a NDArray

Array to be partitioned.

kth int[]

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).

axis int?

Axis to partition along. -1 (default) = last axis; null flattens first.

kind string

Selection algorithm — only 'introselect' exists.

order string

Must stay null (no structured dtypes).

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

TypeError

A numpy.char.chararray operand: NumPy's a.partition(kth, axis=...) is the STRING partition (chararray.partition() got an unexpected keyword argument 'axis'), after the argument checks.

ArgumentNullException

a is 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result; 50 or 50.0 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is null.

TypeError

A text q: NumPy divides it by 100 first, and divide has 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a: a line of two or more elements holding a None-like NA (the sort's Cannot compare null that is not a nan-like value), or the unsafe write-back into a numeric out that cannot parse a string (could not convert string to float: 'a').

TypeError

A numpy.char.chararray operand: NumPy's a.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

keepdims with an out NumPy cannot index: _ureduce's out[(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

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (NumPy divides it by 100 first, and divide has no text loop); over text data an interpolating method, an out that 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 out of 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 out of 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result; 50 or 50.0 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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.

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is null.

TypeError

A text q: NumPy divides it by 100 first, and divide has 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a: a line of two or more elements holding a None-like NA (the sort's Cannot compare null that is not a nan-like value), or the unsafe write-back into a numeric out that cannot parse a string (could not convert string to float: 'a').

TypeError

A numpy.char.chararray operand: NumPy's a.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

keepdims with an out NumPy cannot index: _ureduce's out[(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

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (NumPy divides it by 100 first, and divide has no text loop); over text data an interpolating method, an out that 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 out of 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 out of 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 100]: a C# number converts to a 0-d q (a scalar result; 50 or 50.0 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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.

axis NDAxis?

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.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is null.

TypeError

A text q: NumPy divides it by 100 first, and divide has 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a: a line of two or more elements holding a None-like NA (the sort's Cannot compare null that is not a nan-like value), or the unsafe write-back into a numeric out that cannot parse a string (could not convert string to float: 'a').

TypeError

A numpy.char.chararray operand: NumPy's a.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

keepdims with an out NumPy cannot index: _ureduce's out[(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

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (NumPy divides it by 100 first, and divide has no text loop); over text data an interpolating method, an out that 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 out of 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 out of 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

a NDArray

Input array.

axes int[]

If specified, it must be a permutation of [0, 1, ..., N-1] where N is the number of axes of a. Negative indices can also be used. The i-th axis of the returned array will correspond to the axis numbered axes[i] of the input. If not specified, defaults to reversing the order of the axes.

Returns

NDArray

a with its axes permuted. A view is returned whenever possible. A numpy.char.chararray operand 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.matrix operand 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

x NDArray
condlist NDArray
funclist object[]
args object[]

Returns

NDArray

Exceptions

ValueError

A numpy.matrix operand 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

x NDArray

The 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 integer x truncates toward zero, exactly as NumPy's y[cond] = … does.

condlist NDArray[]

The boolean conditions, one per function (a non-bool array is read by nonzero, matching NumPy's asarray(condlist, dtype=bool)). Each condition should have x's shape.

funclist object[]

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 as f(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 to x's dtype). If funclist.Length == condlist.Length + 1 the extra entry is the default, used where every condition is false.

args object[]

Extra positional arguments forwarded to every Func<NDArray, object[], NDArray> entry (NumPy's *args). A plain Func<NDArray, NDArray> entry ignores them.

Returns

NDArray

A fresh array of x's shape and dtype.

Remarks

Exceptions

ValueError

funclist.Length is neither condlist.Length nor condlist.Length + 1.

IndexError

condlist is empty (NumPy accesses condlist[0]).

ValueError

A numpy.matrix operand 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

x NDArray
condlist bool
funclist object[]
args object[]

Returns

NDArray

Exceptions

ValueError

A numpy.matrix operand 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

arr NDArray

Target array (modified in place).

mask NDArray

Boolean mask. Must have the same total size as arr — NumPy allows shape mismatch as long as element counts match.

vals NDArray

Values 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. null is Python's None: one value, converted into arr'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

arr or mask is null.

TypeError

vals is null (None) and arr is an integer (or decimal) array.

ValueError

arr is read-only (checked first, as NumPy does), or mask's size differs from arr's (place: mask and data must be the same size), or vals is empty while some mask entry is True (Cannot insert from an empty array!).

InvalidCastException

An array vals does not cast 'safely' to arr's dtype (NumPy's TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe') — even when arr is empty.

UnicodeEncodeError

Text values that are not ASCII into an S array.

UnicodeDecodeError

Byte values that are not ASCII into a U array.

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 their str().

SystemError

A U mask 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

arr NDArray

Target array (modified in place).

mask NDArray

Boolean mask of arr's size.

vals Array

The values, cycled over the True positions. NumPy converts a list STRAIGHT INTO arr's dtype (PyArray_FromAny(list, arr.dtype), as np.array(vals, dtype=arr.dtype) does), so there is no 'safe' rule: every item is stored by the dtype's setitem — 'RRRR' into a <U3 array truncates to 'RRR', 1.9 into an int array truncates to 1, [1, 2.5] into a <U3 array 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

arr or mask is null.

TypeError

vals is null (None), or holds None, and arr is an integer (or decimal) 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 S array.

UnicodeDecodeError

Byte values that are not ASCII into a U array.

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_zeros NDArray

A 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 (isfinite has 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's array_function_dispatch iterates 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

a1 NDArray
a2 NDArray

Returns

NDArray

Remarks

polyder(NDArray, int)

Return the derivative of the specified order of a polynomial.

public static NDArray polyder(NDArray p, int m = 1)

Parameters

p NDArray

Polynomial 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]]).

m int

Order of differentiation (default 1); 0 returns p as 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

p is null (NumPy's object array of None).

IncorrectShapeException

An N-D p whose rows do not broadcast with the ramp at some order, the discarded m == 0 product included, as NumPy's recursion computes it.

TypeError

A 0-d p at every order (len() of unsized object); text coefficients the multiply has no loop for.

ArgumentNullException

p is 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

u NDArray

Dividend polynomial coefficients.

v NDArray

Divisor polynomial coefficients.

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

x NDArray

x-coordinates, shape (M,).

y NDArray

y-coordinates, shape (M,) or (M, K) (one dataset per column).

deg int

Degree of the fitting polynomial.

rcond double?

Relative condition number; default len(x) * eps.

full bool

When true, the returned PolyfitResult also carries the SVD diagnostics.

w NDArray

Optional weights, shape (M,).

cov object

null/false (default), true, or the string "unscaled" — when truthy the result also carries the covariance matrix (only meaningful when full is false).

Returns

PolyfitResult

A PolyfitResult that converts implicitly to the coefficient array; deconstruct it for the full five-tuple or the cov two-tuple. It carries exactly the arrays NumPy's return holds: the SVD diagnostics (residuals/rank/singular_values) only when full is true, the covariance only when cov is truthy — every other slot is null.

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

x or y is 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

x is 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

p NDArray

Polynomial to integrate (coefficients, highest degree first).

m int

Order of the antiderivative (default 1).

k NDArray

Integration constants, highest-order term first. null (default) means all zero. For m == 1 a 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 than m.

TypeError

With m above 0: a 0-d p (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

p NDArray
m int
k double

Returns

NDArray

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

a1 NDArray

The first polynomial's coefficients, highest degree first.

a2 NDArray

The 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

a1 NDArray
a2 NDArray

Returns

NDArray

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

p NDArray

1-D array of polynomial coefficients, highest degree first.

x NDArray

A 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 of x. With no coefficient, zeros_like(x) — a chararray for a numpy.char.chararray x.

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.); a numpy.char.chararray x with a coefficient (Can only multiply by integers: NumPy's first y * x is 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

p poly1d
x poly1d

Returns

poly1d

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

nd NDArray
out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x1 NDArray

The bases.

x2 NDArray

The exponents; broadcast against x1.

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed / written (NumPy ufunc where=); null is NumPy's where=True.

dtype DType

The loop dtype (NumPy ufunc dtype=): the computation runs in this dtype.

Returns

NDArray

The result of power(NDArray, NDArray, NDArray, NDArray, DType): out itself 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.matrix operand 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

x1 NDArray

The bases.

x2 NDArray

The exponents (array).

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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 (out itself 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.matrix operand 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

precision int?
threshold int?
edgeitems int?
linewidth int?
suppress bool?
nanstr string
infstr string
sign char?
floatmode string

Returns

IDisposable

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

a NDArray

Input data (any numeric dtype; text has no multiply loop and is refused).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The accumulator and result dtype: every element is cast to it before it is multiplied. null is 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, with out, promote_types(out, a) (no small-integer widening).

out NDArray

The 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: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The 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 double truncated into an integer loop, a 0-d array cast). An empty product is the initial value. null is the identity 1.

where NDArray

A bool mask broadcast against a: only the selected elements are multiplied in; an output with none selected is the start value. The C# true literal is NumPy's default. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis without keepdims.

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

a is null.

TypeError

A C# scalar passed as out; a complex initial for a real loop; text (NumPy's refusal); a numpy.matrix operand with keepdims, initial or where (matrix.prod() got an unexpected keyword argument 'keepdims').

ValueError

A read-only or misshapen out; a mask with more axes than a; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

AttributeError

A numpy.matrix operand 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

a NDArray

Input data (any numeric dtype; text has no multiply loop and is refused).

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The accumulator and result dtype: every element is cast to it before it is multiplied. null is 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, with out, promote_types(out, a) (no small-integer widening).

out NDArray

The 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: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The 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 double truncated into an integer loop, a 0-d array cast). An empty product is the initial value. null is the identity 1.

where NDArray

A bool mask broadcast against a: only the selected elements are multiplied in; an output with none selected is the start value. The C# true literal is NumPy's default. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis without keepdims.

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

a is null.

TypeError

A C# scalar passed as out; a complex initial for a real loop; text (NumPy's refusal); a numpy.matrix operand with keepdims, initial or where (matrix.prod() got an unexpected keyword argument 'keepdims').

ValueError

A read-only or misshapen out; a mask with more axes than a; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

AttributeError

A numpy.matrix operand 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

a NDArray

Input data (any numeric dtype; text has no multiply loop and is refused).

axis NDAxis?

The axis to multiply over (negative counts from the end); null multiplies 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).

dtype DType

The accumulator and result dtype: every element is cast to it before it is multiplied. null is 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, with out, promote_types(out, a) (no small-integer widening).

out NDArray

The 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: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The 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 double truncated into an integer loop, a 0-d array cast). An empty product is the initial value. null is the identity 1.

where NDArray

A bool mask broadcast against a: only the selected elements are multiplied in; an output with none selected is the start value. The C# true literal is NumPy's default. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis without keepdims.

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

a is null.

TypeError

A C# scalar passed as out; a complex initial for a real loop; text (NumPy's refusal); a numpy.matrix operand with keepdims, initial or where (matrix.prod() got an unexpected keyword argument 'keepdims').

ValueError

A read-only or misshapen out; a mask with more axes than a; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

AttributeError

A numpy.matrix operand 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

type1 DType

First data type (any spelling that converts to DType).

type2 DType

Second data type.

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's None): "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

a NDArray

The array (numbers or StringDType; fixed-width text is refused as NumPy refuses it).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An optional output of the result's shape; the result is written into it and it is returned.

keepdims bool

Whether the reduced axes stay with length one.

Returns

NDArray

out itself when given; otherwise the range, a fresh array (read-only when 0-d: NumPy's scalar); a numpy.matrix operand 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

a is 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 out that _ptp's maximum.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); a numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

IncorrectShapeException

An out whose 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

a NDArray

The array (numbers or StringDType; fixed-width text is refused as NumPy refuses it).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An optional output of the result's shape; the result is written into it and it is returned.

keepdims bool

Whether the reduced axes stay with length one.

Returns

NDArray

out itself when given; otherwise the range, a fresh array (read-only when 0-d: NumPy's scalar); a numpy.matrix operand 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

a is 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 out that _ptp's maximum.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); a numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

IncorrectShapeException

An out whose 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

a NDArray

The array (numbers or StringDType; fixed-width text is refused as NumPy refuses it).

axis NDAxis?

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 is a - a).

out NDArray

An optional output of the result's shape; the result is written into it and it is returned.

keepdims bool

Whether the reduced axes stay with length one.

Returns

NDArray

out itself when given; otherwise the range, a fresh array (read-only when 0-d: NumPy's scalar); a numpy.matrix operand 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

a is 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 out that _ptp's maximum.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); a numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

IncorrectShapeException

An out whose 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

a NDArray

Target array (modified in place).

ind NDArray

NumPy'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 of a.

v NDArray

NumPy's v: the values to write, read in C order. Cast to a'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 than ind is fine; an empty array writes nothing (NumPy's no-op). null is Python's None, converted into a's dtype (NoneForStore(DType): NaN, nan+nanj, False, 'None', a StringDType NA object; int()'s TypeError for an integer array — raised before the indices' bounds and even for an empty index array, as NumPy converts first).

mode string

Boundary mode: "raise" (default), "wrap", or "clip"; null is NumPy's None (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

a or ind is null.

TypeError

v is null (None) and a is an integer (or decimal) array.

ValueError

A bad mode (NumPy's clipmode_parser texts, see ClipmodeConverter(string)) — reported first, as NumPy parses it with the arguments —, then a read-only a (put: output array is read-only).

TypeError

The index dtype cannot be cast to int64 under the safe rule (float, complex, uint64), an empty index array included.

IndexError

a is empty while ind is not (cannot replace elements of an empty array), or an index is out of bounds under mode="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

arr NDArray

Destination array (Ni..., M, Nk...), modified in place. Must be writeable.

indices NDArray

Integer index array (Ni..., J, Nk...). Must match the dimension count of arr; the non-axis dimensions Ni/Nk need only broadcast against arr. J need not equal M.

values NDArray

Values 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 one arr element (a size-1 arr dimension, or duplicate indices in a slice), the last write in C-order wins. null is Python's None, converted into arr's dtype (NaN, nan+nanj, False, 'None', a StringDType NA object; int()'s TypeError for an integer array, before the indices' bounds are checked).

axis int?

The axis to place 1-D slices along (no default — required, as in NumPy). When null the destination is treated as its C-order flattening: a C-contiguous arr is written back through that flat view (matching NumPy's np.array(arr.flat), which aliases contiguous storage), while a non-contiguous arr raises read-only — NumPy's np.array(arr.flat) yields a read-only copy there, so the assignment fails (probed 2.4.2). indices must then be 1-D.

Remarks

Exceptions

ArgumentNullException

arr or indices is null.

TypeError

values is null (None) and arr is an integer (or decimal) array.

ValueError

axis is null and indices is not 1-D; the dimension counts of arr and indices differ; or values cannot broadcast to the indexing result shape.

IndexError

indices is not an integer array; a non-axis dimension of indices conflicts with arr; 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

axis is out of range for arr's rank.

ValueError

arr (or the non-contiguous axis=null flat 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

a NDArray

Target array (modified in place).

mask NDArray

Boolean 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).

values NDArray

Values to write, cast to a's dtype. Cycled by position: the value written at flat index i is values.flat[i % values.size] (the cursor advances on every element, unlike place(NDArray, NDArray, NDArray) which advances only on True positions). An empty values is a no-op — NumPy returns without touching a (unlike place(NDArray, NDArray, NDArray), which raises). null is Python's None: one value, converted into a's dtype after the mask's size check (NoneForStore(DType): NaN, nan+nanj, False, 'None', a StringDType NA 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

a or mask is null.

TypeError

values is null (None) and a is an integer (or decimal) array.

ValueError

a is read-only (checked first, as NumPy does), or mask's size differs from a's (putmask: mask and data must be the same size).

InvalidCastException

An array values does not cast 'safely' to a'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 S array.

UnicodeDecodeError

Byte values that are not ASCII into a U array.

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 their str().

SystemError

A U mask 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

a NDArray

Target array (modified in place).

mask NDArray

Boolean mask of a's size.

values Array

The 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 <U3 array is ['1', '2.5'] — where np.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

a or mask is null.

TypeError

values is null (None), or holds None, and a is an integer (or decimal) 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 S array.

UnicodeDecodeError

Byte values that are not ASCII into a U array.

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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result; 0.5 or 1 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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 method linear's virtual index (n - 1) * q an integer that NumPy TAKES instead of interpolating (the data's own dtype and element: np.quantile(int_array, 1) is an int64).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is 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()'s minimum refusal 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a: a line of two or more elements holding a None-like NA (the sort's Cannot compare null that is not a nan-like value), or the unsafe write-back into a numeric out that cannot parse a string (could not convert string to float: 'a').

TypeError

A numpy.char.chararray operand: NumPy's a.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

keepdims with an out NumPy cannot index: _ureduce's out[(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

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (its [0, 1] check refuses); over text data an interpolating method (NumPy subtracts the text), an out that 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 out of 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 out of 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result; 0.5 or 1 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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 method linear's virtual index (n - 1) * q an integer that NumPy TAKES instead of interpolating (the data's own dtype and element: np.quantile(int_array, 1) is an int64).

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is 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()'s minimum refusal 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a: a line of two or more elements holding a None-like NA (the sort's Cannot compare null that is not a nan-like value), or the unsafe write-back into a numeric out that cannot parse a string (could not convert string to float: 'a').

TypeError

A numpy.char.chararray operand: NumPy's a.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

keepdims with an out NumPy cannot index: _ureduce's out[(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

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (its [0, 1] check refuses); over text data an interpolating method (NumPy subtracts the text), an out that 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 out of 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 out of 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

a NDArray

The data (any real dtype; text — S, U, NEP 55 StringDType — takes NumPy's take path or its refusal, see the exceptions).

q NDArray

NumPy's array_like q as one array, each value in [0, 1]: a C# number converts to a 0-d q (a scalar result; 0.5 or 1 is NumPy's Python number, weak for the result dtype, so float32 data keeps float32 under interpolation), a double[] 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 method linear's virtual index (n - 1) * q an integer that NumPy TAKES instead of interpolating (the data's own dtype and element: np.quantile(int_array, 1) is an int64).

axis NDAxis?

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.

out NDArray

An optional output array of the result's shape, written and returned itself.

overwrite_input bool

Whether the data may be partitioned in place (NumSharp stages a copy anyway).

method string

The estimation method (linear by default; NumPy's thirteen names).

keepdims bool

Whether the reduced axes are kept with length one.

weights NDArray

NumPy's weights= (keyword-only there), only with method inverted_cdf: one weight per element of a (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; out itself 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

a is null.

ArgumentNullException

q is 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()'s minimum refusal 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 (its q.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

a is complex: "a must be an array of real numbers", NumPy's first statement (before q is read).

TypeError

A NEP 55 StringDType a: an interpolating method (NumPy's _lerp subtracts the two neighbours: unsupported operand type(s) for -: 'str' and 'str', or no subtract loop for a non-scalar result), an out that 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 StringDType a: a line of two or more elements holding a None-like NA (the sort's Cannot compare null that is not a nan-like value), or the unsafe write-back into a numeric out that cannot parse a string (could not convert string to float: 'a').

TypeError

A numpy.char.chararray operand: NumPy's a.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 axis argument).

TypeError

With weights: weights of another shape without an axis, or text weights (the comparison's refusal).

IndexError

keepdims with an out NumPy cannot index: _ureduce's out[(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

a is complex ("a must be an array of real numbers", NumPy's first statement); a text q (its [0, 1] check refuses); over text data an interpolating method (NumPy subtracts the text), an out that 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 out of 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 out of 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

x NDArray

Angle in radians.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

x NDArray

Angles in degrees.

out NDArray
where NDArray
dtype DType

The 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

x is 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

a NDArray

Input array.

order char

The 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. A numpy.char.chararray operand 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_index NDArray[]

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's None, which is refused (TypeError).

dims Shape

The shape of the array the coordinates index (a.shape, a.Shape, an int[], a tuple). An empty shape (NumPy's ()) takes no coordinate array and gives the flat index 0.

mode string

Boundary mode for every axis: "raise" (default — an out-of-range coordinate raises), "wrap" (modulo with sign correction) or "clip" (saturate).

order char

'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_index is 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 bad mode (NumPy's clipmode_parser texts, 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 from dims' 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 (mode raise) 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 ValueError text 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_index NDArray[]

The coordinate arrays, one per dimension (integer or bool; a null entry is NumPy's None, refused).

dims Shape

Shape of the array the indices are unravelling into.

mode string[]

One boundary mode per dimension (NumPy's mode tuple, under NumPy's keyword name; named modes before API-parity batch 7 — so a bare mode: null, which both forms now accept, is a compile-time ambiguity: write (string[])null or (string)null, both NumPy's None); null is NumPy's None, which raises on every dimension.

order char

'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_index is 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 from dims' length; a zero dimension with a coordinate to fold; (mode raise) 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_index long[]

One coordinate per dimension (NumPy's keyword name; named coords before API-parity batch 7).

dims Shape

The shape the coordinates index (a.shape, a.Shape, an int[]); an empty shape takes no coordinate and gives 0.

mode string

"raise" (default), "wrap" or "clip", for every axis.

order char

'C' (default) or 'F', in either case.

Returns

long

The flat index.

Exceptions

ArgumentNullException

multi_index is 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 from dims' length (parameter multi_index must be a sequence of length N); a zero dimension (cannot unravel if shape has zero entries (is empty).); (mode raise) 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

val NDArray

Input array.

Returns

NDArray

For a COMPLEX input: a float64 VIEW onto the real lane — it SHARES memory with val and is writeable, so np.real(z)[i] = x writes through to z[i]'s real part (reproducing NumPy's z.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.matrix operand 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

a NDArray

Input 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).

tol double

Tolerance 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: with tol <= 0 NOTHING collapses (a magnitude |imag| >= 0 is never strictly < 0), even for an exactly-zero imaginary part. The default 100 resolves to 100 * 2.22e-16 ≈ 2.22e-14.

Returns

NDArray

For a COMPLEX input whose imaginary parts are all strictly within tol of zero: a float64 VIEW onto the real lane (shares memory with a, exactly like real(NDArray) / NumPy's a.real). An EMPTY complex array always collapses (an empty all is 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): a itself, 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

a is 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

x NDArray

Input array.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

x1 NDArray

Dividend array.

x2 NDArray

Divisor array; broadcasts against x1.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=).

Returns

NDArray

The floored remainders, or out itself when given.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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's No 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

x1 NDArray
x2 float

Returns

NDArray

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

a NDArray

Input array.

repeats NDArray

Repeat counts. Either a 0-d/size-1 array (broadcast) or a 1-D array of length equal to a.size (axis=None) or a.shape[axis].

axis int?

Axis along which to repeat. null flattens the input.

Returns

NDArray

A new array with elements repeated according to repeats. A numpy.char.chararray operand 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

a or repeats is null.

ValueError

repeats has more than one dimension (object too deep for desired array, checked first).

TypeError

repeats does 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

axis is 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.matrix operand 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

a T

The value to repeat.

repeats NDArray

The 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 a as a 0-d array, NumPy's checks and texts included.

Returns

NDArray

A new 1-D array of a repeated.

Type Parameters

T

The scalar's type; its dtype is the result's (a C# int gives 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

repeats is 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

a NDArray

The object to be converted to a type-and-requirement-satisfying array.

dtype DType

The required data-type. null preserves the current dtype.

requirements IEnumerable

NumPy'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's KeyError: ''), while a string[], a List<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.matrix or 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.
like NDArray

Reference 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.chararray operand 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

a is 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 a numpy.matrix operand 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

a NDArray

Array to be reshaped.

shape Shape

The new shape. One parameter takes every spelling: an int (a 1-D result of that length), a tuple ((2, 3)), an int[] / long[] or a Shape — Shape's implicit conversions. One dimension may be -1: it is inferred from the size and the other dimensions.

order char

The index order the elements are read in and placed in: 'C' (the default, row-major), 'F' (column-major), or 'A' ('F' when a is Fortran-contiguous and not C-contiguous, else 'C'). 'K' is NumPy's ValueError; either case is accepted.

copy bool?

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's ValueError("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 a whenever possible (and always for copy: false), otherwise a view over an internal copy (owndata False either way, as in NumPy). A numpy.char.chararray operand gives a chararray over the result (NumPy creates it as the subclass), owning its data exactly when the plain result would; a numpy.matrix operand 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

a is null.

ValueError

order 'K' is not permitted for reshaping; two -1 dimensions; the copy: false refusal; a numpy.matrix operand 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

a NDArray

Array to be resized.

new_shape Shape

Shape 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.owndata is false, so an in-place ndarray.resize of it is refused — except for an empty source or result, which is NumPy's owning np.zeros_like(a, shape=new_shape). For a numpy.char.chararray operand that zero-filled result is a chararray (zeros_like keeps the subclass); every other result is a plain array (NumPy's np.concatenate drops it).

Remarks

Exceptions

ArgumentNullException

If a is null.

ArgumentException

If any element of new_shape is 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

dtypes DType[]

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

arr1 NDArray

First array; null is NumPy's None, the float64 descriptor.

arr2 NDArray

Second 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

arrays NDArray[]

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)) is longdouble), 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

type1 NPTypeCode

First type code.

type2 NPTypeCode

Second 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

types NPTypeCode[]

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_dtypes object[]

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

dtypes string[]

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

type1 Type

First CLR type; null is NumPy's None, the float64 descriptor.

type2 Type

Second 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

x1 NDArray

Value operand (integer/bool/char only; bool promotes to int8).

x2 NDArray

Shift-count operand (integer/bool/char only).

out NDArray

A location into which the result is stored; must be same_kind-castable from the promoted loop dtype. Returned as-is.

where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Optional 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 out when 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.matrix operand 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

x NDArray

Input array.

out NDArray

A location into which the result is stored (same_kind cast from the loop dtype).

where NDArray

Boolean mask; compute only where true, leaving other out slots unchanged.

dtype DType

Loop 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.matrix operand 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

a NDArray

Input array.

shift NDArray

The 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's int() reads it (a float truncated, a bool 0 / 1), and repeated axes add up their shifts.

axis int

The 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. A numpy.char.chararray operand 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

a or shift is null.

AxisError

An axis is out of range for a's rank.

IncorrectShapeException

shift does not broadcast against the axes (NumPy's ValueError shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (3,) and arg 1 with shape (2,).).

ValueError

shift and 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-d a with the empty tuple (NumPy's not enough values to unpack (expected 2, got 0)); a numpy.matrix operand 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

a NDArray

Input array.

shift NDArray

The 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's int() reads it (a float truncated, a bool 0 / 1), and repeated axes add up their shifts.

axis int[]

The axes as NumPy's tuple, or null for None.

Returns

NDArray

Output array, with the same shape as a: a's memory order along axes, C order for the flattened roll. A numpy.char.chararray operand 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

a or shift is null.

AxisError

An axis is out of range for a's rank.

IncorrectShapeException

shift does not broadcast against the axes (NumPy's ValueError shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (3,) and arg 1 with shape (2,).).

ValueError

shift and 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-d a with the empty tuple (NumPy's not enough values to unpack (expected 2, got 0)); a numpy.matrix operand 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

a NDArray

Input array.

shift NDArray

The 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's int() reads it (a float truncated, a bool 0 / 1), and repeated axes add up their shifts.

axis NDAxis?

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. A numpy.char.chararray operand 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

a or shift is null.

AxisError

An axis is out of range for a's rank.

IncorrectShapeException

shift does not broadcast against the axes (NumPy's ValueError shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (3,) and arg 1 with shape (2,).).

ValueError

shift and 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-d a with the empty tuple (NumPy's not enough values to unpack (expected 2, got 0)); a numpy.matrix operand 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

a NDArray

Input array.

axis int

The axis to roll backwards. The positions of the other axes do not change relative to one another.

start int

The axis is rolled until it lies before this position. The default, 0, results in a “complete” roll.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

p NDArray

Rank-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_zero over the always complex eigvals — complex otherwise.

Remarks

Exceptions

ValueError

p is not rank 1 after atleast_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's array_function_dispatch iterates 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

m NDArray

Array of two or more dimensions.

k int

Number of times the array is rotated by 90 degrees.

axes int[]

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. A numpy.char.chararray operand 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ValueError

axes does 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

m is 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

a NDArray

Input array (NumPy's keyword a; a C# scalar converts to a 0-d array).

decimals int

Number 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]).

out NDArray

A 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, no where= / 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 for decimals >= 0). Unless out was specified, a new array is created (NumPy's read-only scalar for a 0-d input); with it, out itself 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.matrix operand 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

tup NDArray[]

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.matrix operand 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

tup is null.

ValueError

tup is empty (need at least one array to concatenate); arrays whose other axes differ; a numpy.matrix result 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

tup NDArray[]

The arrays (NumPy's sequence).

dtype DType

The result dtype handed to np.concatenate, or null for the arrays' promoted dtype.

casting string

The 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

tup is null.

ValueError

tup is empty; a numpy.matrix result of more than two long axes.

InvalidCastException

An array that does not cast to dtype under casting (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

tup NDListArray[]

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

tup or 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

arr NDArray
allow_pickle bool

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

file Stream

An 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).

arr NDArray

The array to save.

allow_pickle bool

Whether a pickle may be written; see save(string, NDArray, bool).

Remarks

Exceptions

ValueError

A StringDType array with allow_pickle false (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

file string

Target path. .npy is appended if the name does not already end with it, matching NumPy.

arr NDArray

The array to save. Any layout; a Fortran-contiguous array is stored as such.

allow_pickle bool

Whether a pickle may be written (default true, as in NumPy). Only a NEP 55 StringDType array needs one: NumPy writes it as a pickle behind a '|O' header, and with false raises 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 StringDType missing-data object has no pickle form NumSharp writes.

ValueError

Object arrays cannot be saved when allow_pickle=False (a StringDType array with allow_pickle false; 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

file string
arr Array
allow_pickle bool

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

file Stream

An open, writable stream.

arr NDArray

The array to save.

version NpyFormat.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_pickle bool

Whether 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 StringDType array with allow_pickle false (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

stream Stream

The byte stream.

X NDArray

The 1-D or 2-D array to save.

fmt string

A single %-format spec, or a multi-% row format.

delimiter string

String separating columns.

newline string

String separating rows.

header string

String written first, each line prefixed by comments.

footer string

String written last, each line prefixed by comments.

comments string

String prepended to the header / footer lines.

encoding string

The encoding every write is encoded with, on its own (str.encode: the BOM forms write a BOM before EVERY write, as NumPy's WriteWrap does); null or empty is Latin-1, NumPy's default for a byte stream (WriteWrap(fh, encoding or 'latin1')), so a character past U+00FF raises 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

stream is 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 delimiter where 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

stream Stream

The byte stream.

X NDArray

The 1-D or 2-D array to save.

fmt string[]

One format spec per column (else AttributeError).

delimiter string

String separating columns.

newline string

String separating rows.

header string

String written first.

footer string

String written last.

comments string

String prepended to the header / footer lines.

encoding string

As for the single-spec overload (null is Latin-1).

Remarks

Exceptions

ArgumentNullException

stream is 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

writer TextWriter

The text target.

X NDArray

The 1-D or 2-D array to save (a 1-D array is one value per line).

fmt string

A single %-format spec (repeated for every column, joined by delimiter), or a multi-% row format (delimiter then unused).

delimiter string

String separating columns.

newline string

String separating rows.

header string

String written first, each line prefixed by comments.

footer string

String written last, each line prefixed by comments.

comments string

String prepended to the header / footer lines.

encoding string

Accepted for NumPy's signature and IGNORED, as NumPy ignores it for a text target (its WriteWrap encodes only for a stream that refuses str): 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

writer is 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 delimiter where 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

writer TextWriter

The text target.

X NDArray

The 1-D or 2-D array to save.

fmt string[]

One format spec per column (else AttributeError), joined by delimiter.

delimiter string

String separating columns.

newline string

String separating rows.

header string

String written first.

footer string

String written last.

comments string

String prepended to the header / footer lines.

encoding string

Accepted for NumPy's signature and ignored, as for the single-spec overload.

Remarks

Exceptions

ArgumentNullException

writer is 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

fname string

Target path. It is created (or truncated) first, as NumPy's open(fname, 'wt').close(); a name whose extension is exactly .gz is then written gzip-compressed, as NumPy does (.GZ is plain text, as in NumPy). NumPy writes .bz2 / .xz / .lzma names compressed too; .NET has no compressor for them, so NumSharp refuses those names before touching the file.

X NDArray

The 1-D or 2-D array to save (a 0-D or ≥3-D array raises ValueError).

fmt string

A single %-format spec (%.18e, replicated once per column), or a multi-% format string applied to the whole row (in which case delimiter is ignored). For a complex X a single spec becomes ' (%s+%sj)' per column.

delimiter string

String separating columns.

newline string

String separating rows.

header string

String written at the beginning of the file, each line prefixed by comments.

footer string

String written at the end of the file, each line prefixed by comments.

comments string

String prepended to header/footer lines.

encoding string

The file's encoding: any name Python's codecs.lookup resolves for UTF-8 (utf-8-sig too), 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 (LookupError unknown 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 delimiter where 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 newline once a row is built (Mismatch between array dtype …; for a complex array the plain can only concatenate str (not "NoneType") to str); a null header / footer (object of type 'NoneType' has no len()), or a null comments / newline while 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

fname string
X NDArray
fmt string[]

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").

delimiter string
newline string
header string
footer string
comments string
encoding string

Remarks

Exceptions

AttributeError

A spec list of the wrong length, or a null delimiter (Python's None has no join).

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

args NDArray[]

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

kwds IDictionary<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

file Stream
args NDArray[]

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

file Stream
args NDArray[]
kwds IDictionary<string, NDArray>
allow_pickle bool

Whether a member may be pickled — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).

Remarks

Exceptions

ValueError

A StringDType member with allow_pickle false.

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

file Stream
kwds IDictionary<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

file string

Target path. .npz is appended if not already present.

args NDArray[]

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

file string

Target path. .npz is appended if not already present.

args NDArray[]

Positional arrays, stored as arr_0, arr_1, …

kwds IDictionary<string, NDArray>

Named arrays.

allow_pickle bool

Whether a member may be written as a pickle (NumPy's savez(file, *args, allow_pickle=True, **kwds)): a NEP 55 StringDType member needs one, and with false raises 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 kwds collides with a generated arr_N.

ValueError

A StringDType member with allow_pickle false.

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

file string

Target path. .npz is appended if not already present.

kwds IDictionary<string, NDArray>

Name/array pairs. Each becomes <name>.npy in 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

args NDArray[]

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

kwds IDictionary<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

file Stream
args NDArray[]

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

file Stream
args NDArray[]
kwds IDictionary<string, NDArray>
allow_pickle bool

Whether a member may be pickled — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).

Remarks

Exceptions

ValueError

A StringDType member with allow_pickle false.

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

file Stream
kwds IDictionary<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

file string

Target path. .npz is appended if not already present.

args NDArray[]

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

file string
args NDArray[]
kwds IDictionary<string, NDArray>
allow_pickle bool

Whether a member may be pickled — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).

Remarks

Exceptions

ValueError

A StringDType member with allow_pickle false.

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

file string
kwds IDictionary<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: np.sctype2char was removed in the NumPy 2.0 release. Use np.dtype(obj).char instead.). New code reads char.

public static char sctype2char(NPTypeCode sctype)

Parameters

sctype NPTypeCode

A scalar type; a DType such as np.int32 converts 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

a NDArray

Input 1-D array. Must be sorted ascending unless sorter is provided.

v NDArray

Values to insert into a. May be a scalar or any shape.

side string

If "left" (default), the index of the first suitable location is returned. If "right", the last such index.

sorter NDArray

Optional indices that sort a into ascending order (typically argsort(a)).

Returns

NDArray

Array of insertion points with the same shape as v, or a scalar if v is 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

See searchsorted(NDArray, int, string, NDArray).

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 U dtype.

DTypePromotionError

Text with an operand that has no common dtype with it.

NullReferenceException

a or v is 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

a NDArray

Input 1-D array. Must be sorted ascending unless sorter is provided.

v double

Value to insert into a.

side string

If "left" (default), index of the first suitable location is returned. If "right", the last such index.

sorter NDArray

Optional indices that sort a into ascending order (typically argsort(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

See searchsorted(NDArray, int, string, NDArray).

ValueError

See searchsorted(NDArray, int, string, NDArray).

TypeError

See searchsorted(NDArray, int, string, NDArray) (the object path's text names 'float').

NullReferenceException

a is 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

a NDArray

Input 1-D array. Must be sorted ascending unless sorter is provided.

v int

Value to insert into a.

side string

If "left" (default), index of the first suitable location is returned. If "right", the last such index.

sorter NDArray

Optional indices that sort a into ascending order (typically argsort(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

side is not "left" / "right" (NumPy's two ValueError texts).

ValueError

a is not 1-D, a sorter of uint64, a sorter whose size differs from a's, or a sorter index outside a that 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 StringDType a whose first comparison with the key Python refuses ('<' not supported between instances of 'str' and 'int').

NullReferenceException

a is 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

condlist NDArray[]

The conditions that determine which array in choicelist each output element is taken from. Must be boolean arrays and the same length as choicelist. All conditions are broadcast against each other.

choicelist object[]

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, while bool, char, Half, decimal, arrays and every NDArray are strong. An NDArray[] binds here directly via array covariance; scalar choices need an explicit new object[] { … }. All choices AND default are broadcast against each other.

default object

The value inserted where all conditions are false. null (the C# default) is NumPy's default=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

condlist and choicelist differ in length, or condlist is 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

precision int?
threshold int?
edgeitems int?
linewidth int?
suppress bool?
nanstr string
infstr string
sign char?
floatmode string

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

size long

New 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 size is 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

ar1 NDArray

Input array.

ar2 NDArray

Input comparison array.

assume_unique bool

If 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 ar1 that are not in ar2. Sorted when assume_unique is False. A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_wrap: OWNDATA False); a result of another dtype stays plain.

Remarks

Exceptions

UnicodeDecodeError

The membership test's sort path decodes S text holding a byte that is not ASCII (see np.isin).

ValueError

A NEP 55 StringDType array whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy's Cannot compare null that is not a nan-like value.

ArgumentNullException

ar1 is 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

ar1 NDArray

Input array.

ar2 NDArray

Input array.

assume_unique bool

If 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 U result over S text holding a non-ASCII byte.

DTypePromotionError

A StringDType operand beside a class the concatenation finds no common DType with (a number, bool, S bytes): NumPy's verbatim promotion text.

ValueError

A NEP 55 StringDType array whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy's Cannot compare null that is not a nan-like value.

ArgumentNullException

ar1 is 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

a NDArray

Input array (NumPy's keyword a). A C# scalar converts to a 0-d array and a C# array to an array of its shape, so np.shape(5) is empty as NumPy's ().

Returns

long[]

The lengths of a's dimensions, NumPy's tuple as a fresh long[] (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

a is null (NumSharp has no object dtype for NumPy's np.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

a NDArray

First array. Any layout is accepted (contiguous, sliced, strided, transposed, negative-stride, or broadcast view). A null reference has no memory and shares nothing.

b NDArray

Second array, under the same rules as a.

max_work long

Effort cap on the overlap solver, mirroring NumPy's max_work: -1 (the default) and -2 solve the collision EXACTLY however long it takes; 0 checks 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 -2 are rejected.

Returns

bool

true only 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_work is less than -2.

TooHardError

The solver hit the max_work candidate cap (or was restricted to a bounds check via max_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

x NDArray

Input values.

out NDArray

A location into which the result is stored (NumPy ufunc out=); null allocates the result.

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

The loop dtype (NumPy's dtype=): x must cast to it under same_kind, so a float input with an integer dtype is refused. null keeps 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 dtype names another. This is a scalar if x is a scalar.

Remarks

Exceptions

TypeError

A dtype the input cannot reach under same_kind (Cannot cast ufunc 'sign' input from dtype('float64') to dtype('int64') with casting rule 'same_kind'; NumPy raises UFuncTypeError).

ValueError

A numpy.matrix operand 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

x NDArray

Input array. Complex is unsupported (raises TypeError).

out NDArray

A location into which the result is stored; any numeric dtype (bool casts same_kind to all, True→1); returned as-is.

where NDArray

Boolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.

dtype DType

Validate-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 where x'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

x is complex — signbit has no complex loop (NumPy raises the same, its signbit is ambiguous on complex).

ValueError

A numpy.matrix operand 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

x NDArray

Angle, in radians (2 \pi rad equals 360 degrees).

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x NDArray

Input 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 as x, 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

x is null (NumPy would attempt asanyarray(None); NumSharp rejects it up front rather than surfacing a bare NullReferenceException).

OverflowException

x is a Decimal array whose pi*x overflows 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

x NDArray

Input array.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

a NDArray

Input data.

axis int

The axis (NumPy's axis=k; a negative value counts 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

a is 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

a NDArray

Input data.

axis int[]

The axes as NumPy's tuple, or null for None.

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

a is 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

a NDArray

Input data.

axis NDAxis?

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

a is 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

a NDArray

Array to sort.

axis int?

Axis to sort along. -1 = last axis. null = sort the flattened array.

kind string

The 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.

order object

Field names to sort by. No NumSharp dtype has fields, so any value is refused, as NumPy refuses it for an array without fields.

stable bool?

NumPy's keyword-only stable: true asks for the stable kind. It cannot be combined with kind (false included).

descending bool?

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 with kind (false included); null and false sort ascending.

Returns

NDArray

The sorted copy, laid out as a.copy(order='K') (a 1-D C array for axis=null). A numpy.char.chararray operand 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, kind given with stable or descending, or an order; or a numpy.matrix operand 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 StringDType array sorted descending (unsupported sort kind).

ValueError

A StringDType line of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy's Cannot compare null that is not a nan-like value, raised after the lines before it were sorted).

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

ArgumentNullException

a is 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

a NDArray

Input array.

Returns

NDArray

Sorted complex array (sorted along the last axis). A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.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's b.sort() raises).

ValueError

Text that is not a complex number (complex() arg is a malformed string): NumPy sorts the text, then astype('D') parses it, the first malformed string in the sorted array's C order raising. A StringDType array: a None-like NA in a line of two or more elements (the sort's Cannot 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

a is 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

x NDArray

Input array (float family; integer/bool inputs promote to a float per NumPy's width rule, complex is rejected).

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=); masked-off slots of out keep their prior contents.

dtype DType

Explicit 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 x holding each element's spacing. This is a scalar if x is 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.matrix operand 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

ary NDArray

Array to be divided into sub-arrays.

indices_or_sections int

If 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.

axis int

The axis along which to split, default is 0.

Returns

NDArray[]

A list of sub-arrays as views into ary. A numpy.char.chararray operand gives chararrays over the results (NumPy creates them as the subclass).

Remarks

Exceptions

ArgumentNullException

ary is null.

IndexError

axis is out of range: NumPy reads ary.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.matrix operand 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

ary NDArray

Array to be divided into sub-arrays.

indices int[]

The split points along axis: [2, 3] gives ary[: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.

axis int

The axis along which to split, default is 0.

Returns

NDArray[]

indices.Length + 1 sub-arrays as views into ary. A numpy.char.chararray operand 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

ary is null, or indices is.

IndexError

axis is out of range ("tuple index out of range"; a 0-d array refuses every axis).

ValueError

A numpy.matrix operand 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

ary NDArray

Array to be divided into sub-arrays.

indices long[]

The split points along axis: [2, 3] gives ary[: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.

axis int

The axis along which to split, default is 0.

Returns

NDArray[]

indices.Length + 1 sub-arrays as views into ary. A numpy.char.chararray operand 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

ary is null, or indices is.

IndexError

axis is out of range ("tuple index out of range"; a 0-d array refuses every axis).

ValueError

A numpy.matrix operand 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

x NDArray

The values whose square-roots are required.

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x NDArray

Input data.

out NDArray

A 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).

where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit loop dtype (NumPy ufunc dtype=): the input must be same_kind-castable to it.

Returns

NDArray

Element-wise x*x (out itself 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.matrix operand 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

a NDArray

Input data.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

Returns

NDArray

A view of a with the selected dimensions of length 1 removed: a fresh view object every time, a.view() when there is nothing to remove (NumPy returns a itself there; a fresh view keeps disposing the result from disposing the input - the plan's D15). A numpy.char.chararray operand 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.matrix operand 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

a NDArray

Input data.

axis int[]

The axes as NumPy's tuple, or null for None.

Returns

NDArray

A view of a with the selected dimensions of length 1 removed: a fresh view object every time, a.view() when there is nothing to remove (NumPy returns a itself there; a fresh view keeps disposing the result from disposing the input - the plan's D15). A numpy.char.chararray operand 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.matrix operand 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

a NDArray

Input data.

axis NDAxis?

NumPy's axis: null (None, the default) removes every axis of length one; one axis removes only that axis; a tuple ((0, 2) or new[] { 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 a with the selected dimensions of length 1 removed: a fresh view object every time, a.view() when there is nothing to remove (NumPy returns a itself there; a fresh view keeps disposing the result from disposing the input - the plan's D15). A numpy.char.chararray operand 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.matrix operand 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

arrays NDArray[]

Each array must have the same shape.

axis int

The axis in the result array along which the input arrays are stacked.

out NDArray

NumPy's out=: the destination of the stacked result (it must have the result's shape; the values are cast into it under casting), returned itself; null allocates.

dtype DType

NumPy's dtype=: the result's dtype (the inputs are cast to it under casting); null promotes the inputs. Cannot be combined with out.

casting string

NumPy'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 n 0-d arrays gives shape (n,). A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.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

arrays is null.

ValueError

arrays is 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

axis is 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.matrix operand 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 / out does not reach under casting (NumPy's Cannot cast array data from ... according to the rule ...), or both out and dtype.

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

a NDArray

The values whose standard deviation is desired.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The 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.

out NDArray

The 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: and keepdims: by name.

ddof int

Delta degrees of freedom: the variance divides by max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). The C# true literal is NumPy's default; null is no mask.

mean NDArray

The mean to subtract instead of computing it, used as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null.

correction int?

The Array API's name of ddof (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

Exceptions

ArgumentNullException

a is null.

ValueError

A nonzero ddof together with correction (raised first); a read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is out of bounds.

TypeError

An integer or bool dtype with a result that has dimensions, or an integer or bool out: NumPy's Cannot cast ufunc 'sqrt' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'.

ArgumentException

A non-bool where.

IncorrectShapeException

out, where or mean does not broadcast against a.

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; a numpy.matrix operand with keepdims, where or mean.

AttributeError

A numpy.matrix operand 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

a NDArray

The values whose standard deviation is desired.

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The 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.

out NDArray

The 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: and keepdims: by name.

ddof int

Delta degrees of freedom: the variance divides by max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). The C# true literal is NumPy's default; null is no mask.

mean NDArray

The mean to subtract instead of computing it, used as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null.

correction int?

The Array API's name of ddof (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

Exceptions

ArgumentNullException

a is null.

ValueError

A nonzero ddof together with correction (raised first); a read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is out of bounds.

TypeError

An integer or bool dtype with a result that has dimensions, or an integer or bool out: NumPy's Cannot cast ufunc 'sqrt' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'.

ArgumentException

A non-bool where.

IncorrectShapeException

out, where or mean does not broadcast against a.

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; a numpy.matrix operand with keepdims, where or mean.

AttributeError

A numpy.matrix operand 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

a NDArray

The values whose standard deviation is desired.

axis NDAxis?

The axis to compute along (negative counts from the end); null uses every element. A 0-d array takes no axis unless where is 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).

dtype DType

The 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.

out NDArray

The 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: and keepdims: by name.

ddof int

Delta degrees of freedom: the variance divides by max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)). The C# true literal is NumPy's default; null is no mask.

mean NDArray

The mean to subtract instead of computing it, used as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null.

correction int?

The Array API's name of ddof (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

Exceptions

ArgumentNullException

a is null.

ValueError

A nonzero ddof together with correction (raised first); a read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is out of bounds.

TypeError

An integer or bool dtype with a result that has dimensions, or an integer or bool out: NumPy's Cannot cast ufunc 'sqrt' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'.

ArgumentException

A non-bool where.

IncorrectShapeException

out, where or mean does not broadcast against a.

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; a numpy.matrix operand with keepdims, where or mean.

AttributeError

A numpy.matrix operand 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

x1 NDArray
x2 NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

a NDArray

Elements to sum (any dtype; StringDType concatenates, fixed-width text is refused).

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The 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. null is 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, with out, promote_types(out, a) (no small-integer widening: an int8 sum into an int8 out wraps in int8).

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions, so the result broadcasts against a.

initial object

The 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: 1000 into an int8 loop raises), a double a Python float (truncated into an integer loop), a 0-d NDArray is cast. An empty sum is the initial value. null is NumPy's default, the identity 0 (NumPy's initial=None, which starts from each output's first element, has no C# spelling).

where NDArray

A bool mask broadcast against a: only the selected elements are summed, and an output with none selected is the start value. The C# true literal is NumPy's default where=True; false selects nothing. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis without keepdims.

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

a is null.

TypeError

out is a C# scalar converted to a 0-d array ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; NumPy's text refusals; a numpy.matrix operand with keepdims, initial or where (NumPy calls matrix.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 than a; an unconvertible initial (a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast against a.

OverflowError

initial does not fit an integer loop ("Python integer 1000 out of bounds for int8").

AttributeError

A numpy.matrix operand with a plain (non-matrix) out: NumPy's matrix method computes into it and then calls out._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

a NDArray

Elements to sum (any dtype; StringDType concatenates, fixed-width text is refused).

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The 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. null is 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, with out, promote_types(out, a) (no small-integer widening: an int8 sum into an int8 out wraps in int8).

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions, so the result broadcasts against a.

initial object

The 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: 1000 into an int8 loop raises), a double a Python float (truncated into an integer loop), a 0-d NDArray is cast. An empty sum is the initial value. null is NumPy's default, the identity 0 (NumPy's initial=None, which starts from each output's first element, has no C# spelling).

where NDArray

A bool mask broadcast against a: only the selected elements are summed, and an output with none selected is the start value. The C# true literal is NumPy's default where=True; false selects nothing. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis without keepdims.

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

a is null.

TypeError

out is a C# scalar converted to a 0-d array ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; NumPy's text refusals; a numpy.matrix operand with keepdims, initial or where (NumPy calls matrix.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 than a; an unconvertible initial (a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast against a.

OverflowError

initial does not fit an integer loop ("Python integer 1000 out of bounds for int8").

AttributeError

A numpy.matrix operand with a plain (non-matrix) out: NumPy's matrix method computes into it and then calls out._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

a NDArray

Elements to sum (any dtype; StringDType concatenates, fixed-width text is refused).

axis NDAxis?

The axis to sum over (negative counts from the end); null sums 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).

dtype DType

The 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. null is 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, with out, promote_types(out, a) (no small-integer widening: an int8 sum into an int8 out wraps in int8).

out NDArray

The 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; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions, so the result broadcasts against a.

initial object

The 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: 1000 into an int8 loop raises), a double a Python float (truncated into an integer loop), a 0-d NDArray is cast. An empty sum is the initial value. null is NumPy's default, the identity 0 (NumPy's initial=None, which starts from each output's first element, has no C# spelling).

where NDArray

A bool mask broadcast against a: only the selected elements are summed, and an output with none selected is the start value. The C# true literal is NumPy's default where=True; false selects nothing. null is no mask.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis without keepdims.

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

a is null.

TypeError

out is a C# scalar converted to a 0-d array ("return arrays must be of ArrayType"); initial is complex for a real loop or of an unconvertible type; NumPy's text refusals; a numpy.matrix operand with keepdims, initial or where (NumPy calls matrix.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 than a; an unconvertible initial (a float NaN into an integer loop, a sequence). Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array (NumPy's TypeError text).

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast against a.

OverflowError

initial does not fit an integer loop ("Python integer 1000 out of bounds for int8").

AttributeError

A numpy.matrix operand with a plain (non-matrix) out: NumPy's matrix method computes into it and then calls out._collapse.

swapaxes(NDArray, int, int)

Interchange two axes of an array.

public static NDArray swapaxes(NDArray a, int axis1, int axis2)

Parameters

a NDArray

Input array.

axis1 int

First axis.

axis2 int

Second axis.

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

a NDArray

Source array.

indices NDArray

Integer array of indices to take (any layout; read in C order).

axis int?

Axis along which to take. null (default) flattens a and treats indices as flat indices. A 0-d a is flattened too, so its axis must be valid for one dimension (0 or -1).

out NDArray

Optional 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 returns out itself. When null (default), a fresh array is allocated with a's dtype.

mode string

Boundary mode: "raise" (default — throw on OOB), "wrap" (modulo with sign correction), or "clip" (saturate); null is NumPy's None (raise).

Returns

NDArray

New array with shape:

  • axis=None: same as indices.
  • axis=k: a.shape[:k] + indices.shape + a.shape[k+1:].

Dtype matches a (or out's dtype when out is supplied). A numpy.char.chararray operand gives a chararray over the result; a 0-d result without out is 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

a or indices is null.

ValueError

A bad mode (ClipmodeConverter(string)), checked first; an out of another shape (output array does not match result of ndarray.take) or a read-only one (WRITEBACKIFCOPY base is read-only).

AxisError

axis is out of range.

TypeError

The index dtype does not cast to int64 under same_kind (float, complex), an empty index array included; or out's dtype does not cast to a's under safe.

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 under mode="raise" (index 9 is out of bounds for axis 0 with size 4).

ValueError

A numpy.matrix operand 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

arr NDArray

Source array (Ni..., M, Nk...).

indices NDArray

Integer index array (Ni..., J, Nk...). Must match the dimension count of arr; the non-axis dimensions Ni/Nk only need to broadcast against arr.

axis int?

The axis to take 1-D slices along (default -1, matching NumPy 2.3+). When null the source is treated as if first flattened to 1-D in C-order, for consistency with sort/argsort; then indices must be 1-D.

Returns

NDArray

A fresh C-contiguous array of shape (Ni..., J, Nk...) (the broadcast of the non-axis dimensions, with J = indices.shape[axis]) and dtype of arr. A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_wrap: OWNDATA False); a result of another dtype stays plain.

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x NDArray

Angle, in radians (2 \pi rad equals 360 degrees).

out NDArray
where NDArray

Boolean mask: only mask-true elements are computed/written (NumPy ufunc where=).

dtype DType

Explicit 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.matrix operand 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

x NDArray

Input array.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

a NDArray

The first tensor (not null).

b NDArray

The second tensor (not null).

axes int

How many trailing axes of a to contract against leading axes of b. 0 gives the outer (tensor) product; 1 is dot(NDArray, NDArray, NDArray); 2 (the default) is the double contraction. A NEGATIVE count contracts nothing — NumPy forms range(-axes, 0), which is empty for any axes <= 0.

Returns

NDArray

A new array of a's kept axes followed by b'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 StringDType operand beside a number (NumPy's object product).

NullReferenceException

a or b is 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

a NDArray

The first tensor (not null).

b NDArray

The second tensor (not null).

axes (int AxisA, int AxisB)

The axis of a and the axis of b to contract.

Returns

NDArray

A new array of a's kept axes followed by b'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 StringDType operand beside a number.

NullReferenceException

a or b is 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

a NDArray

The first tensor (not null).

b NDArray

The second tensor (not null).

axes (int[] AxesA, int[] AxesB)

NumPy's pair of axis lists: AxesA, the axes of a to contract in pairing order, and AxesB, the axes of b paired with them element by element.

Returns

NDArray

A new array of a's kept axes followed by b'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 StringDType operand beside a number (NumPy's object product).

NullReferenceException

a, b or 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

A NDArray

The input array.

reps Shape

The number of repetitions of A along each axis, as ONE argument: an int (2), a tuple ((2, 3)), an int[] / long[] or a Shape (all convert implicitly; only the values are read). An empty reps is a copy of A.

Returns

NDArray

The tiled output array, of A's dtype: C-contiguous for a real repetition, a keep-order copy for all-one repetitions. A numpy.char.chararray operand 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

A is null.

ValueError

A negative repetition that NumPy's repeat reaches while the tile still holds elements (negative dimensions are not allowed); a numpy.matrix operand 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

a NDArray

Source array. Must have at least 2 dimensions.

offset int

Offset of the diagonal from the main diagonal. See diagonal(NDArray, int, int, int) for details.

axis1 int

First axis of the 2-D sub-array. Default 0.

axis2 int

Second axis of the 2-D sub-array. Default 1.

dtype DType

Output dtype. null (default) preserves a.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.

out NDArray

Optional output array. Shape must equal the natural reduction output; values are copied with unsafe casting and the method returns out itself. Without dtype the sum runs in promote_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.shape minus axis1 and axis2.

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

a has fewer than two dimensions, or the two axes are the same axis ("axis1 and axis2 cannot be the same"); a read-only out ("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

a is 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

a NDArray

Input array.

axes int[]

NumPy's axes: a permutation of [0, 1, ..., a.ndim - 1] (negative axes count from the end), or null (NumPy's None, 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.chararray operand 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ValueError

axes does not have one entry per dimension (axes don't match array), or repeats an axis (repeated axis in transpose).

AxisError

An entry of axes is 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

y NDArray

Input array to integrate (at least one dimensional).

x NDArray

The sample points corresponding to the y values. When null (the default) the samples are assumed evenly spaced dx apart. A 1-D x supplies the spacing along axis (broadcast across the other axes); an N-D x is differenced along its own axis (counted against x.ndim, as NumPy's diff(x, axis=axis) does) and broadcast against y. Integration follows x's order — the points are NOT sorted, so a decreasing x integrates in reverse (negative area).

dx double

The spacing between sample points when x is null. Default 1. Ignored when x is supplied.

axis int

The 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 use y.ndim, the N-D x's difference uses x.ndim, and the final sum uses the rank of the broadcast product (which an N-D x with more dimensions than y raises).

Returns

NDArray

Definite integral approximated along axis. If y is 1-D (and no higher-rank x broadcasts it) the result is a 0-D array (a scalar); otherwise it is the broadcast product d * (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 of y and x, a single interval included: its final sum runs over a length-1 axis, which starts from NumPy's +0.0 identity, so a -0.0 area comes back +0.0 (np_sum_identity_tests.Trapezoid_OneInterval_NegativeZeroArea_IsPositiveZero).

Remarks

Exceptions

ArgumentNullException

y is null.

IndexError

axis is outside [-y.ndim, y.ndim-1], which every axis of a 0-D y is: NumPy's "list assignment index out of range", verbatim. NumPy's trapezoid never checks the axis; Python's assignment into its list of length y.ndim raises. An error in x (the two below) is reported first, as in NumPy, which resolves the spacing before it slices y.

ArgumentOutOfRangeException

An N-D x has no axis axis: diff(NDArray, int, int, object, object)'s "axis N is out of bounds for array of dimension M" (NumPy's AxisError from diff(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's operands could not be broadcast together with shapes … from the d * (…) multiply, verbatim.

TypeError

A text y or x (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 text x, the multiply of the spacing and the concatenated y[1:] + y[:-1] (for a fixed-width y and an integer spacing, the string multiply's "The 'out' kwarg is necessary" error), or the division by 2.0 of 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

N int

Number of rows in the array.

M int?

Number of columns in the array. By default, M is taken equal to N.

k int

The sub-diagonal at and below which the array is filled. k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above.

dtype DType

Data 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 the k-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

m NDArray

Input array. For arrays with ndim > 2, tril applies to the final two axes.

k int

Diagonal above which to zero elements. k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.

Returns

NDArray

Lower triangle of m, of the same dtype. Always a fresh, writeable, C-contiguous array (2-D for a 1-D m, whose row is broadcast down a square matrix).

Remarks

Exceptions

ArgumentNullException

m is null.

TypeError

m is 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

n int

The row dimension of the arrays for which the returned indices will be valid; a negative count is an empty axis.

k int

Diagonal offset. k = 0 (default) is the main diagonal.

m int?

The column dimension. By default m is taken equal to n.

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

arr NDArray

The 2-D array whose shape supplies the dimensions.

k int

Diagonal offset.

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

arr is null.

ArgumentException

input array must be 2-d (NumPy ValueError, verbatim).

OverflowException

A dimension of arr exceeds 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

filt NDArray

Input array.

trim string

A 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".

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

Returns

NDArray

A view of filt with leading/trailing all-zero hyperplanes removed. The number of dimensions and the input dtype are preserved. A numpy.char.chararray or numpy.matrix operand 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

filt is null.

ValueError

trim contains unexpected characters, an axis is repeated (repeated axis in axis argument), or a numpy.matrix operand'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

filt NDArray

Input array.

trim string

A 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".

axis int[]

The axes as NumPy's tuple, or null for None.

Returns

NDArray

A view of filt with leading/trailing all-zero hyperplanes removed. The number of dimensions and the input dtype are preserved. A numpy.char.chararray or numpy.matrix operand 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

filt is null.

ValueError

trim contains unexpected characters, an axis is repeated (repeated axis in axis argument), or a numpy.matrix operand'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

filt NDArray

Input array.

trim string

A 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".

axis NDAxis?

NumPy's axis: null (None, the default) crops filt to 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 sides trim selects. The empty tuple leaves the input unmodified.

Returns

NDArray

A view of filt with leading/trailing all-zero hyperplanes removed. The number of dimensions and the input dtype are preserved. A numpy.char.chararray or numpy.matrix operand 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

filt is null.

ValueError

trim contains unexpected characters, an axis is repeated (repeated axis in axis argument), or a numpy.matrix operand'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

m NDArray

Input array. For arrays with ndim > 2, triu applies to the final two axes.

k int

Diagonal below which to zero elements. k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.

Returns

NDArray

Upper triangle of m, of the same dtype. Always a fresh, writeable, C-contiguous array (2-D for a 1-D m, whose row is broadcast down a square matrix).

Remarks

Exceptions

ArgumentNullException

m is null.

TypeError

m is 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

n int

The size of the arrays for which the returned indices will be valid; a negative count is an empty axis.

k int

Diagonal offset. k = 0 (default) is the main diagonal.

m int?

The column dimension. By default m is taken equal to n.

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

arr NDArray

The 2-D array whose shape supplies the dimensions.

k int

Diagonal offset.

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

arr is null.

ArgumentException

input array must be 2-d (NumPy ValueError, verbatim).

OverflowException

A dimension of arr exceeds 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

x1 NDArray
x2 NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

Remarks

Exceptions

ValueError

A numpy.matrix operand 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

x NDArray

Input array.

out NDArray
where NDArray
dtype DType

The 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.matrix operand 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

char string

The 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

char is not one of the 22 recognised codes — this covers an unknown code, an empty or multi-character string, a differently-cased code, and a null argument. The message is the Python repr of the argument ('x', '', None), matching the raw dict KeyError 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

ar1 NDArray

Input array (flattened if not already 1-D).

ar2 NDArray

Input array (flattened if not already 1-D).

Returns

NDArray

Unique, sorted union of the input arrays.

Remarks

Exceptions

UnicodeDecodeError

A U union over S text holding a non-ASCII byte (NumPy's concatenation decodes it first).

DTypePromotionError

A StringDType operand beside a class the concatenation finds no common DType with (a number, bool, S bytes): NumPy's verbatim promotion text.

ValueError

A NEP 55 StringDType array whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy's Cannot compare null that is not a nan-like value.

ArgumentNullException

ar1 is 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

ar NDArray

Input array. Unless axis is given, it is flattened first.

return_index bool

If True, also return the first-occurrence indices of ar (along axis if given) that produce the unique values.

return_inverse bool

If True, also return the indices of the unique array that reconstruct ar.

return_counts bool

If True, also return the number of times each unique value appears.

axis int?

The axis to operate on. If null (default), the array is flattened first.

equal_nan bool

If True (default), all NaN values collapse to a single output value; if False, each NaN is a distinct value.

sorted bool

Accepted for NumPy 2.3 parity; NumSharp always returns sorted output (NumPy's sorted=False hash-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 values and the requested outputs. A numpy.char.chararray operand gives a chararray VIEW of the unique values (NumPy's _array_converter.wrap); the index arrays stay plain.

Remarks

Exceptions

AxisError

axis is out of range.

TypeError

A NEP 55 StringDType array with an axis over two or more dimensions: NumPy's structured path refuses StringDType fields (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 StringDType array whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry (the sorted path: sorted or a return flag; NumPy's values-only sorted=False hash pass compares nothing): NumPy's Cannot compare null that is not a nan-like value.

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

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

x NDArray

Input array. Flattened if it is not already 1-D.

Returns

np.UniqueAllResult

A np.UniqueAllResult: (values, indices, inverse_indices, counts). A numpy.char.chararray operand gives a chararray VIEW of the unique values (NumPy's _array_converter.wrap); the index arrays stay plain.

Remarks

Exceptions

ValueError

A NEP 55 StringDType array whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy's Cannot compare null that is not a nan-like value.

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

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

x NDArray

Input array. Flattened if it is not already 1-D.

Returns

np.UniqueCountsResult

A np.UniqueCountsResult: (values, counts). A numpy.char.chararray operand gives a chararray VIEW of the unique values (NumPy's _array_converter.wrap); the index arrays stay plain.

Remarks

Exceptions

ValueError

A NEP 55 StringDType array whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy's Cannot compare null that is not a nan-like value.

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

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

x NDArray

Input array. Flattened if it is not already 1-D.

Returns

np.UniqueInverseResult

A np.UniqueInverseResult: (values, inverse_indices). inverse_indices has the same shape as x, so np.take(values, inverse_indices) reconstructs the input. A numpy.char.chararray operand gives a chararray VIEW of the unique values (NumPy's _array_converter.wrap); the index arrays stay plain.

Remarks

Exceptions

ValueError

A NEP 55 StringDType array whose sort compares a None-like NA (an NA object that is neither a string nor NaN-like) with another entry: NumPy's Cannot compare null that is not a nan-like value.

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

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

x NDArray

Input array. Flattened if it is not already 1-D.

Returns

NDArray

The unique elements of x (dtype preserved). A numpy.char.chararray operand gives a chararray VIEW of a text result (NumPy's array_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 StringDType cell (NumPy's MemoryError text). A StringDType array otherwise computes without raising: NumPy's values-only sorted=False pass 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

a NDArray

Input array. Must be uint8 (any other dtype raises); read in logical order for any memory layout.

axis int?

Axis to unpack along. null (NumPy None) unpacks the C-order flattened array and returns a 1-D result.

count long?

Number of output elements along axis — undoes packing a non-multiple-of-8 size. null unpacks 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).

bitorder string

"big" (default) or "little". Matched to NumPy's unpack rule: only the FIRST character is inspected ('l' ⇒ little, 'b' ⇒ big); null is "big".

Returns

NDArray

A uint8 array of 0/1 values — same ndim as a (except axis=null ⇒ 1-D), F-contiguous iff a is.

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

a is null.

ValueError

bitorder does not begin with 'l' or 'b', or -count exceeds the available bits.

TypeError

a is not uint8.

AxisError

axis is out of bounds for a's rank.

ValueError

A numpy.matrix operand 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

indices NDArray

An 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.

shape Shape

The dimensions to unravel into: NumPy's idiom np.unravel_index(np.argmax(a), a.shape) passes a.shape (a long[]) or a.Shape as it is, and an int[], 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).

order char

'C' (row-major, the default) or 'F' (column-major), in either case.

Returns

NDArray<long>[]

One int64 array per dimension of shape, each of indices' shape — NumPy's ret_arr[..., j]: the COLUMNS of one interleaved buffer of shape indices.shape + (len(shape),), so every array is a strided VIEW (OWNDATA false, element stride len(shape) along the fastest axis) and they share that buffer. The buffer is laid out along indices' 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-d indices gives NumPy's scalars instead — fresh read-only 0-d arrays that own their value. An empty shape with 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

indices is null.

ValueError

In NumPy's order: order is 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 empty shape, an index array of rank 1 or more (multiple indices are not supported for 0d arrays, checked after the indices).

TypeError

indices is 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

indices long

The flat index (NumPy's keyword name, indices, which also takes an array: an array binds unravel_index(NDArray, Shape, char)).

shape Shape

The dimensions to unravel into (a.shape, a.Shape, an int[], a tuple); an empty shape (NumPy's ()) accepts the index 0 and returns no coordinate.

order char

'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

x NDArray

The array to be unstacked.

axis int

Axis along which the array will be split. Default: 0.

Returns

NDArray[]

The unstacked arrays — x.shape[axis] VIEWS into x (shared memory, matching NumPy), each with shape equal to x.shape with the axis entry removed. An empty x gives empty views too. A numpy.char.chararray operand 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 Python str / bytes with 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

x is null.

ValueError

x is 0-d ("Input array must be at least 1-d.").

AxisError

axis is out of range: moveaxis' "source: axis … is out of bounds for array of dimension …".

ValueError

A numpy.matrix operand 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

p NDArray

Input array (at least one dimensional; a 0-D input is rejected exactly as NumPy's inner diff(NDArray, int, int, object, object) rejects it).

discont double?

Maximum discontinuity between values. null (the default) means period/2. Values below period/2 have no effect: taking the complement of a jump smaller than period/2 would only enlarge it. A positional second argument is this one, as in NumPy: np.unwrap(a, 4) is discont=4.

axis int

Axis along which to unwrap; default is the last axis. Negative axes count from the end.

period NDArray

Size of the range over which the input wraps; null is NumPy's default 2*pi. Its kind picks NumPy's path: a C# integer (NumPy's Python int) keeps an integer input integral (the interval half-width is period // 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 is result_type(diff(p), period) (an int8 input with np.int64(4) is int64, with np.float32(4) float32). NumPy's period is keyword-only: write period:.

Returns

NDArray

A fresh, writeable, C-contiguous array of the unwrapped signal, p's shape, the dtype described for period. A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray, 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

p is null.

ValueError

p is 0-D (propagated from diff(NDArray, int, int, object, object)).

AxisError

axis is out of bounds for p's rank.

TypeError

p or period is complex (NumPy's mod has no complex loop), or period is 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's Python integer N out of bounds for <dtype>), raised for empty inputs too.

NotSupportedException

A period of several elements (NumPy broadcasts it into the elementwise steps), or a C# bool period over a bool p.

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

x NDArray

1-D input array.

N int?

Number of columns. If null, a square matrix is returned (N = len(x)).

increasing bool

If true the powers increase left to right (x^0 ... x^(N-1)); if false they are reversed (first column x^(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

x is not one-dimensional, or N is negative (the allocation's negative dimensions are not allowed).

TypeError

A text x with two or more columns: the powers come from multiply.accumulate, which has no string loop.

DTypePromotionError

A 1-D StringDType x: 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. ...), whatever N.

ArgumentNullException

x is 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

a NDArray

The values whose variance is desired.

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The loop of both sums. null is NumPy's default: float64 for bool and integer input, the input's own dtype otherwise; an integer dtype truncates the mean, as in NumPy.

out NDArray

The 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: and keepdims: by name.

ddof int

Delta degrees of freedom: the divisor is max(N - ddof, 0), so ddof >= N gives +inf (NaN when every deviation is 0), never a negative variance.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask broadcast against a: each output takes its selected elements only (its own count, mean and divisor). The C# true literal is NumPy's default. null is no mask.

mean NDArray

The mean to subtract instead of computing it: an array that broadcasts against a (the shape np.mean(a, axis, keepdims: true) has), or a C# number standing for a Python scalar. Footgun: it is used as given, so the deviations take a - 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. null computes it.

correction int?

The Array API's name of ddof: with it given, ddof must be 0, and the variance divides by max(N - correction, 0). null is none.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

Exceptions

ArgumentNullException

a is null.

ValueError

A nonzero ddof together with correction (ddof and correction can't be provided simultaneously., raised first); a read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is out of bounds.

ArgumentException

where is not a bool array (NumPy's TypeError text).

IncorrectShapeException

out, where or mean does not broadcast against a.

TypeError

A bool input with dtype: bool, or a bool mean of a bool input (NumPy's boolean-subtract refusal); a C# scalar passed as out; NumPy's text refusals; a numpy.matrix operand with keepdims, where or mean (matrix.var() got an unexpected keyword argument 'keepdims').

AttributeError

A numpy.matrix operand 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

a NDArray

The values whose variance is desired.

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The loop of both sums. null is NumPy's default: float64 for bool and integer input, the input's own dtype otherwise; an integer dtype truncates the mean, as in NumPy.

out NDArray

The 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: and keepdims: by name.

ddof int

Delta degrees of freedom: the divisor is max(N - ddof, 0), so ddof >= N gives +inf (NaN when every deviation is 0), never a negative variance.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask broadcast against a: each output takes its selected elements only (its own count, mean and divisor). The C# true literal is NumPy's default. null is no mask.

mean NDArray

The mean to subtract instead of computing it: an array that broadcasts against a (the shape np.mean(a, axis, keepdims: true) has), or a C# number standing for a Python scalar. Footgun: it is used as given, so the deviations take a - 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. null computes it.

correction int?

The Array API's name of ddof: with it given, ddof must be 0, and the variance divides by max(N - correction, 0). null is none.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

Exceptions

ArgumentNullException

a is null.

ValueError

A nonzero ddof together with correction (ddof and correction can't be provided simultaneously., raised first); a read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is out of bounds.

ArgumentException

where is not a bool array (NumPy's TypeError text).

IncorrectShapeException

out, where or mean does not broadcast against a.

TypeError

A bool input with dtype: bool, or a bool mean of a bool input (NumPy's boolean-subtract refusal); a C# scalar passed as out; NumPy's text refusals; a numpy.matrix operand with keepdims, where or mean (matrix.var() got an unexpected keyword argument 'keepdims').

AttributeError

A numpy.matrix operand 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

a NDArray

The values whose variance is desired.

axis NDAxis?

The axis to compute along (negative counts from the end); null uses every element. A 0-d array takes no axis unless where is 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).

dtype DType

The loop of both sums. null is NumPy's default: float64 for bool and integer input, the input's own dtype otherwise; an integer dtype truncates the mean, as in NumPy.

out NDArray

The 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: and keepdims: by name.

ddof int

Delta degrees of freedom: the divisor is max(N - ddof, 0), so ddof >= N gives +inf (NaN when every deviation is 0), never a negative variance.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask broadcast against a: each output takes its selected elements only (its own count, mean and divisor). The C# true literal is NumPy's default. null is no mask.

mean NDArray

The mean to subtract instead of computing it: an array that broadcasts against a (the shape np.mean(a, axis, keepdims: true) has), or a C# number standing for a Python scalar. Footgun: it is used as given, so the deviations take a - 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. null computes it.

correction int?

The Array API's name of ddof: with it given, ddof must be 0, and the variance divides by max(N - correction, 0). null is none.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

Exceptions

ArgumentNullException

a is null.

ValueError

A nonzero ddof together with correction (ddof and correction can't be provided simultaneously., raised first); a read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

AxisError

axis is out of bounds.

ArgumentException

where is not a bool array (NumPy's TypeError text).

IncorrectShapeException

out, where or mean does not broadcast against a.

TypeError

A bool input with dtype: bool, or a bool mean of a bool input (NumPy's boolean-subtract refusal); a C# scalar passed as out; NumPy's text refusals; a numpy.matrix operand with keepdims, where or mean (matrix.var() got an unexpected keyword argument 'keepdims').

AttributeError

A numpy.matrix operand 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

a NDArray

First argument. Flattened; conjugated when complex.

b NDArray

Second argument. Flattened.

Returns

NDArray

A 0-d result, always — vdot never performs a matrix product. A numpy.char.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.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

x1 NDArray

First operand. Conjugated when complex.

x2 NDArray

Second operand.

out NDArray

Where to deposit the answer. Returned as-is when given.

axes int[][]

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 with axis.

axis int?

The shared core axis, in place of the default last one. Applied to both operands — the special case of axes that this signature admits because both core dimensions are the SAME one.

keepdims bool

Leave the contracted axis in the result with length 1.

dtype DType

Selects the LOOP: computation runs at this dtype, not merely the result.

casting string

NumPy's casting=: the rule each input's cast to the loop, and the answer's cast into out, is checked under - no, equiv, safe, same_kind (the default) or unsafe.

order char

NumPy'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 with out.

Returns

NDArray

The vector dot products (the operands' loop axes broadcast together), or out itself 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.matrix operand 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; an axes list of the wrong length; loop axes that do not broadcast together, or a read-only out or one the answer does not broadcast into (NumPy's gufunc iterator texts).

TypeError

axis with axes; a dtype with details beyond its class; text operands or a text dtype (no vecdot loop).

AxisError

An axes entry of the wrong length, or an axis out of range.

TypeError

An input cannot be cast to the loop, or the answer into out, under casting (NumPy's UFuncTypeError text: Cannot cast ufunc 'vecdot' input 0 from dtype('int32') to dtype('float64') with casting rule 'no').

ValueError

A casting or order name NumPy refuses (casting first).

NullReferenceException

x1 or x2 is 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

x1 NDArray

Vector operand, at least 1-D. Conjugated when complex.

x2 NDArray

Matrix operand, at least 2-D. Leading axes broadcast.

out NDArray

Where to deposit the answer. Returned as-is when given.

axes int[][]

Which axes carry the core dimensions, per operand: {(n), (n,m), (m)}. All THREE entries are required — the output has a core axis.

axis int?

Present for signature parity only. NumPy raises TypeError for any value — this signature's core dimensions are two DISTINCT ones; use axes.

keepdims bool

Present for signature parity only. NumPy raises TypeError when true.

dtype DType

Selects the LOOP: computation runs at this dtype, not merely the result.

casting string

NumPy's casting=: the rule each input's cast to the loop, and the answer's cast into out, is checked under - no, equiv, safe, same_kind (the default) or unsafe.

order char

NumPy'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 with out.

Returns

NDArray

The vector-matrix products (the operands' loop axes broadcast together), or out itself 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.matrix operand 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; an axes list without three entries; loop axes that do not broadcast together, or a read-only out or one the answer does not broadcast into (NumPy's gufunc iterator texts).

TypeError

axis with axes, or either given; a dtype with details beyond its class; text operands or a text dtype; keepdims.

AxisError

An axes entry of the wrong length, or an axis out of range.

TypeError

An input cannot be cast to the loop, or the answer into out, under casting (NumPy's UFuncTypeError text: Cannot cast ufunc 'vecmat' input 0 from dtype('int32') to dtype('float64') with casting rule 'no').

ValueError

A casting or order name NumPy refuses (casting first).

IncorrectShapeException

Loop axes that do not broadcast.

NullReferenceException

x1 or x2 is 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

pyfunc Delegate

The per-element function (any supported arity; may return a tuple for multi-output).

otypes DType[]

Optional per-output dtype overrides (length must equal the output count).

Returns

Vectorized

A Vectorized in element-wise mode.

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ArgumentException

A parameter is NDArray (needs a signature) or a return component is not a supported dtype.

ValueError

otypes length 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

pyfunc Delegate

Applied to core sub-arrays; must take/return NDArray (a tuple / array for multi-output).

signature string

The gufunc signature; its input arity must equal the delegate's parameter count.

otypes DType[]

Optional per-output dtype overrides.

Returns

Vectorized

A Vectorized in signature mode.

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ValueError

signature is 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

pyfunc Func<NDArray, NDArray, NDArray, NDArray>

Applied to each triple of core sub-arrays.

signature string

The gufunc signature (input side must have exactly three arguments).

otypes DType[]

Optional per-output dtype overrides.

Returns

Vectorized

A Vectorized in signature mode.

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ValueError

signature is 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

pyfunc Func<NDArray, NDArray, NDArray>

Applied to each pair of core sub-arrays.

signature string

The gufunc signature (input side must have exactly two arguments).

otypes DType[]

Optional per-output dtype overrides.

Returns

Vectorized

A Vectorized in signature mode.

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ValueError

signature is 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

pyfunc Func<NDArray, NDArray>

Applied to each core sub-array; receives an NDArray of the input core shape.

signature string

The gufunc signature (input side must have exactly one argument to match the arity).

otypes DType[]

Optional per-output dtype overrides; when absent the first result's dtype is used.

Returns

Vectorized

A Vectorized in signature mode.

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ValueError

signature is 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

pyfunc Func<T1, TR>

The per-element function.

otypes DType[]

Optional single output-dtype override (a trailing cast); usually unnecessary since TR already fixes the dtype.

Returns

Func<NDArray, NDArray>

A delegate applying pyfunc element-wise across a broadcast input.

Type Parameters

T1

The element type the function consumes; inputs are cast to it (NEP50 at the edge).

TR

The element type the function returns; the result array's dtype (unless otypes overrides).

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ArgumentException

TR is 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

pyfunc Func<T1, (TR1, TR2)>

The per-element function returning a 2-tuple.

otypes DType[]

Optional per-output dtype overrides (length 2 if given).

Returns

Vectorized

A Vectorized producing two arrays.

Type Parameters

T1

Argument element type.

TR1

First output element type.

TR2

Second output element type.

Exceptions

ArgumentNullException

pyfunc is null.

ArgumentException

A return component is not a supported dtype.

ValueError

otypes length 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

pyfunc Func<T1, T2, TR>

The per-element function.

otypes DType[]

Optional single output-dtype override.

Returns

Func<NDArray, NDArray, NDArray>

A delegate applying pyfunc element-wise across the broadcast of its two inputs.

Type Parameters

T1

First argument's element type.

T2

Second argument's element type.

TR

Return element type (the result dtype unless otypes overrides).

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ArgumentException

TR is 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

pyfunc Func<T1, (TR1, TR2, TR3)>

The per-element function returning a 3-tuple.

otypes DType[]

Optional per-output dtype overrides (length 3 if given).

Returns

Vectorized

A Vectorized producing three arrays.

Type Parameters

T1

Argument element type.

TR1

First output element type.

TR2

Second output element type.

TR3

Third output element type.

Exceptions

ArgumentNullException

pyfunc is null.

ArgumentException

A return component is not a supported dtype.

ValueError

otypes length 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

pyfunc Func<T1, T2, (TR1, TR2)>

The per-element function returning a 2-tuple.

otypes DType[]

Optional per-output dtype overrides (length 2 if given).

Returns

Vectorized

A Vectorized producing two arrays.

Type Parameters

T1

First argument element type.

T2

Second argument element type.

TR1

First output element type.

TR2

Second output element type.

Exceptions

ArgumentNullException

pyfunc is null.

ArgumentException

A return component is not a supported dtype.

ValueError

otypes length 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

pyfunc Func<T1, T2, T3, TR>

The per-element function.

otypes DType[]

Optional single output-dtype override.

Returns

Func<NDArray, NDArray, NDArray, NDArray>

A delegate applying pyfunc element-wise across the broadcast of its three inputs.

Type Parameters

T1

First argument's element type.

T2

Second argument's element type.

T3

Third argument's element type.

TR

Return element type.

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ArgumentException

TR is 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

pyfunc Func<T1, T2, T3, T4, TR>

The per-element function.

otypes DType[]

Optional single output-dtype override.

Returns

Func<NDArray, NDArray, NDArray, NDArray, NDArray>

A delegate applying pyfunc element-wise across the broadcast of its four inputs.

Type Parameters

T1

First argument's element type.

T2

Second argument's element type.

T3

Third argument's element type.

T4

Fourth argument's element type.

TR

Return element type.

Remarks

Exceptions

ArgumentNullException

pyfunc is null.

ArgumentException

TR is 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

ary NDArray

Array to be divided into sub-arrays.

indices_or_sections int

If 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.chararray operand 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentException

ary has 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

ary is 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

ary NDArray

Array to be divided into sub-arrays.

indices int[]

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.chararray operand 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.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentException

ary has fewer than two dimensions ("vsplit only works on arrays of 2 or more dimensions"; NumPy raises the text as a ValueError).

ArgumentNullException

indices is null (checked after the rank).

NullReferenceException

ary is 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

tup NDArray[]

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.chararray operand gives a plain array: NumPy converts it with asarray (or ends with np.concatenate), which drops the class.

Remarks

Exceptions

ValueError

A numpy.matrix operand whose result cannot be a matrix: more than two axes longer than 1 (shape too large to be a matrix.).

ArgumentNullException

tup is null.

ValueError

tup is 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

tup NDArray[]

The arrays (NumPy's sequence): the same shape along all but the first axis; 1-D arrays the same length.

dtype DType

The result dtype handed to np.concatenate, or null for the arrays' promoted dtype.

casting string

The 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.matrix operand 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

tup is null.

ValueError

tup is empty ("need at least one array to concatenate"); a numpy.matrix result of more than two long axes.

InvalidCastException

An array that does not cast to dtype under casting (np.concatenate's refusal with NumPy's text; NumPy's type is TypeError, pinned in OpenBugs.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

tup NDListArray[]

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

tup or 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

condition NDArray

Input array. Non-zero entries yield their indices.

Returns

NDArray<long>[]

Tuple of arrays with indices where condition is non-zero, one per dimension.

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

condition NDArray

Where True, yield x, otherwise yield y.

x NDArray

Values from which to choose where condition is True.

y NDArray

Values from which to choose where condition is False.

Returns

NDArray

An array with elements from x where condition is True, and elements from y elsewhere.

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

condition NDArray
x NDArray
y object

Returns

NDArray

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

condition NDArray
x object
y NDArray

Returns

NDArray

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

condition NDArray
x object
y object

Returns

NDArray

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

shape Shape

The dimensions: an int (2), a tuple ((2, 3)), an int[] / long[] or a Shape (all convert implicitly). Only the dimensions are read: the layout comes from order, as NumPy's shape is a tuple of ints — a Shape taken from a transposed view gives a C-ordered array unless order says 'F'.

dtype DType

The 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.

order char

'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.

device string

Null 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: order is not one of C, F, A, K (order must be one of 'C', 'F', 'A', or 'K' (got 'X')); device is not "cpu" (Device not understood. Only "cpu" is allowed, but received: gpu); order is 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

dtype names 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

a NDArray

The shape and data-type of a define these same attributes of the returned array.

dtype DType

Overrides the data type of the result, or null for a's.

order char

Memory layout: 'C', 'F', 'A' (F when a is F-contiguous and not C-contiguous, else C) or 'K' (the default: a's axis order, kept also for a shape of the same rank), in either case.

shape Shape?

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.

device string

Target device. Only "cpu" and null are 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.chararray operand 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

order is 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; device is neither null nor "cpu" (NumPy's Device not understood. Only "cpu" is allowed, but received: ...); a negative dimension in shape (negative dimensions are not allowed); a numpy.matrix operand whose result cannot be a matrix (shape too large to be a matrix.).

ValueError

A numpy.char.chararray operand 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

a is null (its layout is read after the order and device checks).