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

public static readonly DType bool8

Field Value

DType

bool_

public static readonly DType bool_

Field Value

DType

byte

public static readonly DType @byte

Field Value

DType

cdouble

public static readonly DType cdouble

Field Value

DType

char

public static readonly DType @char

Field Value

DType

clongdouble

public static readonly DType clongdouble

Field Value

DType

complex128

public static readonly DType complex128

Field Value

DType

complex_

public static readonly DType complex_

Field Value

DType

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_

public static readonly DType float_

Field Value

DType

half

public static readonly DType half

Field Value

DType

int0

public static readonly DType int0

Field Value

DType

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

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

longlong

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

ubyte

public static readonly DType ubyte

Field Value

DType

uint

public static readonly DType @uint

Field Value

DType

uint0

public static readonly DType uint0

Field Value

DType

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

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

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

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

c_

Builds arrays by stacking columns — see np.CClass.

public static np.CClass c_ { get; }

Property Value

np.CClass

Remarks

chars

public static DType chars { get; }

Property Value

DType

complex64

NumSharp does not support complex64 (two 32-bit floats). The only complex type available is complex128 (two 64-bit floats, backed by Complex). Accessing this property throws NotSupportedException; use complex128 or complex_ instead.

public static DType complex64 { get; }

Property Value

DType

csingle

NumPy alias for complex64. Same as complex64 — throws because NumSharp does not support complex64.

public static DType csingle { get; }

Property Value

DType

e

public static double e { get; }

Property Value

double

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

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

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

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

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

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

Methods

abs(NDArray)

Calculate the absolute value element-wise.
np.abs is a shorthand for this function.

public static NDArray abs(NDArray a)

Parameters

a NDArray

Input value.

Returns

NDArray

An ndarray containing the absolute value of each element in x.

Remarks

abs(NDArray, NDArray, NDArray, DType)

Calculate the absolute value element-wise (alias of absolute(NDArray, NDArray, NDArray, NPTypeCode?)). 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
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

Remarks

absolute(NDArray)

Calculate the absolute value element-wise.
np.abs is a shorthand for this function.

public static NDArray absolute(NDArray a)

Parameters

a NDArray

Input value.

Returns

NDArray

An ndarray containing the absolute value of each element in x.

Remarks

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

Remarks

acosh(NDArray, NDArray, NDArray, DType)

Inverse hyperbolic cosine, element-wise (Array-API alias of arccosh(NDArray, NDArray, NDArray, NPTypeCode?), 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

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

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

Remarks

all(NDArray, bool)

Test whether all array elements evaluate to True, optionally keeping reduced dimensions. Reduces over all axes (axis = None semantics).

public static NDArray<bool> all(NDArray nd, bool keepdims)

Parameters

nd NDArray

Input array.

keepdims bool

If True, the result is broadcast-compatible with the input (every dimension becomes size 1). Otherwise the result is a 0-d array.

Returns

NDArray<bool>

A new boolean ndarray.

Remarks

all(NDArray, int, bool)

Test whether all array elements along a given axis evaluate to True.

public static NDArray<bool> all(NDArray nd, int axis, bool keepdims = false)

Parameters

nd NDArray

Input array or object that can be converted to an array.

axis int

Axis along which a logical AND reduction is performed.

keepdims bool

If True, the reduced axes are left in the result as dimensions with size one.

Returns

NDArray<bool>

A new boolean ndarray is returned.

Remarks

all(NDArray, int[], NDArray, bool, NDArray)

Tuple-axis variant of the full np.all overload (with out and where).

public static NDArray all(NDArray a, int[] axis, NDArray @out, bool keepdims = false, NDArray where = null)

Parameters

a NDArray

Input array.

axis int[]

Axes along which to reduce.

out NDArray

Destination array. Its dtype is preserved.

keepdims bool

If True, reduced axes are left as size-one dimensions.

where NDArray

Boolean mask, broadcastable against a.

Returns

NDArray

The reduced array, or out when supplied.

Remarks

all(NDArray, int[], bool)

Test whether all array elements along the given axes evaluate to True. Multiple axes can be specified by passing an array of ints.

public static NDArray<bool> all(NDArray nd, int[] axis, bool keepdims = false)

Parameters

nd NDArray

Input array.

axis int[]

Tuple of axes along which a logical AND reduction is performed. An empty array returns the input cast to bool (no reduction).

keepdims bool

If True, the reduced axes are left in the result as dimensions with size one.

Returns

NDArray<bool>

A new boolean ndarray is returned.

Remarks

all(NDArray, int?, NDArray, bool, NDArray)

Test whether all array elements along the given axis evaluate to True, with optional out= destination and where= mask. Matches NumPy 2.x: all(a, axis=None, out=None, keepdims=False, *, where=True).

public static NDArray all(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

a NDArray

Input array.

axis int?

Axis along which to reduce. Pass null for axis=None (all axes).

out NDArray

Destination array. Its dtype is preserved (e.g. an int out stores 0/1 instead of bool). Pass null to allocate a fresh boolean array.

keepdims bool

If True, the reduced axes are left as dimensions with size one.

where NDArray

Boolean (or numeric-treated-as-bool) mask, broadcastable against a. Elements where where=False are excluded from the reduction and contribute the identity value (True for all). Pass null for no mask.

Returns

NDArray

The reduced array, or out when supplied.

Remarks

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?, bool, DType)

Return the maximum of an array or maximum along an axis.

public static NDArray amax(NDArray a, int? axis = null, bool keepdims = false, DType dtype = null)

Parameters

a NDArray
axis int?

Axis or axes along which to operate.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

amax<T>(NDArray)

Return the maximum of an array or maximum along an axis.

public static T amax<T>(NDArray a) where T : unmanaged

Parameters

a NDArray

Returns

T

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Type Parameters

T

the type expected as a return, cast is performed if necessary.

Remarks

amin(NDArray, int?, bool, DType)

Return the minimum of an array or minimum along an axis.

public static NDArray amin(NDArray a, int? axis = null, bool keepdims = false, DType dtype = null)

Parameters

a NDArray

Input data.

axis int?

Axis or axes along which to operate.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

amin<T>(NDArray)

Return the minimum of an array or minimum along an axis.

public static T amin<T>(NDArray a) where T : unmanaged

Parameters

a NDArray

Input data.

Returns

T

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Type Parameters

T

the type expected as a return, cast is performed if necessary.

Remarks

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, System.Nullable<NPTypeCode>) 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

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

Remarks

any(NDArray, bool)

Test whether any array element evaluates to True, optionally keeping reduced dimensions. Reduces over all axes (axis = None semantics).

public static NDArray<bool> any(NDArray nd, bool keepdims)

Parameters

nd NDArray

Input array.

keepdims bool

If True, the result has all dimensions as size 1 (broadcast-compatible with the input). Otherwise the result is a 0-d array.

Returns

NDArray<bool>

A new boolean ndarray.

Remarks

any(NDArray, int, bool)

Test whether any array element along a given axis evaluates to True.

public static NDArray<bool> any(NDArray nd, int axis, bool keepdims = false)

Parameters

nd NDArray

Input array.

axis int

Axis along which a logical OR reduction is performed.

keepdims bool

If True, the reduced axes are left in the result as dimensions with size one.

Returns

NDArray<bool>

A new boolean ndarray is returned.

Remarks

any(NDArray, int[], NDArray, bool, NDArray)

Tuple-axis variant of the full np.any overload (with out and where).

public static NDArray any(NDArray a, int[] axis, NDArray @out, bool keepdims = false, NDArray where = null)

Parameters

a NDArray

Input array.

axis int[]

Axes along which to reduce.

out NDArray

Destination array. Its dtype is preserved.

keepdims bool

If True, reduced axes are left as size-one dimensions.

where NDArray

Boolean mask, broadcastable against a.

Returns

NDArray

The reduced array, or out when supplied.

Remarks

any(NDArray, int[], bool)

Test whether any array element along the given axes evaluates to True. Multiple axes can be specified by passing an array of ints.

public static NDArray<bool> any(NDArray nd, int[] axis, bool keepdims = false)

Parameters

nd NDArray

Input array.

axis int[]

Tuple of axes along which a logical OR reduction is performed. An empty array returns the input cast to bool (no reduction).

keepdims bool

If True, the reduced axes are left in the result as dimensions with size one.

Returns

NDArray<bool>

A new boolean ndarray is returned.

Remarks

any(NDArray, int?, NDArray, bool, NDArray)

Test whether any array element along the given axis evaluates to True, with optional out= destination and where= mask. Matches NumPy 2.x: any(a, axis=None, out=None, keepdims=False, *, where=True).

public static NDArray any(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

a NDArray

Input array.

axis int?

Axis along which to reduce. Pass null for axis=None (all axes).

out NDArray

Destination array. Its dtype is preserved. Pass null to allocate fresh.

keepdims bool

If True, the reduced axes are left as size-one dimensions.

where NDArray

Boolean (or numeric-treated-as-bool) mask, broadcastable against a. Elements where where=False are excluded from the reduction and contribute the identity value (False for any). Pass null for no mask.

Returns

NDArray

The reduced array, or out when supplied.

Remarks

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.

values NDArray

Values to append. 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.

Remarks

append(NDArray, object, int?)

Scalar / generic-value overload that wraps the value via asanyarray(in object, DType, string) before delegating. Matches NumPy's np.append([1,2,3], 4) idiom — the scalar is auto-coerced to a 0-D ndarray (whose ravel is shape (1,)).

public static NDArray append(NDArray arr, object values, int? axis = null)

Parameters

arr NDArray
values object
axis int?

Returns

NDArray

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.

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

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

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.

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. The interval includes this value.

stop double

End of interval. The interval does not include this value.

step double

Spacing between values. 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, infers from inputs (int64 for integers, float64 for floats).

device string

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

Returns

NDArray

Array of evenly spaced values.

Remarks

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.

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.

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.

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

stop long

End of interval (exclusive).

step long

Spacing between values. Default is 1.

Returns

NDArray

Array of evenly spaced int64 values.

Remarks

NumPy 2.x returns int64 for integer arange.

arange(float)

Return evenly spaced values within a given interval.

public static NDArray arange(float stop)

Parameters

stop float

End of interval (exclusive).

Returns

NDArray

Array of evenly spaced float values.

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

stop float

End of interval (exclusive).

step float

Spacing between values. Default is 1.

Returns

NDArray

Array of evenly spaced float values.

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

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

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

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

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

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

Input array y-coordinates.

out NDArray
where NDArray
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

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

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

argmax(NDArray, int, bool)

Returns the indices of the maximum values along an axis.

public static NDArray argmax(NDArray a, int axis, bool keepdims = false)

Parameters

a NDArray

Input array.

axis int

By default, the index is into the flattened array, otherwise along the specified axis.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed (unless keepdims is True).

Remarks

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

argmin(NDArray, int, bool)

Returns the indices of the minimum values along an axis.

public static NDArray argmin(NDArray a, int axis, bool keepdims = false)

Parameters

a NDArray

Input array.

axis int

By default, the index is into the flattened array, otherwise along the specified axis.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed (unless keepdims is True).

Remarks

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

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

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

argsort(NDArray, int?)

Returns the indices that would sort nd along axis (default last; null flattens). Returns int64 indices. NumPy np.argsort.

public static NDArray argsort(NDArray nd, int? axis = -1)

Parameters

nd NDArray
axis int?

Returns

NDArray

argsort<T>(NDArray, int)

Returns the indices that would sort an array.

Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

public static NDArray argsort<T>(NDArray nd, int axis = -1) where T : unmanaged

Parameters

nd NDArray
axis int

Returns

NDArray

Type Parameters

T

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

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, DType)

Evenly round to the given number of decimals (alias of round_(NDArray, int, NDArray, DType); NumPy: np.around is np.round).

public static NDArray around(NDArray x, int decimals = 0, NDArray @out = null, DType dtype = null)

Parameters

x NDArray

Input array.

decimals int

Number of decimal places to round to (default 0). Half is rounded to even.

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

dtype DType

The DType the returned ndarray should be of (implicit from Type / NPTypeCode / NumPy dtype string).

Returns

NDArray

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.

Remarks

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

public static NDArray array(NDArray nd, bool copy = true)

Parameters

nd NDArray

Source array.

copy bool

When true (default) the source storage is cloned; when false the storage is shared (alias). For "copy only if needed" semantics use asarray(NDArray, Type, char, bool?, NDArray, string).

Returns

NDArray

Remarks

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)

Create a vector NDArray of dtype char.

public static NDArray array(string chars)

Parameters

chars string

Returns

NDArray

array(string[])

Create a vector ndarray of type <xref href="System.String" data-throw-if-not-resolved="false"></xref>.

Encode string array. format: [numOfRow lenOfRow1 lenOfRow2 contents] sample: [2 2 4 aacccc]

public static NDArray array(string[] strArray)

Parameters

strArray string[]

Returns

NDArray

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)

True if two arrays have the same shape and elements, False otherwise.

public static bool array_equal(NDArray a, NDArray b)

Parameters

a NDArray

Input array.

b NDArray

Input array.

Returns

bool

Returns True if the arrays are equal.

Remarks

array_repr(NDArray, int?, int?, bool?)

Return the string representation of an array (NumPy's np.array_repr).

public static string array_repr(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_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
indices_or_sections int
axis int

Returns

NDArray[]

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

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
indices int[]
axis int

Returns

NDArray[]

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
indices long[]
axis int

Returns

NDArray[]

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 NDArray from given data.

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

Parameters

data IEnumerable<T>

The enumeration of data to create NDArray from.

size int

Maximum number of items to read from data.

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

https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
size can be used to limit the amount of items to read form data. Reading stops on either size or data ends.

array<T>(IEnumerable<T>, long)

Creates a Vector NDArray from given data.

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

Parameters

data IEnumerable<T>

The enumeration of data to create NDArray from.

size long

Maximum number of items to read from data.

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

https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
size can be used to limit the amount of items to read form data. Reading stops on either size or data ends.

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

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.

[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. Shape is taken from the first item of each array/nested array.

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.

[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. Shape is taken from the first item of each array/nested array.

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.

[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. Shape is taken from the first item of each array/nested array.

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.

[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. Shape is taken from the first item of each array/nested array.

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

asanyarray(MemoryView, DType, char, string)

Convert a np.MemoryView (obtained from data) to an ndarray, passing ndarray subclasses through — the consumer round-trip of ndarray.data. Matches NumPy's np.asanyarray(a.data) (a zero-copy VIEW sharing memory, copying only if a dtype/layout change forces it). A dedicated overload is required because a np.MemoryView is not otherwise resolvable by the object converter above. Equivalent to np.asanyarray(buffer.obj, …).

public static NDArray asanyarray(np.MemoryView buffer, DType dtype = null, char order = 'K', string device = null)

Parameters

buffer np.MemoryView

A np.MemoryView over an array.

dtype DType

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

order char

'C', 'F', 'A' or 'K' (default).

device string

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

Returns

NDArray

Remarks

asanyarray(in object, DType, char, string)

Convert the input to an ndarray with a specified memory layout.

public static NDArray asanyarray(in object a, DType dtype, char order, string device = null)

Parameters

a object

Input data.

dtype DType

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

order char

'C', 'F', 'A' or 'K' (default — resolved against a).

device string

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

Returns

NDArray

Array interpretation of a in the requested layout.

Remarks

asanyarray(in object, DType, string)

Convert the input to an ndarray, but pass ndarray subclasses through.

public static NDArray asanyarray(in object a, DType dtype = null, string device = null)

Parameters

a object

Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.

dtype DType

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

device string

Returns

NDArray

Array interpretation of a. If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.

Remarks

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 = 'K', bool? copy = null, NDArray like = null, string device = null)

Parameters

a NDArray

Input ndarray.

dtype DType

Requested dtype. null keeps the input dtype.

order char

'C' (row-major), 'F' (column-major), 'A' (any contiguous), 'K' (keep — default). '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.

Remarks

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(buffer.obj, …).

public static NDArray asarray(np.MemoryView buffer, DType dtype = null, char order = 'K', bool? copy = null, NDArray like = null, string device = null)

Parameters

buffer np.MemoryView

A np.MemoryView over an array.

dtype DType

Requested dtype. null keeps the source dtype.

order char

'C', 'F', 'A', or 'K' (default).

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

Remarks

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, Type, char, bool?, NDArray, string).

public static NDArray asarray(np.MemoryView buffer, string dtype, char order = 'K', bool? copy = null, NDArray like = null, string device = null)

Parameters

buffer np.MemoryView
dtype string
order char
copy bool?
like NDArray
device string

Returns

NDArray

Remarks

asarray(string)

public static NDArray asarray(string data)

Parameters

data string

Returns

NDArray

asarray(string[], int)

public static NDArray asarray(string[] data, int ndim = 1)

Parameters

data string[]
ndim int

Returns

NDArray

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 = 'K')

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 — default, equivalent to NumPy's order=None).

Returns

NDArray

Array interpretation of a.

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

asarray<T>(T)

public static NDArray asarray<T>(T data) where T : struct

Parameters

data T

Returns

NDArray

Type Parameters

T

asarray<T>(T[], int)

public static NDArray asarray<T>(T[] data, int ndim = 1) where T : struct

Parameters

data T[]
ndim int

Returns

NDArray

Type Parameters

T

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.

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(buffer.obj, dtype).

public static NDArray ascontiguousarray(np.MemoryView buffer, DType dtype = null)

Parameters

buffer np.MemoryView

A np.MemoryView over an array.

dtype DType

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

Returns

NDArray

Remarks

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.

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(buffer.obj, dtype).

public static NDArray asfortranarray(np.MemoryView buffer, DType dtype = null)

Parameters

buffer np.MemoryView

A np.MemoryView over an array.

dtype DType

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

Returns

NDArray

Remarks

asinh(NDArray, NDArray, NDArray, DType)

Inverse hyperbolic sine, element-wise (Array-API alias of arcsinh(NDArray, NDArray, NDArray, NPTypeCode?), 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

asmatrix(NDArray, DType)

Interpret the input as a matrix — a 2-D array. Unlike a copy, asmatrix does not copy if the input is already an ndarray; it returns a 2-D view that shares memory.

public static NDArray asmatrix(NDArray data, DType dtype = null)

Parameters

data NDArray

Input array.

dtype DType

Data-type of the output. null keeps the input dtype.

Returns

NDArray

data interpreted as a 2-D array. A 0-D input becomes shape (1, 1), a 1-D input of length N becomes (1, N), and a 2-D input is returned unchanged.

Remarks

Port of NumPy 2.x numpy.asmatrixmatrix(data, copy=False). NumSharp has no dedicated matrix subclass (NumPy's is pending-deprecated), so the result is a plain 2-D NDArray — the special matrix operators (* as matmul, ** as matrix power, .H, .I) are NOT provided. The dimensional coercion matches NumPy's matrix.array_finalize exactly, including the >2-D behaviour: axes of length 1 are dropped and the result must then be 2-D, otherwise a ValueError ("shape too large to be a matrix.") is raised. The view is preserved for strided, transposed and reversed inputs (no copy). A dtype change casts (which copies), then coerces the copy. https://numpy.org/doc/stable/reference/generated/numpy.asmatrix.html

asmatrix(string, DType)

Interpret a matrix string as a 2-D array. Rows are separated by ';' and columns by commas and/or whitespace, e.g. "1 2; 3 4". Surrounding brackets are ignored. The dtype is inferred (integer when every element is an integer, otherwise double) unless dtype is given.

public static NDArray asmatrix(string data, DType dtype = null)

Parameters

data string

Matrix string such as "1 2; 3 4".

dtype DType

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

Returns

NDArray

Remarks

Exceptions

ValueError

If the rows are not all the same length.

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.

atanh(NDArray, NDArray, NDArray, DType)

Inverse hyperbolic tangent, element-wise (Array-API alias of arctanh(NDArray, NDArray, NDArray, NPTypeCode?), 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

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.

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.

Remarks

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

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.

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.

Remarks

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

atleast_3d(NDArray)

View inputs as arrays with at least three dimensions.

public static NDArray atleast_3d(NDArray arr)

Parameters

arr NDArray

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

Remarks

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

average(NDArray, int[], NDArray, bool)

Compute the weighted average along a tuple of axes. Equivalent to np.average(a, axis, weights, keepdims) in NumPy with a tuple axis.

public static NDArray average(NDArray a, int[] axis, NDArray weights = null, bool keepdims = false)

Parameters

a NDArray
axis int[]
weights NDArray
keepdims bool

Returns

NDArray

Remarks

average(NDArray, int?, NDArray, bool)

Compute the weighted average along the specified axis. Equivalent to sum(a * weights) / sum(weights). When weights is null this reduces to mean(NDArray) over the same axes.

public static NDArray average(NDArray a, int? axis = null, NDArray weights = null, bool keepdims = false)

Parameters

a NDArray
axis int?
weights NDArray
keepdims bool

Returns

NDArray

Remarks

average_returned(NDArray, int[], NDArray, bool)

public static (NDArray avg, NDArray sumOfWeights) average_returned(NDArray a, int[] axis, NDArray weights = null, bool keepdims = false)

Parameters

a NDArray
axis int[]
weights NDArray
keepdims bool

Returns

(NDArray Lhs, NDArray Rhs)

Remarks

average_returned(NDArray, int?, NDArray, bool)

Compute the weighted average and return a tuple (avg, sum_of_weights). Equivalent to numpy.average(..., returned=True). When weights is null, sum_of_weights is the number of elements per output cell (broadcast to the average's shape).

public static (NDArray avg, NDArray sumOfWeights) average_returned(NDArray a, int? axis = null, NDArray weights = null, bool keepdims = false)

Parameters

a NDArray
axis int?
weights NDArray
keepdims bool

Returns

(NDArray Lhs, NDArray Rhs)

Remarks

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

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

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

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

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

block(object)

Assemble an nd-array from nested lists of blocks. Blocks in the innermost lists are concatenated (see concatenate(NDArray[], int?, NDArray, NPTypeCode?, 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, Type).
  • 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], []].

bmat(NDArray)

Interpret a single array as a matrix — a 2-D 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 NDArray bmat(NDArray obj)

Parameters

obj NDArray

Input array.

Returns

NDArray

A fresh 2-D array 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, Type), which returns a view. The copy is taken first, then coerced to 2-D, so the result never aliases obj. https://numpy.org/doc/stable/reference/generated/numpy.bmat.html

bmat(NDArray[])

Build a 2-D array 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 NDArray bmat(NDArray[] obj)

Parameters

obj NDArray[]

The blocks, concatenated left-to-right (along the last axis).

Returns

NDArray

The assembled 2-D array.

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 2-D array from a nested sequence of blocks: [[A, B], [C, D]] assembles one matrix by joining the blocks in each inner list left-to-right and stacking the resulting rows top-to-bottom.

public static NDArray 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

NDArray

The assembled 2-D array.

Remarks

Port of NumPy 2.x numpy.bmatmatrix(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, NPTypeCode?, string) and the 2-D coercion from asmatrix(NDArray, Type). NumSharp has no dedicated matrix subclass (NumPy's is pending-deprecated), so the result is a plain 2-D NDArray — the special matrix operators (* as matmul, ** as matrix power, .H, .I) are NOT provided. 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 2-D array 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 NDArray 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

NDArray

The assembled 2-D array.

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, Type) 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 2-D array 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 NDArray 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

NDArray

The assembled 2-D array.

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, Type)'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
nd2 NDArray

Returns

np.Broadcast

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_arrays(NDArray, NDArray)

Broadcast two arrays against each other.

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)

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

broadcast_arrays(params NDArray[])

Broadcast any number of arrays against each other.

public static NDArray[] broadcast_arrays(params NDArray[] ndArrays)

Parameters

ndArrays NDArray[]

The arrays to broadcast.

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

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

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

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

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

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

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

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

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

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

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
to DType
casting NPY_CASTING

Returns

bool

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

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
to DType
casting string

Returns

bool

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.

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.

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(bool, NPTypeCode, string)

Returns True if the bool value can be cast to the data type according to the casting rule.

public static bool can_cast(bool value, NPTypeCode to, string casting = "safe")

Parameters

value bool
to NPTypeCode
casting string

Returns

bool

can_cast(byte, NPTypeCode, string)

Returns True if the byte value can be cast to the data type according to the casting rule.

public static bool can_cast(byte value, NPTypeCode to, string casting = "safe")

Parameters

value byte
to NPTypeCode
casting string

Returns

bool

can_cast(decimal, NPTypeCode, string)

Returns True if the decimal value can be cast to the data type according to the casting rule.

public static bool can_cast(decimal value, NPTypeCode to, string casting = "safe")

Parameters

value decimal
to NPTypeCode
casting string

Returns

bool

can_cast(double, NPTypeCode, string)

Returns True if the double value can be cast to the data type according to the casting rule.

public static bool can_cast(double value, NPTypeCode to, string casting = "safe")

Parameters

value double
to NPTypeCode
casting string

Returns

bool

can_cast(short, NPTypeCode, string)

Returns True if the short value can be cast to the data type according to the casting rule.

public static bool can_cast(short value, NPTypeCode to, string casting = "safe")

Parameters

value short
to NPTypeCode
casting string

Returns

bool

can_cast(int, NPTypeCode, string)

Returns True if the int value can be cast to the data type according to the casting rule.

public static bool can_cast(int value, NPTypeCode to, string casting = "safe")

Parameters

value int

Int value to check.

to NPTypeCode

Data type to cast to.

casting string

Controls what kind of data casting may occur.

Returns

bool

True if the value can be cast to the target type.

Remarks

NumSharp extension: NumPy 2.x refuses Python scalars here ("can_cast() does not support Python ints, floats, and complex because the result used to depend on the value", NEP 50); NumSharp keeps the value-based answer as a documented convenience.

can_cast(long, NPTypeCode, string)

Returns True if the long value can be cast to the data type according to the casting rule.

public static bool can_cast(long value, NPTypeCode to, string casting = "safe")

Parameters

value long
to NPTypeCode
casting string

Returns

bool

can_cast(object, NPTypeCode, string)

Returns True if the scalar value can be cast to the data type according to the casting rule.

public static bool can_cast(object value, NPTypeCode to, string casting = "safe")

Parameters

value object

Scalar value to check.

to NPTypeCode

Data type to cast to.

casting string

Controls what kind of data casting may occur.

Returns

bool

True if the value can be cast to the target type.

Examples

np.can_cast(100, NPTypeCode.Byte)    // True (100 fits in byte)
np.can_cast(1000, NPTypeCode.Byte)   // False (1000 > 255)

Remarks

Scalar values can often be cast to smaller types if the value fits (NumSharp extension — see can_cast(int, NPTypeCode, string)).

can_cast(float, NPTypeCode, string)

Returns True if the float value can be cast to the data type according to the casting rule.

public static bool can_cast(float value, NPTypeCode to, string casting = "safe")

Parameters

value float
to NPTypeCode
casting string

Returns

bool

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
to DType
casting string

Returns

bool

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.

can_cast(ushort, NPTypeCode, string)

Returns True if the ushort value can be cast to the data type according to the casting rule.

public static bool can_cast(ushort value, NPTypeCode to, string casting = "safe")

Parameters

value ushort
to NPTypeCode
casting string

Returns

bool

can_cast(uint, NPTypeCode, string)

Returns True if the uint value can be cast to the data type according to the casting rule.

public static bool can_cast(uint value, NPTypeCode to, string casting = "safe")

Parameters

value uint
to NPTypeCode
casting string

Returns

bool

can_cast(ulong, NPTypeCode, string)

Returns True if the ulong value can be cast to the data type according to the casting rule.

public static bool can_cast(ulong value, NPTypeCode to, string casting = "safe")

Parameters

value ulong
to NPTypeCode
casting string

Returns

bool

can_cast<TFrom, TTo>(string)

Returns True if cast between data types can occur according to the casting rule.

public static bool can_cast<TFrom, TTo>(string casting = "safe") where TFrom : struct where TTo : struct

Parameters

casting string

Controls what kind of data casting may occur.

Returns

bool

True if cast can occur according to the casting rule.

Type Parameters

TFrom

Source type.

TTo

Target type.

Examples

np.can_cast<int, long>()           // True
np.can_cast<long, int>()           // False
np.can_cast<int, float>("safe")    // True (int to float is safe)

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

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
where NDArray
dtype DType

The dtype the returned ndarray should be of, only non integer values are supported.

Returns

NDArray

The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar.

Remarks

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
choices NDArray
out NDArray
mode string

Returns

NDArray

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
choices NDArray[]
out NDArray
mode string

Returns

NDArray

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

Exceptions

ValueError

choices is empty ("0-length sequence."), or an index is out of range under mode="raise" ("invalid entry in choice array").

TypeError

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

clip(NDArray, NDArray, NDArray, NDArray, DType, 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=None, a_max=None, out=None, *, min=None, max=None). Either or both bounds may be null. The min and max keyword aliases (added in NumPy 2.0) are accepted; mixing a_min with min (or a_max with max) throws.

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)

Parameters

a NDArray

Array containing elements to clip.

a_min NDArray

Minimum value. If null, clipping is not performed on lower interval edge.

a_max NDArray

Maximum value. If null, clipping is not performed on upper interval edge.

out NDArray

The results will be placed in this array. It may be the input array for in-place clipping. out must be of the right shape to hold the output. Its type is preserved.

dtype DType

The dtype the returned ndarray should be of.

min NDArray

NumPy 2.x keyword alias for a_min. Cannot be combined with a_min.

max NDArray

NumPy 2.x keyword alias for a_max. Cannot be combined with a_max.

Returns

NDArray

An array with the elements of a, but where values < min are replaced with min, and those > max with max.

Remarks

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.

Remarks

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.

Returns

DType

The common scalar type as CLR Type.

Examples

np.common_type(np.array(new int[] {1, 2}))           // typeof(double)
np.common_type(a_float32, a_float64)                 // typeof(double)

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.

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.

Returns

NPTypeCode

The common scalar type as NPTypeCode.

Remarks

The return type will always be a floating-point type (minimum Double for integers).

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.

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.

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 ArgumentException, mirroring 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).

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.

concat(NDArray[], int?, NDArray, DType, string)

Join a sequence of arrays along an existing axis. Alias of concatenate(NDArray[], int?, NDArray, NPTypeCode?, 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

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

Remarks

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, NPTypeCode?) — 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

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

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
v NDArray
mode string

Returns

NDArray

copy(NDArray, char)

Return an array copy of the given object.

public static NDArray copy(NDArray a, char order = 'K')

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.

Returns

NDArray

Array interpretation of a.

Remarks

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

copyto(NDArray, NDArray, string, NDArray)

Copies values from one array to another, broadcasting as necessary.

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.

src NDArray

The array from which values are copied.

casting string

Controls what kind of data casting may occur when copying. Default "same_kind". Allowed values: "no", "equiv", "safe", "same_kind", "unsafe".

where NDArray

Optional boolean mask broadcast to dst's shape. Elements of src are only written to dst where the mask is true. null (default) is equivalent to where=True — every element is copied.

Remarks

Exceptions

NumSharpException

If dst is read-only (NumPy raises ValueError: assignment destination is read-only; the standard write guard — ThrowIfNotWriteable(Shape, string) — is the same one every other write path uses).

ArgumentException

If casting is not a recognised casting name, or where is not a boolean array.

InvalidCastException

If casting from src's dtype to dst's dtype is not allowed under the chosen rule (NumPy raises TypeError).

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. https://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html

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, sharing one engine with convolve(NDArray, NDArray, string).

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. For LONG float kernels NumPy routes the middle/ramps through cblas sdot/ddot (a different summation order); NumSharp.Core has no BLAS, so those cases carry a bounded-ULP divergence — a pre-existing property of the scalar sum, NOT introduced by the SIMD path (the SIMD kernel is bit-identical to the scalar sum for every dtype and size). Integer, bool, complex, decimal and Half outputs are exact.

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

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

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.

Remarks

count_nonzero(NDArray, int, bool)

Counts the number of non-zero values in the array along the given axis.

public static NDArray count_nonzero(NDArray a, int axis, bool keepdims = false)

Parameters

a NDArray

The array for which to count non-zeros.

axis int

Axis along which to count non-zeros.

keepdims bool

If True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

Number of non-zero values along the specified axis.

Remarks

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

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 may have length 2 or 3 — where a vector's length is 2 its missing third component is treated as zero. When BOTH inputs are 2-vectors the scalar z-component is returned; otherwise the 3-vector result is placed along axisc.

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). Ignored when both inputs are 2-D vectors (the return is then scalar). 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, int, int) (no new kernel), so it supports full broadcasting of the leading axes and its result dtype is promote_types(a.dtype, b.dtype). The 2-vector forms are DEPRECATED in NumPy 2.0 but still compute; NumSharp does not model that warning and simply returns the value. Distinct from cross(NDArray, NDArray, int), the Array-API form, which accepts 3-vectors only and takes a single axis.

Exceptions

ValueError

When either input has zero dimensions, or a vector's length is neither 2 nor 3.

AxisError

When an axis is out of bounds for its operand.

cumprod(NDArray, int?, DType, NDArray)

Return the cumulative product of the elements along a given axis.

public static NDArray cumprod(NDArray arr, int? axis = null, DType typeCode = null, NDArray @out = null)

Parameters

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

typeCode DType

Type of the returned array and of the accumulator in which the elements are multiplied. 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

cumsum(NDArray, int?, DType, NDArray)

Return the cumulative sum of the elements along a given axis.

public static NDArray cumsum(NDArray arr, int? axis = null, DType typeCode = null, NDArray @out = null)

Parameters

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

typeCode DType

Type of the returned array and of the accumulator in which the elements are summed. 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

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

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

delete(NDArray, NDArray, int?)

NDArray-typed obj dispatch — selects the integer-array path or the boolean-mask path based on obj.GetTypeCode. 0-D and 1-element integer arrays collapse to the scalar-index fast path (matching 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
obj NDArray
axis int?

Returns

NDArray

delete(NDArray, Slice, int?)

Slice-index overload. obj is interpreted via Python slice.indices(N) against the axis length.

public static NDArray delete(NDArray arr, Slice obj, int? axis = null)

Parameters

arr NDArray
obj Slice
axis int?

Returns

NDArray

delete(NDArray, bool[], int?)

Bool-array overload — values are interpreted as a keep-mask inversion. Length must match the targeted axis size (NumPy raises ValueError otherwise).

public static NDArray delete(NDArray arr, bool[] obj, int? axis = null)

Parameters

arr NDArray
obj bool[]
axis int?

Returns

NDArray

delete(NDArray, int, int?)

Return a new array with the element at obj along axis removed.

public static NDArray delete(NDArray arr, int obj, int? axis = null)

Parameters

arr NDArray

Input array.

obj int

Integer index of the position to remove. Accepts negative indices (counted from the end). Raises IndexOutOfRangeException when out of bounds for the selected axis.

axis int?

Axis along which to delete. null (default) flattens arr first and returns a 1-D result.

Returns

NDArray

A C-contiguous copy of arr with one sub-array removed along axis.

Remarks

delete(NDArray, int[], int?)

Array-of-indices overload. Negative indices are normalized; duplicates are silently collapsed (each axis position is removed at most once).

public static NDArray delete(NDArray arr, int[] obj, int? axis = null)

Parameters

arr NDArray
obj int[]
axis int?

Returns

NDArray

delete(NDArray, long, int?)

Long-index overload of delete(NDArray, int, int?).

public static NDArray delete(NDArray arr, long obj, int? axis = null)

Parameters

arr NDArray
obj long
axis int?

Returns

NDArray

delete(NDArray, long[], int?)

Long-array-of-indices overload.

public static NDArray delete(NDArray arr, long[] obj, int? axis = null)

Parameters

arr NDArray
obj long[]
axis int?

Returns

NDArray

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.

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.

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

Exceptions

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

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.

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

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.

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

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

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

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

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

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.

Remarks

Equivalent to split with axis=2. Array must have ndim >= 3. https://numpy.org/doc/stable/reference/generated/numpy.dsplit.html

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.

Remarks

Equivalent to split with axis=2. Array must have ndim >= 3. https://numpy.org/doc/stable/reference/generated/numpy.dsplit.html

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.

Remarks

dtype(DType)

A descriptor converts to itself — np.dtype(np.dtype('f8')).

public static DType dtype(DType dtype)

Parameters

dtype DType

Returns

DType

dtype(NPTypeCode)

The descriptor of an NPTypeCode — NumSharp's storage enum spelling.

public static DType dtype(NPTypeCode typecode)

Parameters

typecode NPTypeCode

Returns

DType

dtype(string)

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)

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

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.

Remarks

Grammar, in NumPy's order: a comma-string / parenthesised sub-array is a structured dtype (unsupported); the byte-order character is consumed ('|' reads as native, 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 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. Case matters everywhere ("I4" is not "i4"), whitespace is never stripped.

https://numpy.org/doc/stable/reference/arrays.dtypes.html

Exceptions

ArgumentNullException

dtype is null.

NotSupportedException

A valid NumPy dtype NumSharp does not implement — bytes/str (S, U, a, c), void, object, complex64, structured / sub-array / comma-string dtypes — or an invalid string, reported with NumPy's own data type 'X' not understood / Alias 'bool8' was removed in NumPy 2.0. … texts.

TypeError

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

dtype(Type)

The descriptor of a C# Typenp.dtype(typeof(int)) (NumPy's np.dtype(np.int32)).

public static DType dtype(Type type)

Parameters

type Type

Returns

DType

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

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

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 contraction is 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) 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

NotSupportedException

Always, once the subscripts validate.

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
operands NDArray[]
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'.

casting string

Casting rule — "no", "equiv", "safe", "same_kind" or "unsafe".

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 NAMEnp.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 contraction is 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) 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).

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

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

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

empty(Shape)

Return a new array of given shape and type, without initializing entries.

public static NDArray empty(Shape shape)

Parameters

shape Shape

Shape of the empty array, e.g., (2, 3) or 2.

Returns

NDArray

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

Remarks

empty(Shape, DType, string)

Return a new array of given shape and type, without initializing entries.

public static NDArray empty(Shape shape, DType dtype, string device = null)

Parameters

shape Shape

Shape of the empty array, e.g., (2, 3) or 2.

dtype DType

Desired output dtype — one descriptor parameter, like NumPy's dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. Default (null) is numpy.float64.

device string

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

Returns

NDArray

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

Remarks

empty(Shape, char, DType)

Return a new array of given shape and type with a specified memory layout.

public static NDArray empty(Shape shape, char order, DType dtype = null)

Parameters

shape Shape

Shape of the empty array, e.g., (2, 3) or 2.

order char

Memory layout: 'C' (row-major), 'F' (column-major), 'A' (any), 'K' (keep). With no source array, 'A' and 'K' default to 'C'.

dtype DType

Desired output data-type. Default is numpy.float64.

Returns

NDArray

Array of uninitialized data with the requested memory layout.

Remarks

empty(int)

Return a new array of given shape and type, without initializing entries.

public static NDArray empty(int shape)

Parameters

shape int

Returns

NDArray

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

Remarks

empty(int[])

Return a new array of given shape and type, without initializing entries.

public static NDArray empty(int[] shape)

Parameters

shape int[]

Shape of the empty array, e.g., (2, 3) or 2.

Returns

NDArray

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

Remarks

empty(long[])

Return a new array of given shape and type, without initializing entries.

public static NDArray empty(long[] shape)

Parameters

shape long[]

Shape of the empty array, e.g., (2, 3) or 2.

Returns

NDArray

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

Remarks

empty_like(NDArray, DType, Shape, char, string)

Return a new array with the same shape and type as a given array.

public static NDArray empty_like(NDArray prototype, DType dtype, Shape shape, char order, 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 (a Type, NPTypeCode, dtype string or DType — all convert implicitly).

shape Shape

Overrides the shape of the result.

order char

Memory layout: 'C', 'F', 'A' or 'K' (default, preserves prototype layout).

device string

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

Returns

NDArray

Array of uninitialized (arbitrary) data with the same shape and type as prototype.

Remarks

empty_like(NDArray, DType, Shape, string)

Return a new array with the same shape and type as a given array.

public static NDArray empty_like(NDArray prototype, DType dtype = null, Shape shape = default, 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.

shape Shape

Overrides the shape of the result.

device string

Returns

NDArray

Array of uninitialized (arbitrary) data with the same shape and type as prototype.

Remarks

empty<T>(int[])

Return a new array of given shape and type, without initializing entries.

public static NDArray empty<T>(int[] shape)

Parameters

shape int[]

Shape of the empty array, e.g., (2, 3) or 2.

Returns

NDArray

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

Type Parameters

T

Remarks

empty<T>(long[])

Return a new array of given shape and type, without initializing entries.

public static NDArray empty<T>(long[] shape)

Parameters

shape long[]

Shape of the empty array, e.g., (2, 3) or 2.

Returns

NDArray

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

Type Parameters

T

Remarks

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

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)

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 @out = null)

Parameters

expr NDExpr

Expression with embedded array leaves. 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)

A repeated NDArray reference becomes ONE iterator operand.

out NDArray

Optional pre-allocated result (ufunc out= rules: joins the broadcast but is never stretched; same_kind cast from the resolved dtype; may alias an input — overlap-safe).

Returns

NDArray

The evaluated array at the tree's NumPy result_type — dtypes 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.

evaluate(NDExpr, NDArray[], NDArray)

Evaluate an expression built over positional Input(int) leaves against an explicit operand list: np.evaluate(NDExpr.Input(0) * NDExpr.Input(1), new[] { a, b }).

public static NDArray evaluate(NDExpr expr, NDArray[] operands, NDArray @out = null)

Parameters

expr NDExpr
operands NDArray[]
out NDArray

Returns

NDArray

exp(NDArray)

Base-e exponential, element-wise.

public static NDArray exp(NDArray a)

Parameters

a NDArray

Input value.

Returns

NDArray

The natural logarithm of x, element-wise. This is a scalar NDArray.

Remarks

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

Remarks

exp2(NDArray)

Calculate 2**p for all p in the input array.

public static NDArray exp2(NDArray a)

Parameters

a NDArray

Input value.

Returns

NDArray

Element-wise 2 to the power x. This is a scalar if x is a scalar.

Remarks

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

Remarks

expand_dims(NDArray, IEnumerable<int>)

Sequence overload — accepts any IEnumerable<T>, materializes to an array, and delegates to the tuple-axis path.

public static NDArray expand_dims(NDArray a, IEnumerable<int> axis)

Parameters

a NDArray
axis IEnumerable<int>

Returns

NDArray

expand_dims(NDArray, int)

public static NDArray expand_dims(NDArray a, int axis)

Parameters

a NDArray
axis int

Returns

NDArray

expand_dims(NDArray, int[])

Expand the shape of an array. Insert new axes that will appear at the axis positions in the expanded output.

public static NDArray expand_dims(NDArray a, int[] axis)

Parameters

a NDArray
axis int[]

Returns

NDArray

Remarks

Matches NumPy 2.x: each axis in the tuple is normalized against the FINAL output ndim (a.ndim + axis.Length). Duplicate normalized positions raise ArgumentException ("repeated axis"); out-of-range axes throw the same. Empty axis returns the input unchanged.

expm1(NDArray)

Calculate exp(x) - 1 for all elements in the array.

public static NDArray expm1(NDArray a)

Parameters

a NDArray

Input value.

Returns

NDArray

Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar.

Remarks

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

Remarks

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.

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

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.

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,int[]) 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.

find_common_type(DType[])

Determine common type following standard coercion rules — the DType form, which is what 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[]

A list of dtype descriptors representing arrays. Can be null.

Returns

DType

The common data type of array_types (no scalar types).

Remarks

find_common_type(DType[], DType[])

Determine common type following standard coercion rules — the DType form, which is what 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[]

A list of dtype descriptors representing arrays. Can be null.

scalar_types DType[]

A list of dtype descriptors representing scalars. Can be null.

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 kind (dtype.kind). If the kind is not understood, then None is returned.

Remarks

find_common_type(NPTypeCode[], NPTypeCode[])

Determine common type following standard coercion rules.

public static DType find_common_type(NPTypeCode[] array_types, NPTypeCode[] scalar_types)

Parameters

array_types NPTypeCode[]

A list of dtypes or dtype convertible objects representing arrays. Can be null.

scalar_types NPTypeCode[]

A list of dtypes or dtype convertible objects representing scalars.Can be null.

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 kind (dtype.kind). If the kind is not understood, then None is returned.

Remarks

find_common_type(NPTypeCode[], Type[])

Determine common type following standard coercion rules.

public static DType find_common_type(NPTypeCode[] array_types, Type[] scalar_types)

Parameters

array_types NPTypeCode[]

A list of dtypes or dtype convertible objects representing arrays. Can be null.

scalar_types Type[]

A list of dtypes or dtype convertible objects representing scalars.Can be null.

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 kind (dtype.kind). If the kind is not understood, then None is returned.

Remarks

find_common_type(params string[])

Resolves to which type should the output be.

public static DType find_common_type(params string[] involvedTypes)

Parameters

involvedTypes string[]

Returns

DType

find_common_type(string[], string[])

Determine common type following standard coercion rules.

public static DType find_common_type(string[] array_types, string[] scalar_types)

Parameters

array_types string[]

A list of dtypes or dtype convertible objects representing arrays. Can be null.

scalar_types string[]

A list of dtypes or dtype convertible objects representing scalars.Can be null.

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 kind (dtype.kind). If the kind is not understood, then None is returned.

Remarks

find_common_type(Type[])

Determine common type following standard coercion rules.

public static DType find_common_type(Type[] array_types)

Parameters

array_types Type[]

A list of dtypes or dtype convertible objects representing arrays. Can be null.

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 kind (dtype.kind). If the kind is not understood, then None is returned.

Remarks

find_common_type(Type[], NPTypeCode[])

Determine common type following standard coercion rules.

public static DType find_common_type(Type[] array_types, NPTypeCode[] scalar_types)

Parameters

array_types Type[]

A list of dtypes or dtype convertible objects representing arrays. Can be null.

scalar_types NPTypeCode[]

A list of dtypes or dtype convertible objects representing scalars.Can be null.

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 kind (dtype.kind). If the kind is not understood, then None is returned.

Remarks

find_common_type(Type[], Type[])

Determine common type following standard coercion rules.

public static DType find_common_type(Type[] array_types, Type[] scalar_types)

Parameters

array_types Type[]

A list of dtypes or dtype convertible objects representing arrays. Can be null.

scalar_types Type[]

A list of dtypes or dtype convertible objects representing scalars.Can be null.

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 kind (dtype.kind). If the kind is not understood, then None is returned.

Remarks

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, a NumPy dtype string or a DType (np.float64, arr.dtype) all convert implicitly.

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

finfo(NDArray)

Machine limits for floating point types.

public static finfo finfo(NDArray arr)

Parameters

arr NDArray

An NDArray with floating point dtype.

Returns

finfo

An finfo object describing the array's floating point type limits.

Examples

var a = np.array(new double[] {1.0, 2.0, 3.0});
var info = np.finfo(a);
Console.WriteLine(info.bits);  // 64

Exceptions

ArgumentNullException

Thrown if arr is null.

finfo(string)

Machine limits for floating point types.

public static finfo finfo(string dtypeName)

Parameters

dtypeName string

A dtype string (e.g., "float32", "float64", "double").

Returns

finfo

An finfo object describing the floating point type limits.

Examples

var info = np.finfo("float64");
Console.WriteLine(info.bits);  // 64

Exceptions

ArgumentException

Thrown if dtypeName is not a valid floating point dtype.

finfo<T>()

Machine limits for floating point types.

public static finfo finfo<T>() where T : struct

Returns

finfo

An finfo object describing the floating point type limits.

Type Parameters

T

A floating point type (float, double, decimal).

Examples

var info = np.finfo<double>();
Console.WriteLine(info.bits);  // 64

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[])

Reverse the order of elements in an array along the given axes. The shape of the array is preserved, but the elements are reordered.

public static NDArray flip(NDArray m, int[] axis)

Parameters

m NDArray

Input array.

axis int[]

Axes along which to flip over — NumPy's tuple-of-ints form; flipping is performed on all of the specified axes. Negative axes count from the last to the first axis. An empty array flips no axis (returns an unreversed view of the whole array); null flips all axes.

Returns

NDArray

A view of m with the entries of the given axes reversed. Since a view is returned, this operation is done in constant time.

Remarks

Exceptions

AxisError

When any axis is out of bounds for the array's dimensions.

ValueError

When an axis is repeated ("repeated axis").

flip(NDArray, int?)

Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered.

public static NDArray flip(NDArray m, int? axis = null)

Parameters

m NDArray

Input array.

axis int?

Axis along which to flip over. The default, null, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis.

Returns

NDArray

A view of m with the entries of axis reversed. Since a view is returned, this operation is done in constant time.

Remarks

Exceptions

AxisError

When axis is out of bounds for the array's dimensions.

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.

Remarks

Exceptions

ValueError

When m is less than 2-d ("Input must be >= 2-d.").

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.

Remarks

Exceptions

ValueError

When m is less than 1-d ("Input must be >= 1-d.").

floor(NDArray, NDArray, NDArray, DType)

public static NDArray floor(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)

Parameters

x NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

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

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

fmax(NDArray, NDArray, DType)

Element-wise maximum of array elements, ignoring NaNs. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The net effect is that NaNs are ignored when possible.

public static NDArray fmax(NDArray x1, NDArray x2, DType dtype = null)

Parameters

x1 NDArray

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

x2 NDArray

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

dtype DType

Loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.

Returns

NDArray

The maximum of x1 and x2, element-wise, ignoring NaNs.

fmax(NDArray, NDArray, NDArray)

Element-wise maximum of array elements, ignoring NaNs, writing into @out.

public static NDArray fmax(NDArray x1, NDArray x2, NDArray @out)

Parameters

x1 NDArray
x2 NDArray
out NDArray

Returns

NDArray

fmin(NDArray, NDArray, DType)

Element-wise minimum of array elements, ignoring NaNs. Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The net effect is that NaNs are ignored when possible.

public static NDArray fmin(NDArray x1, NDArray x2, DType dtype = null)

Parameters

x1 NDArray

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

x2 NDArray

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

dtype DType

Loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.

Returns

NDArray

The minimum of x1 and x2, element-wise, ignoring NaNs.

fmin(NDArray, NDArray, NDArray)

Element-wise minimum of array elements, ignoring NaNs, writing into @out.

public static NDArray fmin(NDArray x1, NDArray x2, NDArray @out)

Parameters

x1 NDArray
x2 NDArray
out NDArray

Returns

NDArray

format_float_positional(double, int?, bool, bool, char, bool, int?, int?, int?)

Format a floating-point scalar as a decimal string in positional notation (NumPy's np.format_float_positional).

public static string format_float_positional(double x, int? precision = null, bool unique = true, bool fractional = true, char trim = 'k', bool sign = false, int? pad_left = null, int? pad_right = null, int? min_digits = null)

Parameters

x double
precision int?
unique bool
fractional bool
trim char
sign bool
pad_left int?
pad_right int?
min_digits int?

Returns

string

format_float_scientific(double, int?, bool, char, bool, int?, int?, int?)

Format a floating-point scalar as a decimal string in scientific notation (NumPy's np.format_float_scientific).

public static string format_float_scientific(double x, int? precision = null, bool unique = true, char trim = 'k', bool sign = false, int? pad_left = null, int? exp_digits = null, int? min_digits = null)

Parameters

x double
precision int?
unique bool
trim char
sign bool
pad_left int?
exp_digits int?
min_digits int?

Returns

string

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. Default is float64.

count long

Number of items to read. -1 means all data in the buffer.

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

Remarks

frombuffer(MemoryView, NPTypeCode, 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, 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. Default is float64.

count long

Number of items to read. -1 means all data in the buffer.

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

Remarks

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). Little-endian / native dtypes are a zero-copy view; a big-endian dtype needs a byte-swap and so COPIES (as the byte[] path does).

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

Data-type of the returned array. Default is float64.

count long

Number of items to read. -1 means all data in the buffer.

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

Remarks

frombuffer(ArraySegment<byte>, DType, long)

Interpret an ArraySegment as a 1-dimensional array. Uses the segment's Offset and Count automatically.

public static NDArray frombuffer(ArraySegment<byte> segment, DType dtype = null, long count = -1)

Parameters

segment ArraySegment<byte>

The array segment to interpret.

dtype DType

Data-type of the returned array. Default is float64.

count long

Number of items to read. -1 means all data in the segment.

Returns

NDArray

1-dimensional NDArray viewing the segment's data.

frombuffer(ArraySegment<byte>, NPTypeCode, long)

Interpret an ArraySegment as a 1-dimensional array.

public static NDArray frombuffer(ArraySegment<byte> segment, NPTypeCode dtype, long count = -1)

Parameters

segment ArraySegment<byte>
dtype NPTypeCode
count long

Returns

NDArray

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[]

An object that exposes the buffer interface.

dtype DType

Data-type of the returned array. Default is float64.

count long

Number of items to read. -1 means all data in the buffer.

offset long

Start reading the buffer from this offset (in bytes). Default is 0.

Returns

NDArray

1-dimensional NDArray with data interpreted from the buffer.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html

Like NumPy, this creates a VIEW of the buffer (pins the array, shares memory). Modifications to the NDArray will affect the original buffer. The buffer must stay alive while the NDArray is in use.

frombuffer(byte[], NPTypeCode, long, long)

Interpret a buffer as a 1-dimensional array.

public static NDArray frombuffer(byte[] buffer, NPTypeCode dtype, long count = -1, long offset = 0)

Parameters

buffer byte[]

An object that exposes the buffer interface.

dtype NPTypeCode

Data-type of the returned array. Default is float64.

count long

Number of items to read. -1 means all data in the buffer.

offset long

Start reading the buffer from this offset (in bytes). Default is 0.

Returns

NDArray

1-dimensional NDArray with data interpreted from the buffer.

frombuffer(byte[], string, long, long)

Interpret a buffer as a 1-dimensional array.

public static NDArray frombuffer(byte[] buffer, string dtype, long count = -1, long offset = 0)

Parameters

buffer byte[]

An object that exposes the buffer interface.

dtype string

Data-type string (e.g., ">u4" for big-endian uint32).

count long

Number of items to read. -1 means all data in the buffer.

offset long

Start reading the buffer from this offset (in bytes). Default is 0.

Returns

NDArray

1-dimensional NDArray with data interpreted from the buffer.

Remarks

Note: Big-endian dtype strings (">u4", ">i4", etc.) require a COPY to perform byte swapping. Little-endian and native endian create views without copying.

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. 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. Use to transfer ownership: dispose: () => Marshal.FreeHGlobal(ptr) If null, caller is responsible for memory lifetime (view semantics).

Returns

NDArray

1-dimensional NDArray viewing/owning the memory.

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

frombuffer(nint, long, NPTypeCode, long, long, Action)

Interpret unmanaged memory at a pointer as a 1-dimensional array.

public static NDArray frombuffer(nint address, long byteLength, NPTypeCode dtype, long count = -1, long offset = 0, Action dispose = null)

Parameters

address nint
byteLength long
dtype NPTypeCode
count long
offset long
dispose Action

Returns

NDArray

frombuffer(Memory<byte>, DType, long, long)

Interpret a Memory<byte> as a 1-dimensional array. Creates a view if backed by an array, otherwise copies.

public static NDArray frombuffer(Memory<byte> memory, DType dtype = null, long count = -1, long offset = 0)

Parameters

memory Memory<byte>

The memory to interpret.

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 within the memory. Default is 0.

Returns

NDArray

1-dimensional NDArray.

frombuffer(Memory<byte>, NPTypeCode, long, long)

Interpret a Memory<byte> as a 1-dimensional array.

public static NDArray frombuffer(Memory<byte> memory, NPTypeCode dtype, long count = -1, long offset = 0)

Parameters

memory Memory<byte>
dtype NPTypeCode
count long
offset long

Returns

NDArray

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>
dtype DType
count long
offset long

Returns

NDArray

frombuffer(ReadOnlySpan<byte>, NPTypeCode, 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, NPTypeCode dtype, long count = -1, long offset = 0)

Parameters

buffer ReadOnlySpan<byte>
dtype NPTypeCode
count long
offset long

Returns

NDArray

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.

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*
byteLength long
dtype NPTypeCode
count long
offset long
dispose Action

Returns

NDArray

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.

dtype DType

Target data-type. Default preserves source type.

count long

Number of items of target dtype. -1 for all.

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)

frombuffer<TSource>(TSource[], NPTypeCode, long, long)

Reinterpret a typed array as a different dtype.

public static NDArray frombuffer<TSource>(TSource[] array, NPTypeCode dtype, long count = -1, long offset = 0) where TSource : unmanaged

Parameters

array TSource[]
dtype NPTypeCode
count long
offset long

Returns

NDArray

Type Parameters

TSource

fromfile(Stream, DType, int, string, long)

Construct an array from data in an open Stream (the file-object form). Reads from the stream's current position and leaves it open.

public static NDArray fromfile(Stream stream, DType dtype = null, int count = -1, string sep = "", long offset = 0)

Parameters

stream Stream
dtype DType

Element type. For binary files it sets the item size; defaults to double.

count int

Number of items to read. -1 (default) reads the whole file.

sep string

Separator between items for a text file. Empty (default) reads binary. A separator containing spaces matches runs of whitespace; a whitespace-only separator splits on any whitespace run.

offset long

Bytes to skip from the file's current position. Binary files only.

Returns

NDArray

Remarks

fromfile(string, DType, int, string, long)

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, int count = -1, string sep = "", long offset = 0)

Parameters

file string

A filename.

dtype DType

Element type. For binary files it sets the item size; defaults to double.

count int

Number of items to read. -1 (default) reads the whole file.

sep string

Separator between items for a text file. Empty (default) reads binary. A separator containing spaces matches runs of whitespace; a whitespace-only separator splits on any whitespace run.

offset long

Bytes to skip from the file's current position. Binary files only.

Returns

NDArray

Remarks

fromstring(string, DType, int, string)

Construct a 1-D array from the numbers in a text string.

public static NDArray fromstring(string @string, DType dtype = null, int count = -1, string sep = null)

Parameters

string string

The text to parse. Numbers are separated by sep.

dtype DType

Element type of the result (default double).

count int

Number of items to read; -1 (default) reads all of them.

sep string

Separator between numbers. A separator containing spaces matches runs of whitespace (a whitespace-only separator splits on any whitespace run). An empty or null separator selects the removed binary mode and raises ValueError — use frombuffer(byte[],Type,long,long) instead.

Returns

NDArray

Remarks

Parity with NumPy 2.4.2's np.fromstring (text mode). Shares fromfile(string, DType, int, string, long)'s text reader, so item parsing, the single-trailing-separator rule and the verbatim "unmatched data" error all match it. https://numpy.org/doc/stable/reference/generated/numpy.fromstring.html

full(Shape, object, DType, string)

Return a new array of given shape and type, filled with fill_value.

public static NDArray full(Shape shape, object fill_value, DType dtype = null, string device = null)

Parameters

shape Shape

Shape of the array, e.g., (2, 3) or 2.

fill_value object

Fill value (scalar).

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. Default (null) infers from fill_value.

device string

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

Returns

NDArray

Array of fill_value with the given shape, dtype, and order.

Remarks

full(int[], object)

Return a new array of given shape and type, filled with fill_value.

public static NDArray full(int[] shape, object fill_value)

Parameters

shape int[]

Shape of the array, e.g., (2, 3) or 2.

fill_value object

Fill value (scalar).

Returns

NDArray

Array of fill_value with the given shape, dtype, and order.

Remarks

full(long[], object)

Return a new array of given shape and type, filled with fill_value.

public static NDArray full(long[] shape, object fill_value)

Parameters

shape long[]

Shape of the array, e.g., (2, 3) or 2.

fill_value object

Fill value (scalar).

Returns

NDArray

Array of fill_value with the given shape, dtype, and order.

Remarks

full_like(NDArray, object, DType, char, string)

Return a full array with the same shape and type as a given array.

public static NDArray full_like(NDArray a, object fill_value, DType dtype, char order, 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.

dtype DType

Overrides the data type of the result.

order char

Memory layout: 'C', 'F', 'A' or 'K' (default, preserves source layout).

device string

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

Returns

NDArray

Array of fill_value with the same shape and type as a.

Remarks

full_like(NDArray, object, DType, string)

Return a full array with the same shape and type as a given array.

public static NDArray full_like(NDArray a, object fill_value, DType dtype = 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.

dtype DType

Overrides the data type of the result.

device string

Returns

NDArray

Array of fill_value with the same shape and type as a.

Remarks

full<T>(int[], object)

Return a new array of given shape and type, filled with fill_value.

public static NDArray full<T>(int[] shape, object fill_value) where T : unmanaged

Parameters

shape int[]

Shape of the array, e.g., (2, 3) or 2.

fill_value object

Fill value (scalar).

Returns

NDArray

Array of fill_value with the given shape, dtype, and order.

Type Parameters

T

Remarks

full<T>(long[], object)

Return a new array of given shape and type, filled with fill_value.

public static NDArray full<T>(long[] shape, object fill_value) where T : unmanaged

Parameters

shape long[]

Shape of the array, e.g., (2, 3) or 2.

fill_value object

Fill value (scalar).

Returns

NDArray

Array of fill_value with the given shape, dtype, and order.

Type Parameters

T

Remarks

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 on the calling thread).

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 thread-local: it reflects the last setbufsize(long) call on the current thread (or the 8192 default if none), matching NumPy 2.x's context-local error/buffer state. The buffer size affects only how buffered iteration is chunked internally — it never changes any computed result.

np.getbufsize();          // 8192
np.setbufsize(4096);      // returns 8192 (the previous size)
np.getbufsize();          // 4096

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

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

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.

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.

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

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.

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

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.

Remarks

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

Parameters

dtype DType

The integer dtype — one descriptor parameter, like NumPy's: a C# Type (typeof(int)), an NPTypeCode, a NumPy dtype string or a DType (np.int32, arr.dtype) all convert implicitly.

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

iinfo(NDArray)

Machine limits for integer types.

public static iinfo iinfo(NDArray arr)

Parameters

arr NDArray

An NDArray with integer dtype.

Returns

iinfo

An iinfo object describing the array's integer type limits.

Examples

var a = np.array(new int[] {1, 2, 3});
var info = np.iinfo(a);
Console.WriteLine(info.bits);  // 32

Exceptions

ArgumentNullException

Thrown if arr is null.

iinfo(string)

Machine limits for integer types.

public static iinfo iinfo(string dtypeName)

Parameters

dtypeName string

A dtype string (e.g., "int32", "uint8", "bool").

Returns

iinfo

An iinfo object describing the integer type limits.

Examples

var info = np.iinfo("int32");
Console.WriteLine(info.bits);  // 32

Exceptions

ArgumentException

Thrown if dtypeName is not a valid integer dtype.

iinfo<T>()

Machine limits for integer types.

public static iinfo iinfo<T>() where T : struct

Returns

iinfo

An iinfo object describing the integer type limits.

Type Parameters

T

An integer type (bool, byte, short, ushort, int, uint, long, ulong, char).

Examples

var info = np.iinfo<int>();
Console.WriteLine(info.bits);  // 32

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

indices(int[], DType)

Return an array representing the indices of a grid. Dense form — for the sparse form, see indices_sparse(int[], DType).

public static NDArray indices(int[] dimensions, DType dtype = null)

Parameters

dimensions int[]

Shape of the grid.

dtype DType

Element type of the result. Default is long.

Returns

NDArray

Single dense array of shape (len(dimensions), *dimensions). The d-th sub-array contains the d-th coordinate of each output position.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.indices.html

NumPy's sparse=True mode is exposed as the separate method indices_sparse(int[], DType) — C# can't change return type based on a parameter the way Python's dynamic typing does, so splitting the API is clearer than throwing from a shared signature.

indices_sparse(int[], DType)

Sparse counterpart to indices(int[], DType) — returns a tuple of broadcast-shaped arrays where each axis-d array has shape (1, …, 1, dimensions[d], 1, …, 1). Equivalent to NumPy's np.indices(dimensions, sparse=True).

public static NDArray[] indices_sparse(int[] dimensions, DType dtype = null)

Parameters

dimensions int[]
dtype DType

Returns

NDArray[]

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) for the conjugating form).

insert(NDArray, NDArray, NDArray, int?)

NDArray-typed obj. Dispatches:

  • 0-D / 1-element integer ⇒ scalar single-index path.
  • 1-D bool ⇒ flatnonzero(NDArray) ⇒ multi-index path.
  • 1-D integer ⇒ multi-index path.
  • > 1-D ⇒ ArgumentException matching NumPy's "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
obj NDArray
values NDArray
axis int?

Returns

NDArray

insert(NDArray, NDArray, object, int?)

NDArray-obj overload accepting a scalar value.

public static NDArray insert(NDArray arr, NDArray obj, object value, int? axis = null)

Parameters

arr NDArray
obj NDArray
value object
axis int?

Returns

NDArray

insert(NDArray, Slice, NDArray, int?)

Slice-obj overload. obj is expanded via Python slice.indices(N) into an indices array, then the multi-index branch runs.

public static NDArray insert(NDArray arr, Slice obj, NDArray values, int? axis = null)

Parameters

arr NDArray
obj Slice
values NDArray
axis int?

Returns

NDArray

insert(NDArray, Slice, object, int?)

Slice-obj overload accepting a scalar value.

public static NDArray insert(NDArray arr, Slice obj, object value, int? axis = null)

Parameters

arr NDArray
obj Slice
value object
axis int?

Returns

NDArray

insert(NDArray, int, NDArray, int?)

Insert values along axis before the position obj. Scalar-obj path.

public static NDArray insert(NDArray arr, int obj, NDArray values, int? axis = null)

Parameters

arr NDArray
obj int
values NDArray
axis int?

Returns

NDArray

Remarks

insert(NDArray, int, object, int?)

int-overload accepting a scalar value.

public static NDArray insert(NDArray arr, int obj, object value, int? axis = null)

Parameters

arr NDArray
obj int
value object
axis int?

Returns

NDArray

insert(NDArray, int[], NDArray, int?)

int[]-obj overload. Always routes through the multi-index branch (NumPy parity: np.insert(arr, [1], v) != np.insert(arr, 1, v) when v has multiple axes, even though both have one insertion point).

public static NDArray insert(NDArray arr, int[] obj, NDArray values, int? axis = null)

Parameters

arr NDArray
obj int[]
values NDArray
axis int?

Returns

NDArray

insert(NDArray, int[], object, int?)

int[]-obj overload accepting a scalar value.

public static NDArray insert(NDArray arr, int[] obj, object value, int? axis = null)

Parameters

arr NDArray
obj int[]
value object
axis int?

Returns

NDArray

insert(NDArray, long, NDArray, int?)

Long-index overload of insert(NDArray, int, NDArray, int?).

public static NDArray insert(NDArray arr, long obj, NDArray values, int? axis = null)

Parameters

arr NDArray
obj long
values NDArray
axis int?

Returns

NDArray

insert(NDArray, long, object, int?)

Scalar-obj overload accepting a scalar value (NumPy: np.insert(a, 1, 99)). Broadcasts the value to the required shape using arr.dtype.

public static NDArray insert(NDArray arr, long obj, object value, int? axis = null)

Parameters

arr NDArray
obj long
value object
axis int?

Returns

NDArray

insert(NDArray, long[], NDArray, int?)

long[]-obj overload.

public static NDArray insert(NDArray arr, long[] obj, NDArray values, int? axis = null)

Parameters

arr NDArray
obj long[]
values NDArray
axis int?

Returns

NDArray

insert(NDArray, long[], object, int?)

long[]-obj overload accepting a scalar value.

public static NDArray insert(NDArray arr, long[] obj, object value, int? axis = null)

Parameters

arr NDArray
obj long[]
value object
axis int?

Returns

NDArray

interp(NDArray, NDArray, NDArray, double?, double?, 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, double? left = null, double? 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 double?

Value returned for x < xp[0]; default is fp[0]. Ignored when period is given.

right double?

Value returned for x > xp[-1]; default is fp[-1]. 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

interp(NDArray, NDArray, NDArray, Complex?, Complex?, double?)

Complex-fp overload of interp(NDArray, NDArray, NDArray, double?, double?, double?) accepting complex left / right fill values.

public static NDArray interp(NDArray x, NDArray xp, NDArray fp, Complex? left, Complex? right = null, double? period = null)

Parameters

x NDArray
xp NDArray
fp NDArray
left Complex?
right Complex?
period double?

Returns

NDArray

Remarks

intersect1d(NDArray, NDArray)

Find the intersection of two arrays (the bare-return form of np.intersect1d).
Return the sorted, unique values that are in both of the input arrays.

public static NDArray intersect1d(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

Sorted 1-D array of common, unique elements.

Remarks

intersect1d(NDArray, NDArray, bool)

Find the intersection of two arrays (bare-return, with the assume_unique speed hint).
Return the sorted, unique values that are in both of the input arrays.

public static NDArray intersect1d(NDArray ar1, NDArray ar2, bool assume_unique)

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. Default is False.

Returns

NDArray

Sorted 1-D array of common, unique elements.

Remarks

intersect1d(NDArray, NDArray, bool, bool)

Find the intersection of two arrays, returning the indices of the common values.
Mirrors NumPy's tuple return: np.intersect1d(a, b, return_indices=True) — both assume_unique and return_indices are optional so the keyword-only return_indices call binds here (the bare overloads above have no return_indices parameter, so they cannot capture it — no ambiguity with this one).

public static NDArray[] 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.

return_indices bool

If True, also return the indices of the first occurrences of the common values in ar1 and ar2.

Returns

NDArray[]

[values] when return_indices is False, otherwise [values, comm1, comm2].

Remarks

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

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

Parameters

a NDArray

Input array.

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.

iscomplexobj(NDArray)

Return True if x is a complex type or an array of complex numbers.

public static bool iscomplexobj(NDArray a)

Parameters

a NDArray

Input array or scalar.

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.

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
kind DType

Returns

bool

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.

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
kinds string[]

Returns

bool

isdtype(NDArray, string)

Returns True if the array's dtype is of a specified category (NumSharp convenience: NumPy's isdtype takes only a dtype, so this is np.isdtype(arr.dtype, kind)).

public static bool isdtype(NDArray arr, string kind)

Parameters

arr NDArray

The NDArray to check.

kind string

The dtype category.

Returns

bool

True if array's dtype belongs to the specified category.

Exceptions

ArgumentNullException

Thrown if arr is null.

isdtype(NDArray, string[])

Returns True if the array's dtype is of any of the specified categories.

public static bool isdtype(NDArray arr, string[] kinds)

Parameters

arr NDArray

The NDArray to check.

kinds string[]

Array of dtype categories to check.

Returns

bool

True if array's dtype belongs to any of the specified categories.

Exceptions

ArgumentNullException

Thrown if arr is null.

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

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

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.

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". Does not affect the result, only speed/memory. "table" is only valid for boolean/integer arrays.

Returns

NDArray

A boolean array with the same shape as element.

Remarks

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)

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

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.

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.

isreal(NDArray)

Returns a bool array, where True if input element is real.

public static NDArray isreal(NDArray a)

Parameters

a NDArray

Input array.

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.

isrealobj(NDArray)

Return True if x is a not complex type or an array of complex numbers.

public static bool isrealobj(NDArray a)

Parameters

a NDArray

Input array or scalar.

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.

isscalar(object)

Returns true incase of a number, bool or string. If null, returns false.

public static bool isscalar(object obj)

Parameters

obj object

Returns

bool

Remarks

issctype(object)

Determines whether the given object represents a scalar dtype.

public static bool issctype(object rep)

Parameters

rep object

The object to check.

Returns

bool

True if rep represents a scalar dtype.

Examples

np.issctype(typeof(int))       // True
np.issctype(NPTypeCode.Int32)  // True
np.issctype(typeof(NDArray))   // False

Remarks

issubdtype(DType, DType)

Returns True if the scalar type of arg1 is the scalar type 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
arg2 DType

Returns

bool

issubdtype(DType, string)

Returns True if the descriptor's scalar type is under the abstract category arg2 ("generic", "number", "integer", "signedinteger", "unsignedinteger", "inexact", "floating", "complexfloating", "bool") — NumPy's scalar hierarchy, in which datetime64 sits directly under generic ("Datetime doesn't fit in any category") and timedelta64 under signedinteger ("Timedelta is an integer with an associated unit").

public static bool issubdtype(DType arg1, string arg2)

Parameters

arg1 DType
arg2 string

Returns

bool

issubdtype(NDArray, string)

Returns True if first argument is a typecode lower/equal in type hierarchy.

public static bool issubdtype(NDArray arr, string arg2)

Parameters

arr NDArray

NDArray - array whose dtype to check.

arg2 string

string - string representing a typecode category.

Returns

bool

True if array's dtype is a subtype of arg2 category.

Exceptions

ArgumentNullException

Thrown if arr is null.

issubdtype(NPTypeCode, NPTypeCode)

Returns True if first argument is a typecode lower/equal in type hierarchy.

public static bool issubdtype(NPTypeCode arg1, NPTypeCode arg2)

Parameters

arg1 NPTypeCode

dtype - dtype representing a typecode.

arg2 NPTypeCode

dtype - dtype representing a typecode.

Returns

bool

True if arg1 is equal to or a subtype of arg2.

Remarks

When comparing two concrete types, returns true only if they are the same type. For hierarchy checks, use the (NPTypeCode, string) overload.

issubdtype(NPTypeCode, string)

Returns True if first argument is a typecode lower/equal in type hierarchy.

public static bool issubdtype(NPTypeCode arg1, string arg2)

Parameters

arg1 NPTypeCode

dtype or string - dtype or string representing a typecode.

arg2 string

dtype or string - dtype or string representing a typecode.

Returns

bool

True if arg1 is a subtype of arg2.

Examples

np.issubdtype(NPTypeCode.Int32, "integer")     // True
np.issubdtype(NPTypeCode.Double, "floating")   // True
np.issubdtype(NPTypeCode.Boolean, "integer")   // False (NumPy 2.x)

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.issubdtype.html

Implementation mirrors NumPy's issubdtype which uses issubclass() on the type hierarchy defined in numpy/_core/src/multiarray/multiarraymodule.c.

Type hierarchy in NumPy:

  • generic → number → integer/inexact
  • integer → signedinteger/unsignedinteger
  • inexact → floating/complexfloating

Note: In NumPy 2.x, bool is NOT a subtype of integer (it's directly under generic).

issubdtype(string, string)

Returns True if the dtype named by arg1 (a NumPy dtype string such as "i4" or "M8[ns]") is under the abstract category arg2. 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
arg2 string

Returns

bool

issubdtype(Type, string)

Returns True if first argument is a typecode lower/equal in type hierarchy.

public static bool issubdtype(Type arg1, string arg2)

Parameters

arg1 Type

Type - CLR type representing a typecode.

arg2 string

string - string representing a typecode category.

Returns

bool

True if arg1 is a subtype of arg2 category.

issubdtype(Type, Type)

Returns True if first argument is a typecode lower/equal in type hierarchy.

public static bool issubdtype(Type arg1, Type arg2)

Parameters

arg1 Type

Type - first CLR type.

arg2 Type

Type - second CLR type to compare against.

Returns

bool

True if arg1 is equal to or a subtype of arg2.

issubsctype(NPTypeCode, NPTypeCode)

Determine if a class is a subclass of a second class.

public static bool issubsctype(NPTypeCode arg1, NPTypeCode arg2)

Parameters

arg1 NPTypeCode

The dtype to check.

arg2 NPTypeCode

The dtype to compare against.

Returns

bool

True if arg1 is a subtype of arg2.

Remarks

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).
  • NDArrayndim != 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, string) 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.

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.

https://numpy.org/doc/stable/reference/generated/numpy.ix_.html

Exceptions

ValueError

A sequence is not 1-D ("Cross index must be 1 dimensional").

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

Remarks

left_shift(NDArray, NDArray)

Shift the bits of an integer to the left.

public static NDArray left_shift(NDArray x1, NDArray x2)

Parameters

x1 NDArray

Input array (integer types only).

x2 NDArray

Number of bits to shift (integer types only).

Returns

NDArray

Array with bits shifted left.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.left_shift.html

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

left_shift(NDArray, object)

Shift the bits of an integer to the left by a scalar or array-like amount.

public static NDArray left_shift(NDArray x1, object x2)

Parameters

x1 NDArray

Input array (integer types only).

x2 object

Number of bits to shift (scalar or array-like).

Returns

NDArray

Array with bits shifted left.

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

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

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

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.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.lexsort.html
Port of PyArray_LexSort (item_selection.c): 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.

linspace(double, double, int, bool, DType, string)

public static NDArray linspace(double start, double stop, int num, bool endpoint = true, DType dtype = null, string device = null)

Parameters

start double
stop double
num int
endpoint bool
dtype DType
device string

Returns

NDArray

linspace(double, double, long, bool, DType, string)

public static NDArray linspace(double start, double stop, long num, bool endpoint = true, DType dtype = null, string device = null)

Parameters

start double
stop double
num long
endpoint bool
dtype DType
device string

Returns

NDArray

linspace(float, float, int, bool, DType)

public static NDArray linspace(float start, float stop, int num, bool endpoint = true, DType dtype = null)

Parameters

start float
stop float
num int
endpoint bool
dtype DType

Returns

NDArray

linspace(float, float, long, bool, DType)

public static NDArray linspace(float start, float stop, long num, bool endpoint = true, DType dtype = null)

Parameters

start float
stop float
num long
endpoint bool
dtype DType

Returns

NDArray

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. NumSharp cannot unpickle at all, so this only selects the error message — and, per NumPy, 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

EndOfStreamException

The file is empty.

FormatException

The content is not a .npy or .npz file, or is malformed.

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. NumSharp cannot unpickle at all, so this only selects the error message — and, per NumPy, 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

EndOfStreamException

The file is empty.

FormatException

The content is not a .npy or .npz file, or is malformed.

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. NumSharp cannot unpickle at all, so this only selects the error message — and, per NumPy, 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

EndOfStreamException

The file is empty.

FormatException

The content is not a .npy or .npz file, or is malformed.

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.

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

EndOfStreamException

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.

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, string, string, object, int, int[], bool, int, int?, string)

Load data from a sequence of lines (each string is one or more newline-separated lines).

public static NDArray loadtxt(IEnumerable<string> lines, DType dtype = null, string comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, int? max_rows = null, string quotechar = null)

Parameters

lines IEnumerable<string>
dtype DType

Element type of the result (default double).

comments string

String marking the start of a comment (rest of the line ignored); a multi-character string is stripped from each line. null disables comments.

delimiter string

Column separator. null (default) splits on runs of whitespace; otherwise a single character.

converters object

Per-field parser(s): a Func<T, TResult> applied to every column, or an IDictionary<TKey, TValue> mapping a column index to a parser. null uses the dtype's parser.

skiprows int

Skip this many leading lines (including comments/blanks).

usecols int[]

Which columns to read (0-based, negatives count from the end). null reads all.

unpack bool

If true, transpose the result so columns can be unpacked as separate arrays.

ndmin int

Minimum dimensions of the result (0, 1 or 2); otherwise size-1 axes are squeezed.

max_rows int?

Read at most this many data rows after skiprows (blank/comment lines don't count).

quotechar string

Quote character; delimiters and comments inside a quoted field are literal. null disables quoting.

Returns

NDArray

Remarks

loadtxt(Stream, DType, string, string, object, int, int[], bool, int, string, int?, string)

Load data from an open text Stream (read from the current position; left open).

public static NDArray loadtxt(Stream stream, DType dtype = null, string 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
dtype DType

Element type of the result (default double).

comments string

String marking the start of a comment (rest of the line ignored); a multi-character string is stripped from each line. null disables comments.

delimiter string

Column separator. null (default) splits on runs of whitespace; otherwise a single character.

converters object

Per-field parser(s): a Func<T, TResult> applied to every column, or an IDictionary<TKey, TValue> mapping a column index to a parser. null uses the dtype's parser.

skiprows int

Skip this many leading lines (including comments/blanks).

usecols int[]

Which columns to read (0-based, negatives count from the end). null reads all.

unpack bool

If true, transpose the result so columns can be unpacked as separate arrays.

ndmin int

Minimum dimensions of the result (0, 1 or 2); otherwise size-1 axes are squeezed.

encoding string

Text encoding used to decode the file (default UTF-8).

max_rows int?

Read at most this many data rows after skiprows (blank/comment lines don't count).

quotechar string

Quote character; delimiters and comments inside a quoted field are literal. null disables quoting.

Returns

NDArray

Remarks

loadtxt(TextReader, DType, string, string, object, int, int[], bool, int, int?, string)

Load data from an open TextReader (left open).

public static NDArray loadtxt(TextReader reader, DType dtype = null, string comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, int? max_rows = null, string quotechar = null)

Parameters

reader TextReader
dtype DType

Element type of the result (default double).

comments string

String marking the start of a comment (rest of the line ignored); a multi-character string is stripped from each line. null disables comments.

delimiter string

Column separator. null (default) splits on runs of whitespace; otherwise a single character.

converters object

Per-field parser(s): a Func<T, TResult> applied to every column, or an IDictionary<TKey, TValue> mapping a column index to a parser. null uses the dtype's parser.

skiprows int

Skip this many leading lines (including comments/blanks).

usecols int[]

Which columns to read (0-based, negatives count from the end). null reads all.

unpack bool

If true, transpose the result so columns can be unpacked as separate arrays.

ndmin int

Minimum dimensions of the result (0, 1 or 2); otherwise size-1 axes are squeezed.

max_rows int?

Read at most this many data rows after skiprows (blank/comment lines don't count).

quotechar string

Quote character; delimiters and comments inside a quoted field are literal. null disables quoting.

Returns

NDArray

Remarks

loadtxt(string, DType, string, string, object, int, int[], bool, int, string, int?, string)

Load data from a text file into a 1-D or 2-D array.

public static NDArray loadtxt(string fname, DType dtype = null, string 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; a .gz name is transparently decompressed.

dtype DType

Element type of the result (default double).

comments string

String marking the start of a comment (rest of the line ignored); a multi-character string is stripped from each line. null disables comments.

delimiter string

Column separator. null (default) splits on runs of whitespace; otherwise a single character.

converters object

Per-field parser(s): a Func<T, TResult> applied to every column, or an IDictionary<TKey, TValue> mapping a column index to a parser. null uses the dtype's parser.

skiprows int

Skip this many leading lines (including comments/blanks).

usecols int[]

Which columns to read (0-based, negatives count from the end). null reads all.

unpack bool

If true, transpose the result so columns can be unpacked as separate arrays.

ndmin int

Minimum dimensions of the result (0, 1 or 2); otherwise size-1 axes are squeezed.

encoding string

Text encoding used to decode the file (default UTF-8).

max_rows int?

Read at most this many data rows after skiprows (blank/comment lines don't count).

quotechar string

Quote character; delimiters and comments inside a quoted field are literal. null disables quoting.

Returns

NDArray

Remarks

log(NDArray)

Natural logarithm, element-wise. The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e.

public static NDArray log(NDArray x)

Parameters

x NDArray

Input value.

Returns

NDArray

The natural logarithm of x, element-wise. This is a scalar if x is a scalar.

Remarks

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

Remarks

log10(NDArray)

Return the base 10 logarithm of the input array, element-wise.

public static NDArray log10(NDArray x)

Parameters

x NDArray

Input value.

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

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
where NDArray
dtype DType

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

log1p(NDArray)

Return the natural logarithm of one plus the input array, element-wise.
Calculates log(1 + x).

public static NDArray log1p(NDArray x)

Parameters

x NDArray

Input value.

Returns

NDArray

Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.

Remarks

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
where NDArray
dtype DType

Returns

NDArray

Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.

Remarks

log2(NDArray)

Base-2 logarithm of x.

public static NDArray log2(NDArray x)

Parameters

x NDArray

Input value.

Returns

NDArray

Base-2 logarithm of x. This is a scalar if x is a scalar.

Remarks

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
where NDArray
dtype DType

Returns

NDArray

Base-2 logarithm of x. This is a scalar if x is a scalar.

Remarks

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

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,NPTypeCode?), 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

logical_and(NDArray, NDArray)

Compute the truth value of x1 AND x2 element-wise.

public static NDArray<bool> logical_and(NDArray x1, NDArray x2)

Parameters

x1 NDArray

Input array.

x2 NDArray

Input array.

Returns

NDArray<bool>

Boolean result of the logical AND operation applied to the elements of x1 and x2; the shape is determined by broadcasting.

Remarks

logical_not(NDArray)

Compute the truth value of NOT x element-wise.

public static NDArray<bool> logical_not(NDArray x)

Parameters

x NDArray

Logical NOT is applied to the elements of x.

Returns

NDArray<bool>

Boolean result with the same shape as x.

Remarks

logical_or(NDArray, NDArray)

Compute the truth value of x1 OR x2 element-wise.

public static NDArray<bool> logical_or(NDArray x1, NDArray x2)

Parameters

x1 NDArray

Input array.

x2 NDArray

Input array.

Returns

NDArray<bool>

Boolean result of the logical OR operation applied to the elements of x1 and x2; the shape is determined by broadcasting.

Remarks

logical_xor(NDArray, NDArray)

Compute the truth value of x1 XOR x2 element-wise.

public static NDArray<bool> logical_xor(NDArray x1, NDArray x2)

Parameters

x1 NDArray

Input array.

x2 NDArray

Input array.

Returns

NDArray<bool>

Boolean result of the logical XOR operation applied to the elements of x1 and x2; the shape is determined by broadcasting.

Remarks

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

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

Returns

NDArray

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 the rarer genuine loop-dimension mismatch raises copyto's broadcast ValueError whose wording differs from NumPy's leaked iterator text (the same latitude the siblings take).

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.

Remarks

Exceptions

ArgumentException

If x has fewer than 2 dimensions.

matvec(NDArray, NDArray, NDArray, int[][], int?, bool, DType)

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)

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

Returns

NDArray

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) it does not conjugate — the transformation, not the inner product, is what this computes.

NumPy's remaining ufunc keywords (casting, order, subok, signature) are not modelled anywhere in NumSharp's ufunc surface and are absent here too. See vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType).

max(NDArray, int?, bool, DType)

Return the maximum of an array or maximum along an axis.

public static NDArray max(NDArray a, int? axis = null, bool keepdims = false, DType dtype = null)

Parameters

a NDArray
axis int?

Axis or axes along which to operate.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

maximum(NDArray, NDArray, DType)

Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

public static NDArray maximum(NDArray x1, NDArray x2, DType dtype = null)

Parameters

x1 NDArray

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

x2 NDArray

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

dtype DType

Loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.

Returns

NDArray

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

maximum(NDArray, NDArray, NDArray)

Element-wise maximum of array elements (NaN-propagating), writing into @out.

public static NDArray maximum(NDArray x1, NDArray x2, NDArray @out)

Parameters

x1 NDArray
x2 NDArray
out NDArray

Returns

NDArray

maximum_sctype(NPTypeCode)

Return the scalar type of highest precision of the same kind as the input.

public static DType maximum_sctype(NPTypeCode t)

Parameters

t NPTypeCode

The input scalar type.

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/stable/reference/generated/numpy.maximum_sctype.html

Uses NPTypeHierarchy for consistent type categorization across all typing functions.

mean(NDArray)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public static NDArray mean(NDArray a)

Parameters

a NDArray

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

Remarks

mean(NDArray, bool)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public static NDArray mean(NDArray a, bool keepdims)

Parameters

a NDArray

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

Remarks

mean(NDArray, int)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public static NDArray mean(NDArray a, int axis)

Parameters

a NDArray

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

axis int

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

Remarks

mean(NDArray, int, DType, bool)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public static NDArray mean(NDArray a, int axis, DType dtype, bool keepdims = false)

Parameters

a NDArray

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

axis int

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

dtype DType

Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

Remarks

mean(NDArray, int, bool)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public static NDArray mean(NDArray a, int axis, bool keepdims)

Parameters

a NDArray

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

axis int

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

median(NDArray, int[], NDArray, bool, bool)

public static NDArray median(NDArray a, int[] axis, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)

Parameters

a NDArray
axis int[]
out NDArray
overwrite_input bool
keepdims bool

Returns

NDArray

median(NDArray, int?, NDArray, bool, bool)

Compute the median along the specified axis. For an even-sized slice the median is the mean of the two central values; for an odd-sized slice it is the single central value. Equivalent to np.quantile(a, 0.5) for our purposes, which matches NumPy's contract.

public static NDArray median(NDArray a, int? axis = null, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)

Parameters

a NDArray
axis int?
out NDArray
overwrite_input bool
keepdims bool

Returns

NDArray

Remarks

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.

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

min(NDArray, int?, bool, DType)

Return the minimum of an array or minimum along an axis.

public static NDArray min(NDArray a, int? axis = null, bool keepdims = false, DType dtype = null)

Parameters

a NDArray

Input data.

axis int?

Axis or axes along which to operate.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

min_scalar_type(object)

For scalar value, returns the data type with the smallest size and smallest scalar kind which can hold its value.

public static DType min_scalar_type(object value)

Parameters

value object

The scalar value to check.

Returns

DType

The minimum dtype that can represent the value.

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

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.min_scalar_type.html

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

minimum(NDArray, NDArray, DType)

Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

public static NDArray minimum(NDArray x1, NDArray x2, DType dtype = null)

Parameters

x1 NDArray

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

x2 NDArray

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

dtype DType

Loop dtype (NumPy ufunc dtype=): the comparison runs at this precision.

Returns

NDArray

The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

minimum(NDArray, NDArray, NDArray)

Element-wise minimum of array elements (NaN-propagating), writing into @out.

public static NDArray minimum(NDArray x1, NDArray x2, NDArray @out)

Parameters

x1 NDArray
x2 NDArray
out NDArray

Returns

NDArray

mintypecode(char[], string, char)

Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in typechars(or if typechars is an array, then its dtype.char).

public static char mintypecode(char[] typechars, string typeset = "GDFgdf", char @default = 'd')

Parameters

typechars char[]
typeset string

The set of characters that the returned character is chosen from. The default set is ‘GDFgdf’.

default char

The default character, this is returned if none of the characters in typechars matches a character in typeset.

Returns

char

The character representing the minimum-size type that was found.

mintypecode(string, string, char)

Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in typechars(or if typechars is an array, then its dtype.char).

public static char mintypecode(string typechars, string typeset = "GDFgdf", char @default = 'd')

Parameters

typechars string

every character represents a type. see char

typeset string

The set of characters that the returned character is chosen from. The default set is ‘GDFgdf’.

default char

The default character, this is returned if none of the characters in typechars matches a character in typeset.

Returns

char

The character representing the minimum-size type that was found.

mod(NDArray, NDArray, NDArray, NDArray, DType)

public static NDArray mod(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

mod(NDArray, float)

public static NDArray mod(NDArray x1, float x2)

Parameters

x1 NDArray
x2 float

Returns

NDArray

modf(NDArray, DType)

Return the fractional and integral parts of an array, element-wise. The fractional and integral parts are negative if the given number is negative.

public static (NDArray Fractional, NDArray Intergral) modf(NDArray x, DType dtype = null)

Parameters

x NDArray

Input array.

dtype DType

The dtype the returned ndarray should be of, only non integer values are supported.

Returns

(NDArray Lhs, NDArray Rhs)

Fractional part of x. This is a scalar if x is a scalar.

Remarks

moveaxis(NDArray, int, int)

Move axes of an array to new positions. Other axes remain in their original order.

public static NDArray moveaxis(NDArray a, int source, int destination)

Parameters

a NDArray

The array whose axes should be reordered.

source int

Original positions of the axes to move. These must be unique (distinct).

destination int

Destination positions for each of the original axes. These must also be unique (distinct).

Returns

NDArray

Array with moved axes.

Remarks

moveaxis(NDArray, int, int[])

Move axes of an array to new positions. Other axes remain in their original order.

public static NDArray moveaxis(NDArray a, int source, int[] destination)

Parameters

a NDArray

The array whose axes should be reordered.

source int

Original positions of the axes to move. These must be unique (distinct).

destination int[]

Destination positions for each of the original axes. These must also be unique (distinct).

Returns

NDArray

Array with moved axes.

Remarks

moveaxis(NDArray, int[], int)

Move axes of an array to new positions. Other axes remain in their original order.

public static NDArray moveaxis(NDArray a, int[] source, int destination)

Parameters

a NDArray

The array whose axes should be reordered.

source int[]

Original positions of the axes to move. These must be unique (distinct).

destination int

Destination positions for each of the original axes. These must also be unique (distinct).

Returns

NDArray

Array with moved axes.

Remarks

moveaxis(NDArray, int[], int[])

Move axes of an array to new positions. Other axes remain in their original order.

public static NDArray moveaxis(NDArray a, int[] source, int[] destination)

Parameters

a NDArray

The array whose axes should be reordered.

source int[]

Original positions of the axes to move. These must be unique (distinct).

destination int[]

Destination positions for each of the original axes. These must also be unique (distinct).

Returns

NDArray

Array with moved axes.

Remarks

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

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) 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 scalar (int/float/bool) or an array_like (NDArray or a C# array) broadcast position-wise. null (default) fills NaN with 0.0.

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.

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.

nanargmax(NDArray, int?, 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, int? axis = null, NDArray @out = null, bool keepdims = false)

Parameters

a NDArray

Input data.

axis int?

Axis along which to operate. If null, the flattened input is used.

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

Exceptions

ValueError

All-NaN slice encountered.

AxisError

Axis out of bounds (reports the original axis, like NumPy).

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.

nanargmin(NDArray, int?, 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, int? axis = null, NDArray @out = null, bool keepdims = false)

Parameters

a NDArray

Input data.

axis int?

Axis along which to operate. If null, the flattened input is used.

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

Exceptions

ValueError

All-NaN slice encountered.

AxisError

Axis out of bounds (reports the original axis, like NumPy).

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

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

nanmax(NDArray, int?, bool)

Return maximum of an array or maximum along an axis, ignoring any NaNs.

public static NDArray nanmax(NDArray a, int? axis = null, bool keepdims = false)

Parameters

a NDArray

Array containing numbers whose maximum is desired. If a is not an array, a conversion is attempted.

axis int?

Axis or axes along which the maximum is computed. The default is to compute the maximum of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

A new array containing the maximum. If all values are NaN, returns NaN.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.nanmax.html Only applicable to float and double arrays. For integer arrays, this is equivalent to np.amax (no NaN values possible).

nanmean(NDArray, int?, bool)

Compute the arithmetic mean along the specified axis, ignoring NaNs. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public static NDArray nanmean(NDArray a, int? axis = null, bool keepdims = false)

Parameters

a NDArray

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

axis int?

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

A new array containing the mean values, with NaN values ignored. If all values along an axis are NaN, returns NaN for that slice.

Remarks

nanmedian(NDArray, int[], NDArray, bool, bool)

public static NDArray nanmedian(NDArray a, int[] axis, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)

Parameters

a NDArray
axis int[]
out NDArray
overwrite_input bool
keepdims bool

Returns

NDArray

nanmedian(NDArray, int?, NDArray, bool, bool)

Compute the median along the specified axis, ignoring NaNs. Equivalent to np.nanquantile(a, 0.5). A slice that is entirely NaN (or empty) yields NaN, matching NumPy's "All-NaN slice" behaviour.

public static NDArray nanmedian(NDArray a, int? axis = null, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)

Parameters

a NDArray
axis int?
out NDArray
overwrite_input bool
keepdims bool

Returns

NDArray

Remarks

nanmin(NDArray, int?, bool)

Return minimum of an array or minimum along an axis, ignoring any NaNs.

public static NDArray nanmin(NDArray a, int? axis = null, bool keepdims = false)

Parameters

a NDArray

Array containing numbers whose minimum is desired. If a is not an array, a conversion is attempted.

axis int?

Axis or axes along which the minimum is computed. The default is to compute the minimum of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

A new array containing the minimum. If all values are NaN, returns NaN.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html Only applicable to float and double arrays. For integer arrays, this is equivalent to np.amin (no NaN values possible).

nanpercentile(NDArray, NDArray, int?, NDArray, bool, string, bool)

public static NDArray nanpercentile(NDArray a, NDArray q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q NDArray
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

nanpercentile(NDArray, double, int[], NDArray, bool, string, bool)

public static NDArray nanpercentile(NDArray a, double q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double
axis int[]
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

nanpercentile(NDArray, double, int?, NDArray, bool, string, bool)

Compute the q-th percentile of the data along the specified axis, ignoring NaNs. q must be in [0, 100]. Equivalent to np.nanquantile(a, q/100). A slice that is entirely NaN (or empty) yields NaN.

public static NDArray nanpercentile(NDArray a, double q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

Remarks

nanpercentile(NDArray, double[], int[], NDArray, bool, string, bool)

public static NDArray nanpercentile(NDArray a, double[] q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double[]
axis int[]
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

nanpercentile(NDArray, double[], int?, NDArray, bool, string, bool)

public static NDArray nanpercentile(NDArray a, double[] q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double[]
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

nanprod(NDArray, int?, bool)

Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones.

public static NDArray nanprod(NDArray a, int? axis = null, bool keepdims = false)

Parameters

a NDArray

Array containing numbers whose product is desired. If a is not an array, a conversion is attempted.

axis int?

Axis or axes along which the product is computed. The default is to compute the product of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

A new array containing the product, with NaN values treated as one.

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

nanquantile(NDArray, NDArray, int?, NDArray, bool, string, bool)

NDArray-q overload — accepts a 0-D or 1-D NDArray of quantile values. Higher-rank q is rejected (NumPy raises "q must be a scalar or 1d").

public static NDArray nanquantile(NDArray a, NDArray q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q NDArray
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

nanquantile(NDArray, double, int[], NDArray, bool, string, bool)

public static NDArray nanquantile(NDArray a, double q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double
axis int[]
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

nanquantile(NDArray, double, int?, NDArray, bool, string, bool)

Compute the q-th quantile of the data along the specified axis, ignoring NaNs. q must be in the range [0, 1]. A slice that is entirely NaN (or empty) yields NaN, matching NumPy's "All-NaN slice" behaviour.

public static NDArray nanquantile(NDArray a, double q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

Remarks

nanquantile(NDArray, double[], int[], NDArray, bool, string, bool)

public static NDArray nanquantile(NDArray a, double[] q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double[]
axis int[]
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

nanquantile(NDArray, double[], int?, NDArray, bool, string, bool)

public static NDArray nanquantile(NDArray a, double[] q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double[]
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

nanstd(NDArray, int?, bool, int)

Compute the standard deviation along the specified axis, while ignoring NaNs. Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

public static NDArray nanstd(NDArray a, int? axis = null, bool keepdims = false, int ddof = 0)

Parameters

a NDArray

Calculate the standard deviation of the non-NaN values.

axis int?

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

ddof int

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.

Returns

NDArray

A new array containing the standard deviation. If all values along an axis are NaN, returns NaN for that slice.

Remarks

nansum(NDArray, int?, bool)

Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.

public static NDArray nansum(NDArray a, int? axis = null, bool keepdims = false)

Parameters

a NDArray

Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.

axis int?

Axis or axes along which the sum is computed. The default is to compute the sum of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

A new array containing the sum, with NaN values treated as zero.

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

nanvar(NDArray, int?, bool, int)

Compute the variance along the specified axis, while ignoring NaNs. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

public static NDArray nanvar(NDArray a, int? axis = null, bool keepdims = false, int ddof = 0)

Parameters

a NDArray

Array containing numbers whose variance is desired.

axis int?

Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

ddof int

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.

Returns

NDArray

A new array containing the variance. If all values along an axis are NaN, returns NaN for that slice.

Remarks

ndarray(Shape, DType, Array, char)

Create an array.

public static NDArray ndarray(Shape shape, DType dtype = null, Array buffer = null, char order = 'F')

Parameters

shape Shape

Shape of the array.

dtype DType

Data type. Default is float32.

buffer Array

Optional buffer to use for data. If null, allocates new memory filled with zeros.

order char

Memory order. Note: Only C-order is supported, F-order parameter is accepted but ignored.

Returns

NDArray

New NDArray with the specified shape and dtype.

Remarks

This function creates an NDArray directly without going through TensorEngine. Memory allocation is not backend-specific - all backends use the same unmanaged memory.

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.

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.

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.

buffersize long

Buffer size to use when buffering is enabled; 0 selects the default.

Returns

np.NDIterator

Remarks

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 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[][]

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.

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.

buffersize long

Buffer size to use when buffering is enabled; 0 selects the default.

Returns

np.NDIterator

Remarks

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[], NPTypeCode[], 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

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[]

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.nested_iters.html

Parity: the multi_index path — the documented primary use — is bit-exact with NumPy 2.4.2 across single/multiple operands, any axis order, and any nesting depth (coordinates AND values pair identically). One KNOWN divergence: WITHOUT multi_index, the pure value-stream TRAVERSAL ORDER can differ, because NumSharp's underlying np.NDIterator currently reorders op_axes iteration by memory (F-like) regardless of the order argument, where NumPy follows order (C/F/K). This is a pre-existing NDIter op_axes limitation, not a property of the nesting itself; track multi_index for order parity.

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[]

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.nested_iters.html

Parity: the multi_index path — the documented primary use — is bit-exact with NumPy 2.4.2 across single/multiple operands, any axis order, and any nesting depth (coordinates AND values pair identically). One KNOWN divergence: WITHOUT multi_index, the pure value-stream TRAVERSAL ORDER can differ, because NumSharp's underlying np.NDIterator currently reorders op_axes iteration by memory (F-like) regardless of the order argument, where NumPy follows order (C/F/K). This is a pre-existing NDIter op_axes limitation, not a property of the nesting itself; track multi_index for order parity.

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

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

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)

Return a new array of given shape and type, filled with ones.

public static NDArray ones(Shape shape)

Parameters

shape Shape

Shape of the new array.

Returns

NDArray

Remarks

ones(Shape, DType, string)

Return a new array of given shape and type, filled with ones.

public static NDArray ones(Shape shape, DType dtype, string device = null)

Parameters

shape Shape

Shape of the new array.

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 (uint8) all convert implicitly. Default (null) is float64 / double.

device string

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

Returns

NDArray

Remarks

ones(Shape, char, DType)

Return a new array of ones with a specified memory layout — the port of NumPy's np.ones(shape, dtype, order='C') order parameter (mirrors empty(Shape, char, DType)).

public static NDArray ones(Shape shape, char order, DType dtype = null)

Parameters

shape Shape

Shape of the new array.

order char

Memory layout: 'C' (row-major), 'F' (column-major), 'A'/'K' (default to 'C' with no source).

dtype DType

Desired dtype (a Type, NPTypeCode, dtype string or DType — all convert implicitly). Default is float64 / double.

Returns

NDArray

Array of ones in the requested layout (the fill is order-independent, so only the flags differ).

Remarks

ones(int)

Return a new array of given shape and type, filled with ones.

public static NDArray ones(int shape)

Parameters

shape int

Returns

NDArray

Remarks

ones(int[])

Return a new array of given shape and type, filled with ones.

public static NDArray ones(int[] shape)

Parameters

shape int[]

Shape of the new array.

Returns

NDArray

Remarks

ones(int[], DType)

Return a new array of given shape and type, filled with ones.

public static NDArray ones(int[] shape, DType dtype)

Parameters

shape int[]

Shape of the new array.

dtype DType

The desired data-type for the array, e.g., uint8. Default is float64 / double.

Returns

NDArray

Remarks

ones(long[])

Return a new array of given shape and type, filled with ones.

public static NDArray ones(long[] shape)

Parameters

shape long[]

Shape of the new array.

Returns

NDArray

Remarks

ones_like(NDArray, DType, char, string)

Return an array of ones with the same shape and type as a given array.

public static NDArray ones_like(NDArray a, DType dtype, char order, string device = null)

Parameters

a NDArray

Array of ones with the same shape and type as a.

dtype DType

Overrides the data type of the result.

order char

Memory layout: 'C', 'F', 'A' or 'K' (default, preserves source layout).

device string

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

Returns

NDArray

Array of ones with the same shape and type as nd.

Remarks

ones_like(NDArray, DType, string)

Return an array of ones with the same shape and type as a given array.

public static NDArray ones_like(NDArray a, DType dtype = null, string device = null)

Parameters

a NDArray

Array of ones with the same shape and type as a.

dtype DType

Overrides the data type of the result.

device string

Returns

NDArray

Array of zeros with the same shape and type as nd.

Remarks

ones<T>(int[])

Return a new array of given shape and type, filled with ones.

public static NDArray ones<T>(int[] shape) where T : unmanaged

Parameters

shape int[]

Shape of the new array.

Returns

NDArray

Type Parameters

T

The desired data-type for the array, e.g., uint8. Default is float64 / double.

Remarks

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

pad(NDArray, IDictionary<int, object>, PadFunc, object)

public static NDArray pad(NDArray array, IDictionary<int, object> pad_width, np.PadFunc mode, object kwargs = null)

Parameters

array NDArray
pad_width IDictionary<int, object>
mode np.PadFunc
kwargs object

Returns

NDArray

pad(NDArray, IDictionary<int, object>, string, object, object, object, string)

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
pad_width IDictionary<int, object>
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)

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

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

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

percentile(NDArray, NDArray, int?, NDArray, bool, string, bool)

public static NDArray percentile(NDArray a, NDArray q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q NDArray
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

percentile(NDArray, double, int[], NDArray, bool, string, bool)

public static NDArray percentile(NDArray a, double q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double
axis int[]
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

percentile(NDArray, double, int?, NDArray, bool, string, bool)

Compute the q-th percentile of the data along the specified axis. q must be in [0, 100]. Equivalent to np.quantile(a, q/100).

public static NDArray percentile(NDArray a, double q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

Remarks

percentile(NDArray, double[], int[], NDArray, bool, string, bool)

public static NDArray percentile(NDArray a, double[] q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double[]
axis int[]
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

percentile(NDArray, double[], int?, NDArray, bool, string, bool)

public static NDArray percentile(NDArray a, double[] q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double[]
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

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.

Remarks

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. Cast to arr's dtype and cycled to fill the True positions. Must be non-empty when at least one mask entry is True (NumPy parity).

Remarks

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

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.

m int

Order of differentiation (default 1).

Returns

NDArray

A new polynomial representing the derivative.

Remarks

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.

Remarks

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

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
a2 NDArray

Returns

NDArray

Remarks

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.

Remarks

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

power(NDArray, NDArray)

First array elements raised to powers from second array, element-wise. Supports broadcasting between x1 and x2.

public static NDArray power(NDArray x1, NDArray x2)

Parameters

x1 NDArray

The bases.

x2 NDArray

The exponents (array).

Returns

NDArray

The bases in x1 raised to the exponents in x2.

Remarks

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

Remarks

power(NDArray, object)

First array elements raised to powers from second array, element-wise.

public static NDArray 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. This is a scalar NDArray if both x1 and x2 are scalars.

Remarks

power(in NDArray, in NDArray)

First array elements raised to powers from second array, element-wise. Supports broadcasting between x1 and x2.

public static NDArray power(in NDArray x1, in NDArray x2)

Parameters

x1 NDArray

The bases.

x2 NDArray

The exponents (array).

Returns

NDArray

The bases in x1 raised to the exponents in x2.

Remarks

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, bool)

Return the product of array elements over a given axis.

public static NDArray prod(NDArray a, int? axis = null, DType dtype = null, bool keepdims = false)

Parameters

a NDArray

Input data.

axis int?

Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.

dtype DType

The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

Returns

NDArray

An array shaped as a but with the specified axis removed.

Remarks

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.

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.

promote_types(NPTypeCode, NPTypeCode)

Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 can be safely cast.

public static DType promote_types(NPTypeCode type1, NPTypeCode type2)

Parameters

type1 NPTypeCode

First data type.

type2 NPTypeCode

Second data type.

Returns

DType

The promoted type.

Examples

np.promote_types(NPTypeCode.Int32, NPTypeCode.Single)  // Double
np.promote_types(NPTypeCode.Int16, NPTypeCode.UInt16)  // Int32
np.promote_types(NPTypeCode.Int8, NPTypeCode.Int8)     // Int8

Remarks

The NPTypeCode spelling of promote_types(DType, DType): the same NEP 42 engine, whose answers for the storage-backed types ARE NumSharp's frozen promotion table.

promote_types(Type, Type)

Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 can be safely cast.

public static DType promote_types(Type type1, Type type2)

Parameters

type1 Type

First CLR type.

type2 Type

Second CLR type.

Returns

DType

The promoted type as NPTypeCode.

promote_types<T1, T2>()

Returns the data type with the smallest size and smallest scalar kind to which both T1 and T2 can be safely cast.

public static DType promote_types<T1, T2>() where T1 : struct where T2 : struct

Returns

DType

The promoted type as NPTypeCode.

Type Parameters

T1

First type.

T2

Second type.

Examples

np.promote_types<int, long>()      // Int64
np.promote_types<float, double>()  // Double

ptp(NDArray, int[], NDArray, bool)

public static NDArray ptp(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false)

Parameters

a NDArray
axis int[]
out NDArray
keepdims bool

Returns

NDArray

ptp(NDArray, int?, NDArray, bool)

Range of values (maximum - minimum) along an axis. Equivalent to np.amax(a, axis) - np.amin(a, axis); 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, int? axis = null, NDArray @out = null, bool keepdims = false)

Parameters

a NDArray
axis int?
out NDArray
keepdims bool

Returns

NDArray

Remarks

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[indices] = values with cyclic broadcasting of values.

public static void put(NDArray a, NDArray indices, NDArray values, string mode = "raise")

Parameters

a NDArray

Target array (modified in place).

indices NDArray

Integer array of flat indices (cast to int64 internally). Indexing is into the C-order flattening of a.

values NDArray

Values to write. Cast to a's dtype. Cycles modulo its size — shorter than indices is fine.

mode string

Boundary mode: "raise" (default), "wrap", or "clip".

Remarks

put(NDArray, long, object, string)

Scalar-index, scalar-value convenience overload.

public static void put(NDArray a, long index, object value, string mode = "raise")

Parameters

a NDArray
index long
value object
mode string

quantile(NDArray, NDArray, int?, NDArray, bool, string, bool)

NDArray-q overload — accepts a 0-D or 1-D NDArray of quantile values. Higher-rank q is rejected (NumPy raises "q must be a scalar or 1d").

public static NDArray quantile(NDArray a, NDArray q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q NDArray
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

quantile(NDArray, double, int[], NDArray, bool, string, bool)

Compute the q-th quantile, reducing along multiple axes.

public static NDArray quantile(NDArray a, double q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double
axis int[]
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

quantile(NDArray, double, int?, NDArray, bool, string, bool)

Compute the q-th quantile of the data along the specified axis. q must be in the range [0, 1].

public static NDArray quantile(NDArray a, double q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

Remarks

quantile(NDArray, double[], int[], NDArray, bool, string, bool)

public static NDArray quantile(NDArray a, double[] q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double[]
axis int[]
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

quantile(NDArray, double[], int?, NDArray, bool, string, bool)

Compute the q-th quantiles of the data along the specified axis. Each value in q must be in [0, 1]. Result's first axis is q.

public static NDArray quantile(NDArray a, double[] q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)

Parameters

a NDArray
q double[]
axis int?
out NDArray
overwrite_input bool
method string
keepdims bool

Returns

NDArray

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

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

ravel(NDArray)

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned

public static NDArray ravel(NDArray a)

Parameters

a NDArray

Input array. The elements in a are read in the order specified by order, and packed as a 1-D array.

Returns

NDArray

Remarks

ravel(NDArray, char)

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned

public static NDArray ravel(NDArray a, char order)

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' - memory order.

Returns

NDArray

Remarks

ravel_multi_index(NDArray[], int[], string, char)

Converts a tuple of coordinate arrays into an array of flat indices, applying boundary modes per axis. Inverse of unravel_index(NDArray, int[], char).

public static NDArray<long> ravel_multi_index(NDArray[] multi_index, int[] dims, string mode = "raise", char order = 'C')

Parameters

multi_index NDArray[]

Tuple of integer arrays, one per dimension. All arrays must share the same shape, which becomes the shape of the result.

dims int[]

Shape of the array the indices are unravelling into.

mode string

Boundary mode: "raise" (default — throw on OOB), "wrap" (modulo with sign correction), or "clip" (saturate). Applied to every axis.

order char

'C' (row-major, default) or 'F' (column-major). Selects the stride ordering used to fold coordinates into a flat index.

Returns

NDArray<long>

1-D (or shape-preserving) NDArray<TDType> of long.

Remarks

ravel_multi_index(NDArray[], int[], string[], char)

Per-axis mode overload. modes length must match dims length.

public static NDArray<long> ravel_multi_index(NDArray[] multi_index, int[] dims, string[] modes, char order = 'C')

Parameters

multi_index NDArray[]
dims int[]
modes string[]
order char

Returns

NDArray<long>

ravel_multi_index(long[], int[], 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[] coords, int[] dims, string mode = "raise", char order = 'C')

Parameters

coords long[]
dims int[]
mode string
order char

Returns

long

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

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

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.

Remarks

repeat(NDArray, int, int?)

Repeat each element of an array after themselves.

public static NDArray repeat(NDArray a, int repeats, int? axis = null)

Parameters

a NDArray

Input array.

repeats int

The number of repetitions for each element.

axis int?

Axis along which to repeat values. null (NumPy None) flattens the input and returns a flat array.

Returns

NDArray

Output array which has the same shape as a, except along axis.

Remarks

repeat(NDArray, long, int?)

Repeat each element of an array after themselves.

public static NDArray repeat(NDArray a, long repeats, int? axis = null)

Parameters

a NDArray

Input array.

repeats long

The number of repetitions for each element.

axis int?

Axis along which to repeat values. null (NumPy None) flattens the input.

Returns

NDArray

Output array.

Remarks

repeat<T>(T, int)

Repeat a scalar value.

public static NDArray repeat<T>(T a, int repeats) where T : unmanaged

Parameters

a T

Input scalar.

repeats int

The number of repetitions.

Returns

NDArray

A 1-D array with the scalar repeated.

Type Parameters

T

Remarks

repeat<T>(T, long)

Repeat a scalar value.

public static NDArray repeat<T>(T a, long repeats) where T : unmanaged

Parameters

a T

Input scalar.

repeats long

The number of repetitions.

Returns

NDArray

A 1-D array with the scalar repeated.

Type Parameters

T

Remarks

require(NDArray, DType, string)

Single-string requirements overload. Mirrors NumPy's iteration semantics exactly: a string is iterated CHARACTER BY CHARACTER, so "F" is the Fortran flag, "CF" requests both C and F (and raises), and a multi-character alias such as "F_CONTIGUOUS" is NOT one token — its '_' is unrecognized and raises. Pass a single-element array (new[]{ "F_CONTIGUOUS" }) to use the full alias.

public static NDArray require(NDArray a, DType dtype, string requirements)

Parameters

a NDArray
dtype DType
requirements string

Returns

NDArray

Remarks

require(NDArray, DType, string[], NDArray)

Return an ndarray of the provided type that satisfies requirements.

public static NDArray require(NDArray a, DType dtype = null, string[] 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 string[]

The requirements list. Each element is one of (case-insensitive, with 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 array instead of a subclass (no-op in NumSharp: no ndarray subclasses)
like NDArray

Reference array for NumPy's array-function dispatch — accepted for signature parity but has no observable effect in NumSharp (no array-subclass dispatch).

Returns

NDArray

Array with the specified requirements and dtype if given. A copy is made only when needed.

Remarks

Port of NumPy 2.x numpy.require. With no requirements this is exactly asanyarray(a, dtype). Otherwise it resolves an order ('A' by default, or 'C'/'F' when requested), routes through asarray(NDArray, DType, char, bool?, NDArray, string), then makes a single copy (in the resolved order) if any of the remaining ALIGNED / WRITEABLE / OWNDATA flags is not already satisfied. ALIGNED is always satisfied in NumSharp (managed allocations), so only WRITEABLE (false for broadcast views) and OWNDATA (false for views) can force a copy. 'ENSUREARRAY' is accepted and stripped but has no effect — NumSharp has no ndarray subclasses to demote. https://numpy.org/doc/stable/reference/generated/numpy.require.html

Exceptions

ValueError

If both 'C' and 'F' order are requested, or a requirement string is not understood.

reshape(NDArray, Shape)

Gives a new shape to an array without changing its data.

public static NDArray reshape(NDArray nd, Shape shape)

Parameters

nd NDArray

Array to be reshaped.

shape Shape

The new shape should be compatible with the original shape.

Returns

NDArray

original nd reshaped without copying.

Remarks

reshape(NDArray, ref Shape)

Gives a new shape to an array without changing its data.

public static NDArray reshape(NDArray nd, ref Shape shape)

Parameters

nd NDArray

Array to be reshaped.

shape Shape

The new shape should be compatible with the original shape.

Returns

NDArray

original nd reshaped without copying.

Remarks

reshape(NDArray, int[])

Gives a new shape to an array without changing its data.

public static NDArray reshape(NDArray nd, int[] shape)

Parameters

nd NDArray

Array to be reshaped.

shape int[]

The new shape should be compatible with the original shape.

Returns

NDArray

original nd reshaped without copying.

Remarks

reshape(NDArray, long[])

Gives a new shape to an array without changing its data.

public static NDArray reshape(NDArray nd, long[] shape)

Parameters

nd NDArray

Array to be reshaped.

shape long[]

The new shape should be compatible with the original shape.

Returns

NDArray

original nd reshaped without copying.

Remarks

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.

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.

Returns

DType

The result descriptor.

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.

arr2 NDArray

Second array.

Returns

DType

The result type from combining the array dtypes.

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.

Returns

DType

The result type from combining the array dtypes.

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.

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.

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 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[]

Returns

DType

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.

type2 Type

Second CLR type.

Returns

DType

The result type from combining the inputs.

right_shift(NDArray, NDArray)

Shift the bits of an integer to the right.

public static NDArray right_shift(NDArray x1, NDArray x2)

Parameters

x1 NDArray

Input array (integer types only).

x2 NDArray

Number of bits to shift (integer types only).

Returns

NDArray

Array with bits shifted right.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.right_shift.html

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

right_shift(NDArray, object)

Shift the bits of an integer to the right by a scalar or array-like amount.

public static NDArray right_shift(NDArray x1, object x2)

Parameters

x1 NDArray

Input array (integer types only).

x2 object

Number of bits to shift (scalar or array-like).

Returns

NDArray

Array with bits shifted right.

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

roll(NDArray, int, int?)

Roll array elements along a given axis.

Elements that roll beyond the last position are re-introduced at the first.

public static NDArray roll(NDArray a, int shift, int? axis = null)

Parameters

a NDArray

Input array.

shift int

The number of places by which elements are shifted.

axis int?

Axis along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.

Returns

NDArray

Output array, with the same shape as a.

Remarks

Matches NumPy's algorithm: empty_like + slice-copy pairs. https://numpy.org/doc/stable/reference/generated/numpy.roll.html

roll(NDArray, long, int?)

Roll array elements along a given axis.

Elements that roll beyond the last position are re-introduced at the first.

public static NDArray roll(NDArray a, long shift, int? axis = null)

Parameters

a NDArray

Input array.

shift long

The number of places by which elements are shifted.

axis int?

Axis along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.

Returns

NDArray

Output array, with the same shape as a.

Remarks

Matches NumPy's algorithm: empty_like + slice-copy pairs. https://numpy.org/doc/stable/reference/generated/numpy.roll.html

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

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.

Remarks

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.

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

round_(NDArray, int, NDArray, DType)

Evenly round to the given number of decimals.

public static NDArray round_(NDArray x, int decimals = 0, NDArray @out = null, DType dtype = null)

Parameters

x NDArray

Input array.

decimals int

Number of decimal places to round to (default 0). Half is rounded to even.

out NDArray

A location into which the result is stored; must be the correct shape, returned as-is. np.round/np.around are FUNCTIONS, not ufuncs, so they accept out= only — there is no where=/dtype= ufunc kwarg (probed 2.4.2). The dtype here is NumSharp's dtype-target convenience, taken as a keyword.

dtype DType

The DType the returned ndarray should be of (a C# Type, an NPTypeCode or a NumPy dtype string all convert implicitly). null preserves NumPy's round dtype rules (integer inputs are an identity copy).

Returns

NDArray

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.

Remarks

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

Present for NumPy parity; see save(string, NDArray, bool).

Remarks

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

Present for NumPy parity. NumSharp has no object dtype, so nothing can reach the pickle path and this never changes the outcome.

Remarks

The file is byte-for-byte what NumPy 2.4.2's own np.save writes for the same array. https://numpy.org/doc/stable/reference/generated/numpy.save.html

Exceptions

NotSupportedException

The dtype has no NumPy equivalent — Decimal.

save(string, Array, bool)

Save an array to a .npy file, converting arr with np.asanyarray(in object, Type) 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

Present for NumPy parity; see save(string, NDArray, bool).

Exceptions

FormatException

The version is not one of (1,0), (2,0) or (3,0).

savetxt(Stream, NDArray, string, string, string, string, string, string, string)

Write a 1-D or 2-D array as text to an open stream. 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
X NDArray
fmt string
delimiter string
newline string
header string
footer string
comments string
encoding string

Remarks

savetxt(Stream, NDArray, string[], string, string, string, string, string, string)

Write a 1-D or 2-D array as text to an open 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
X NDArray
fmt string[]
delimiter string
newline string
header string
footer string
comments string
encoding string

Remarks

savetxt(TextWriter, NDArray, string, string, string, string, string, string)

Write a 1-D or 2-D array as text to an open TextWriter. The writer is left open and owns its encoding/newline policy; rows are separated by newline verbatim.

public static void savetxt(TextWriter writer, NDArray X, string fmt = "%.18e", string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ")

Parameters

writer TextWriter
X NDArray
fmt string
delimiter string
newline string
header string
footer string
comments string

Remarks

savetxt(TextWriter, NDArray, 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 = "# ")

Parameters

writer TextWriter
X NDArray
fmt string[]
delimiter string
newline string
header string
footer string
comments string

Remarks

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. If it ends in .gz the file is written gzip-compressed, as NumPy does.

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

Output encoding; null (default) and bytes/utf-8 use UTF-8 with no BOM, latin1 uses Latin-1.

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

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

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

Present for NumPy parity; a no-op — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).

Remarks

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

Present for NumPy parity (its signature is savez(file, *args, allow_pickle=True, **kwds)). NumSharp has no object dtype, so nothing can reach the pickle path and this never changes the outcome.

Remarks

Exceptions

ArgumentException

A name in kwds collides with a generated arr_N.

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

Present for NumPy parity; a no-op — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).

Remarks

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

Present for NumPy parity; a no-op — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).

Remarks

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.

public static char sctype2char(NPTypeCode sctype)

Parameters

sctype NPTypeCode

A scalar type.

Returns

char

The character code for the type.

Examples

np.sctype2char(NPTypeCode.Int32)   // 'i'
np.sctype2char(NPTypeCode.Double)  // 'd'

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.sctype2char.html

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

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
v double
side string
sorter NDArray

Returns

long

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

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 on the calling thread) 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 thread-local (matching NumPy 2.x's context-local buffer state) and persists until changed again on the same thread; it never affects other threads. Buffering is purely a performance/chunking knob, so changing it leaves every computed result bit-for-bit identical.

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.

Remarks

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

sign(NDArray, NDArray, NDArray, DType)

public static NDArray sign(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)

Parameters

x NDArray
out NDArray
where NDArray
dtype DType

Returns

NDArray

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

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

size(NDArray, int?)

Return the number of elements along a given axis.

public static long size(NDArray a, int? axis = null)

Parameters

a NDArray

Input data.

axis int?

Axis along which the elements are counted. By default, give the total number of elements.

Returns

long

Number of elements along the specified axis.

Remarks

sort(NDArray, int?, string)

Return a sorted copy of an array, sorted along axis (default last; null flattens first). NumPy np.sort.

public static NDArray sort(NDArray a, int? axis = -1, string kind = null)

Parameters

a NDArray

Array to sort.

axis int?

Axis to sort along. -1 = last axis. null = sort the flattened array.

kind string

Sort algorithm name (NumPy compatibility). All kinds produce identical sorted output; the kernel is a stable LSD radix (numeric) or BCL introsort (Half/Complex/Decimal).

Returns

NDArray

Remarks

NaN floats sort to the end; complex sorts lexicographically (real then imaginary), any-NaN-part last — matching NumPy 2.4.2.

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

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.

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.

Remarks

Exceptions

ArgumentException

If indices_or_sections is an integer and does not result in equal division.

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
indices int[]
axis int

Returns

NDArray[]

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
indices long[]
axis int

Returns

NDArray[]

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

square(NDArray)

Return the element-wise square of the input.

public static NDArray square(NDArray x)

Parameters

x NDArray

Input data.

Returns

NDArray

Element-wise x*x, of the same shape and dtype as x. Returns scalar if x is a scalar.

Remarks

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

Remarks

squeeze(NDArray)

Remove single-dimensional entries from the shape of an array.

public static NDArray squeeze(NDArray a)

Parameters

a NDArray

Input data.

Returns

NDArray

The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.

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). https://numpy.org/doc/stable/reference/generated/numpy.squeeze.html

squeeze(NDArray, int)

Remove single-dimensional entries from the shape of an array.

public static NDArray squeeze(NDArray a, int axis)

Parameters

a NDArray

Input data.

axis int

Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised.

Returns

NDArray

The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.

Remarks

Exceptions

IncorrectShapeException

If axis is not None, and an axis being squeezed is not of length 1

squeeze(Shape)

Remove single-dimensional entries from a shape.

public static Shape squeeze(Shape shape)

Parameters

shape Shape

Input shape.

Returns

Shape

The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.

Remarks

stack(NDArray[], int)

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)

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.

Returns

NDArray

The stacked array has one more dimension than the input arrays.

Remarks

std(NDArray, bool, int?, DType)

Compute the standard deviation of the flattened array. Returns the standard deviation, a measure of the spread of a distribution, of the array elements.

public static NDArray std(NDArray a, bool keepdims = false, int? ddof = null, DType dtype = null)

Parameters

a NDArray

Calculate the standard deviation of these values.

keepdims bool

If true, the reduced axes are left in the result as size-one dimensions.

ddof int?

Delta Degrees of Freedom. The divisor used is N - ddof (default 0).

dtype DType

The DType the computation/result should use (a C# Type, an NPTypeCode or a NumPy dtype string all convert implicitly).

Returns

NDArray

A new array containing the std values, or a reference to the output array.

Remarks

std(NDArray, int, bool, int?, DType)

Compute the standard deviation along the specified axis.

public static NDArray std(NDArray a, int axis, bool keepdims = false, int? ddof = null, DType dtype = null)

Parameters

a NDArray

Calculate the standard deviation of these values.

axis int

Axis along which the standard deviation is computed.

keepdims bool

If true, the reduced axes are left in the result as size-one dimensions.

ddof int?

Delta Degrees of Freedom. The divisor used is N - ddof (default 0).

dtype DType

The DType the computation/result should use (implicit from Type / NPTypeCode / NumPy dtype string).

Returns

NDArray

A new array containing the std values, or a reference to the output array.

Remarks

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

sum(NDArray)

Sum of all array elements.

public static NDArray sum(NDArray a)

Parameters

a NDArray

Elements to sum.

Returns

NDArray

A scalar (0-d) sum of the flattened array.

Remarks

sum(NDArray, DType)

Sum of array elements in a given dtype (the accumulator/return type).

public static NDArray sum(NDArray a, DType dtype)

Parameters

a NDArray

Elements to sum.

dtype DType

The DType of the accumulator/return (a C# Type, an NPTypeCode or a NumPy dtype string all convert implicitly). By default NumPy's NEP50 accumulator rules apply (e.g. int32 → int64).

Returns

NDArray

Remarks

sum(NDArray, bool)

Sum of all array elements, optionally keeping the reduced dimensions.

public static NDArray sum(NDArray a, bool keepdims)

Parameters

a NDArray

Elements to sum.

keepdims bool

If true, the reduced axes are left in the result as size-one dimensions.

Returns

NDArray

Remarks

sum(NDArray, int)

Sum of array elements over the given axis.

public static NDArray sum(NDArray a, int axis)

Parameters

a NDArray

Elements to sum.

axis int

Axis along which a sum is performed (negative counts from the last axis).

Returns

NDArray

Remarks

sum(NDArray, int?, DType)

Sum of array elements over the given axis in a given dtype.

public static NDArray sum(NDArray a, int? axis, DType dtype)

Parameters

a NDArray

Elements to sum.

axis int?

Axis along which a sum is performed (null sums the flattened array).

dtype DType

The DType of the accumulator/return (implicit from Type / NPTypeCode / NumPy dtype string).

Returns

NDArray

Remarks

sum(NDArray, int?, bool)

Sum of array elements over the given axis, optionally keeping the reduced dimensions.

public static NDArray sum(NDArray a, int? axis, bool keepdims)

Parameters

a NDArray

Elements to sum.

axis int?

Axis along which a sum is performed (null sums the flattened array).

keepdims bool

If true, the reduced axes are left in the result as size-one dimensions.

Returns

NDArray

Remarks

sum(NDArray, int?, bool, DType)

Sum of array elements over the given axis in a given dtype, optionally keeping the reduced dimensions.

public static NDArray sum(NDArray a, int? axis, bool keepdims, DType dtype)

Parameters

a NDArray

Elements to sum.

axis int?

Axis along which a sum is performed (null sums the flattened array).

keepdims bool

If true, the reduced axes are left in the result as size-one dimensions.

dtype DType

The DType of the accumulator/return (implicit from Type / NPTypeCode / NumPy dtype string).

Returns

NDArray

Remarks

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

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.

axis int?

Axis along which to take. null (default) flattens a and treats indices as flat indices.

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

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

Remarks

take(NDArray, long, int?, NDArray, string)

Scalar convenience overload — take a single element by flat index.

public static NDArray take(NDArray a, long index, int? axis = null, NDArray @out = null, string mode = "raise")

Parameters

a NDArray
index long
axis int?
out NDArray
mode string

Returns

NDArray

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

Remarks

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

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

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
b NDArray
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

Remarks

tensordot(NDArray, NDArray, int[], int[])

Tensor contraction pairing axesA of a with axesB of b, element by element — NumPy's axes=(list, list) spelling.

public static NDArray tensordot(NDArray a, NDArray b, int[] axesA, int[] axesB)

Parameters

a NDArray
b NDArray
axesA int[]
axesB int[]

Returns

NDArray

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.

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
b NDArray
axes (int AxisA, int AxisB)

Returns

NDArray

tile(NDArray, params int[])

Construct an array by repeating A the number of times given by 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, params int[] reps)

Parameters

A NDArray

The input array.

reps int[]

The number of repetitions of A along each axis. Each rep must be non-negative.

Returns

NDArray

The tiled output array. Expanded outputs are C-contiguous; all-one reps produce a keep-order copy. Dtype matches A.

Remarks

Exceptions

ArgumentNullException

If A or reps is null.

ArgumentException

If any element of reps is negative.

tile(NDArray, long[])

Construct an array by repeating A the number of times given by reps.

Long overload — see tile(NDArray, params int[]).

public static NDArray tile(NDArray A, long[] reps)

Parameters

A NDArray
reps long[]

Returns

NDArray

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 integer dtypes narrower than long promote to long (NEP50 / matches NumPy's "default platform integer" rule). Bool input promotes to long.

out NDArray

Optional output array. Shape must equal the natural reduction output; values are copied with unsafe casting and the method returns out itself.

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.

transpose(NDArray, int[])

Permute the dimensions of an array.

public static NDArray transpose(NDArray a, int[] premute = null)

Parameters

a NDArray

Input array.

premute int[]

By default, reverse the dimensions, otherwise permute the axes according to the values given.

Returns

NDArray

a with its axes permuted. A view is returned whenever possible.

Remarks

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

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.

Remarks

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.

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.

Remarks

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>[]

Remarks

Exceptions

ArgumentException

input array must be 2-d (NumPy ValueError, verbatim).

trim_zeros(NDArray, string, int[])

Remove values which are zero along all other dimensions, trimming the given sequence of axes. trim is required on this overload so it does not collide with the single-axis primary above on calls like trim_zeros(filt) / trim_zeros(filt, "f").

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[]

If null, filt is cropped to the smallest bounding box that still contains all non-zero values. If axes are specified, filt is sliced in those dimensions only, on the sides selected by trim. An empty array of axes 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.

Remarks

Exceptions

ArgumentException

If trim contains unexpected characters, or an axis is repeated.

AxisOutOfRangeException

If an axis is out of bounds for filt.

trim_zeros(NDArray, string, int?)

Remove values along a dimension which are zero along all other dimensions. Mirrors NumPy's numpy.trim_zeros(filt, trim='fb', axis=None) exactly: axis is a single axis, or null for the whole-array bounding box. Pass an int[] to trim several axes.

public static NDArray trim_zeros(NDArray filt, string trim = "fb", int? axis = null)

Parameters

filt NDArray

Input array.

trim string

'f' trims from the front, 'b' from the back; "fb" (default) trims both. Case-insensitive.

axis int?

The single dimension to trim; null trims the whole-array bounding box.

Returns

NDArray

Remarks

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.

Remarks

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.

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.

Remarks

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>[]

Remarks

Exceptions

ArgumentException

input array must be 2-d (NumPy ValueError, verbatim).

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

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

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

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.

Remarks

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

Remarks

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

Remarks

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.

Remarks

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

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.

unravel_index(NDArray, int[], char)

Converts a flat index or array of flat indices into a tuple of coordinate arrays. Inverse of ravel_multi_index(NDArray[], int[], string, char).

public static NDArray<long>[] unravel_index(NDArray indices, int[] shape, char order = 'C')

Parameters

indices NDArray

An integer array whose elements are indices into the flattened version of an array of dimensions shape. Cast to int64 internally.

shape int[]

The shape of the array to use for unraveling.

order char

'C' (row-major, default) or 'F' (column-major) — selects the extraction order for the coordinate tuple.

Returns

NDArray<long>[]

A tuple of shape.Length NDArrays. Each output array has the same shape as indices. Element dtype is always Int64.

Remarks

Exceptions

ArgumentException

shape is empty, has non-positive dims, or the dims' product overflows int64.

ArgumentOutOfRangeException

Any index in indices is < 0 or

= product of shape.

unravel_index(long, int[], char)

Scalar convenience overload — converts a single flat index into a coord array. Equivalent to unravel_index(NDArray.Scalar(index), shape, order) but returns a long[] directly without NDArray wrapping.

public static long[] unravel_index(long index, int[] shape, char order = 'C')

Parameters

index long
shape int[]
order char

Returns

long[]

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.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.unstack.html
unstack serves as the reverse operation of stack(NDArray[], int): 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.

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

var(NDArray, bool, int?, DType)

Compute the variance of the flattened array. Returns the variance, a measure of the spread of a distribution, of the array elements.

public static NDArray var(NDArray a, bool keepdims = false, int? ddof = null, DType dtype = null)

Parameters

a NDArray

Calculate the variance of these values.

keepdims bool

If true, the reduced axes are left in the result as size-one dimensions.

ddof int?

Delta Degrees of Freedom. The divisor used is N - ddof (default 0).

dtype DType

The DType the computation/result should use (a C# Type, an NPTypeCode or a NumPy dtype string all convert implicitly).

Returns

NDArray

A new array containing the variance values, or a reference to the output array.

Remarks

var(NDArray, int, bool, int?, DType)

Compute the variance along the specified axis.

public static NDArray var(NDArray a, int axis, bool keepdims = false, int? ddof = null, DType dtype = null)

Parameters

a NDArray

Calculate the variance of these values.

axis int

Axis along which the variance is computed.

keepdims bool

If true, the reduced axes are left in the result as size-one dimensions.

ddof int?

Delta Degrees of Freedom. The divisor used is N - ddof (default 0).

dtype DType

The DType the computation/result should use (implicit from Type / NPTypeCode / NumPy dtype string).

Returns

NDArray

A new array containing the variance values, or a reference to the output array.

Remarks

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.

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)

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)

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.

Returns

NDArray

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.vecdot.html

Unlike sum(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 remaining ufunc keywords — casting, order, subok and signature — are not modelled anywhere in NumSharp's ufunc surface and so are absent here too rather than accepted and ignored. signature is what dtype already does; subok concerns ndarray subclasses, which NumSharp does not have.

vecmat(NDArray, NDArray, NDArray, int[][], int?, bool, DType)

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)

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.

Returns

NDArray

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) 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)'s convention.

NumPy's remaining ufunc keywords (casting, order, subok, signature) are not modelled anywhere in NumSharp's ufunc surface and are absent here too. See vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType).

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.

Remarks

Equivalent to split with axis=0. Array must have ndim >= 2. https://numpy.org/doc/stable/reference/generated/numpy.vsplit.html

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.

Remarks

Equivalent to split with axis=0. Array must have ndim >= 2. https://numpy.org/doc/stable/reference/generated/numpy.vsplit.html

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.

Remarks

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)

Return a new double array of given shape, filled with zeros.

public static NDArray zeros(Shape shape)

Parameters

shape Shape

Shape of the new array,

Returns

NDArray

Array of zeros with the given shape, dtype.

Remarks

zeros(Shape, DType, string)

Return a new double array of given shape, filled with zeros.

public static NDArray zeros(Shape shape, DType dtype, string device = null)

Parameters

shape Shape

Shape of the new array,

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 (uint8) all convert implicitly. Default (null) is float64 / double.

device string

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

Returns

NDArray

Array of zeros with the given shape, dtype.

Remarks

zeros(Shape, char, DType)

Return a new array of zeros with a specified memory layout — the port of NumPy's np.zeros(shape, dtype, order='C') order parameter (mirrors empty(Shape, char, DType)).

public static NDArray zeros(Shape shape, char order, DType dtype = null)

Parameters

shape Shape

Shape of the new array.

order char

Memory layout: 'C' (row-major), 'F' (column-major), 'A'/'K' (default to 'C' with no source).

dtype DType

Desired dtype (a Type, NPTypeCode, dtype string or DType — all convert implicitly). Default is float64 / double.

Returns

NDArray

Array of zeros in the requested layout (the fill is order-independent, so only the flags differ).

Remarks

zeros(int)

Return a new double array of given shape, filled with zeros.

public static NDArray zeros(int shape)

Parameters

shape int

Returns

NDArray

Array of zeros with the given shape, dtype.

Remarks

zeros(int[])

Return a new double array of given shape, filled with zeros.

public static NDArray zeros(int[] shape)

Parameters

shape int[]

Shape of the new array,

Returns

NDArray

Array of zeros with the given shape, dtype.

Remarks

zeros(long[])

Return a new double array of given shape, filled with zeros.

public static NDArray zeros(long[] shape)

Parameters

shape long[]

Shape of the new array,

Returns

NDArray

Array of zeros with the given shape, dtype.

Remarks

zeros_like(NDArray, DType, char, string)

Return an array of zeros with the same shape and type as a given array.

public static NDArray zeros_like(NDArray a, DType dtype, char order, 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.

order char

Memory layout: 'C', 'F', 'A' or 'K' (default, preserves source layout).

device string

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

Returns

NDArray

Array of zeros with the same shape and type as nd.

Remarks

zeros_like(NDArray, DType, string)

Return an array of zeros with the same shape and type as a given array.

public static NDArray zeros_like(NDArray a, DType dtype = 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.

device string

Returns

NDArray

Array of zeros with the same shape and type as nd.

Remarks

zeros<T>(int[])

Return a new double array of given shape, filled with zeros.

public static NDArray zeros<T>(int[] shape) where T : unmanaged

Parameters

shape int[]

Shape of the new array,

Returns

NDArray

Array of zeros with the given shape, type T.

Type Parameters

T

Remarks

zeros<T>(long[])

Return a new double array of given shape, filled with zeros.

public static NDArray zeros<T>(long[] shape) where T : unmanaged

Parameters

shape long[]

Shape of the new array,

Returns

NDArray

Array of zeros with the given shape, type T.

Type Parameters

T

Remarks