Class DefaultEngine
Default Tensor Engine implemented in pure micro-optimized C#.
public class DefaultEngine : TensorEngine
- Inheritance
-
DefaultEngine
- Inherited Members
Remarks
DefaultEngine is the pure C# implementation of TensorEngine. It uses DirectILKernelGenerator internally for SIMD-optimized kernels. All computation on NDArray should go through TensorEngine methods. Its results bind the instance that computed them (NewArray(DType, Shape, bool)), so a subclass assigned to an array, or to Default, also computes the operations on those results.
Methods
ACos(NDArray, DType, NDArray, NDArray)
Element-wise inverse cosine (arccos) using IL-generated kernels.
public override NDArray ACos(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
ACosh(NDArray, DType, NDArray, NDArray)
Element-wise inverse hyperbolic cosine (arccosh) using IL-generated kernels.
public override NDArray ACosh(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
AMax(NDArray, int?, DType, bool)
public override NDArray AMax(NDArray nd, int? axis = null, DType dtype = null, bool keepdims = false)
Parameters
Returns
AMin(NDArray, int?, DType, bool)
public override NDArray AMin(NDArray nd, int? axis = null, DType dtype = null, bool keepdims = false)
Parameters
Returns
ASin(NDArray, DType, NDArray, NDArray)
Element-wise inverse sine (arcsin) using IL-generated kernels.
public override NDArray ASin(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
ASinh(NDArray, DType, NDArray, NDArray)
Element-wise inverse hyperbolic sine (arcsinh) using IL-generated kernels.
public override NDArray ASinh(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
ATan(NDArray, DType, NDArray, NDArray)
Element-wise inverse tangent (arctan) using IL-generated kernels.
public override NDArray ATan(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
ATan2(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise arc tangent of y/x choosing the quadrant correctly. NumPy: arctan2(y, x) returns the angle in radians between the positive x-axis and the point (x, y), with correct quadrant determination.
public override NDArray ATan2(NDArray y, NDArray x, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
yNDArrayy-coordinates
xNDArrayx-coordinates. If y.shape != x.shape, they must be broadcastable.
dtypeDTypeoutNDArraywhereNDArray
Returns
- NDArray
Array of angles in radians, range [-pi, pi]
ATanh(NDArray, DType, NDArray, NDArray)
Element-wise inverse hyperbolic tangent (arctanh) using IL-generated kernels.
public override NDArray ATanh(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Abs(NDArray, DType, NDArray, NDArray)
Element-wise absolute value using IL-generated kernels. NumPy behavior: preserves input dtype (unlike sin/cos which promote to float). Exception: np.abs(complex) returns float64 (the magnitude).
public override NDArray Abs(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Add(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise addition using IL-generated kernels. Supports all 144 type combinations with automatic type promotion.
public override NDArray Add(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe first operand.
rhsNDArrayThe second operand.
dtypeDTypeThe
dtype=loop request, or null. A string request over numbers (or a number and a string of another class) formats the numbers as text and concatenates (AddUnderStringRequest(DType, NDArray, NDArray, NDArray, NDArray)).outNDArrayThe
out=operand, or null.whereNDArrayThe
where=mask, or null.
Returns
- NDArray
The sums (or concatenations), or
outwhen one is given.
Exceptions
- TypeError
A sized string request, two string classes, a concatenation wider than 2^31 - 1 bytes, or no loop for the operands (NumPy's texts).
- ArgumentException
A cast the loop refuses, a non-bool mask, or operands that do not broadcast (NumPy's texts).
- ValueError
A read-only
out.
All(NDArray)
Test whether all array elements evaluate to True (non-zero). Supports all 12 dtypes with SIMD optimization for contiguous arrays.
public override bool All(NDArray nd)
Parameters
ndNDArrayInput array
Returns
- bool
True if all elements are non-zero
Remarks
NDAnchoredAttribute: the flat reduction reads nd's raw address (the SIMD
scan, or NDIter.ReduceBool), and np.all(a) / ndarray.all() reach it through this method,
which opens no scope; the weaver roots nd until it returns, so a caller's temporary
(np.all(a > 0)) cannot be collected under the scan.
Exceptions
- SystemError
A
Uarray holding a unit above U+10FFFF: NumPy'slogical_and.reducereads a string's truth through the bool cast, which raises there. (A string is otherwise True when non-empty.)
All(NDArray, int[], NDArray, bool, NDArray)
NumPy's np.all with a tuple axis, the whole call: the reduce prologue (every axis,
then a repeat), the text truth route, the masked reduction and the out= store.
public override NDArray All(NDArray a, int[] axis, NDArray @out, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayThe array (any dtype, any layout).
axisint[]The reduced axes (an empty tuple reduces nothing).
outNDArrayNumPy's
out=, or null for a fresh result.keepdimsboolWhether the reduced axes stay with length one.
whereNDArrayNumPy's
where=bool mask, or null.
Returns
- NDArray
outitself when given; otherwise the fresh bool array, read-only when 0-d.
Remarks
New in 0.80.0 (the np-layer dtype plan, P1b).
Exceptions
- ArgumentNullException
aoraxisis null.- ValueError
A read-only or misshapen
out, a mask with more axes thana, or an axis that appears twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array, oroutdoes not have the result's shape.- AxisError
An axis is out of range.
- IncorrectShapeException
whereoroutdoes not broadcast againsta.- SystemError
A
Uarray holding a unit above U+10FFFF.
All(NDArray, int[], bool)
np.all over a tuple of axes: every axis checked, then a repeat refused, then the boolean reduction
(an EMPTY tuple reduces nothing and returns the truth values in the input's shape).
public override NDArray<bool> All(NDArray nd, int[] axis, bool keepdims = false)
Parameters
ndNDArrayThe array (any dtype, any layout).
axisint[]The reduced axes (negative values count from the end).
keepdimsboolWhether the reduced axes stay with length one.
Returns
Remarks
Abstract since 0.80.0 (the np-layer dtype plan's P1b): DefaultEngine had it as its own
member, which the public np.all reached by a type test.
Exceptions
- ArgumentNullException
ndoraxisis null.- AxisError
An axis is out of range (the first one, in the tuple's order).
- ValueError
An axis appears twice (
duplicate value in 'axis').- SystemError
A
Uarray holding a unit above U+10FFFF.
All(NDArray, int?, NDArray, bool, NDArray)
NumPy's np.all(a, axis, out, keepdims, *, where), the whole call: logical_and.reduce(a, axis, bool,
out, keepdims=keepdims, where=where) — the reduce prologue in NumPy's order, the text truth route, the masked
reduction and the out= store.
public override NDArray All(NDArray a, int? axis, NDArray @out, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayThe array (any dtype, any layout).
axisint?The reduced axis, or null for every axis (NumPy's
axis=None).outNDArrayNumPy's
out=: an array of the result's shape and any dtype that receives the bool result with unsafe casting, or null for a fresh result.keepdimsboolWhether the reduced axes stay with length one.
whereNDArrayNumPy's
where=: a bool mask that broadcasts toa's shape (masked-off elements count as True, the identity), or null for no mask.
Returns
- NDArray
outitself when given; otherwise a fresh bool array, read-only when 0-d (NumPy's scalar).
Remarks
The engine owns NumPy's whole call, dtype decisions included (the np-layer dtype plan, P1b): the public
np.all only calls this (the declaration below dispatches a subclass operand to its method). New in
0.80.0. A bare null axis is
ambiguous with the tuple member below: pass a typed int?.
Exceptions
- ArgumentNullException
ais null.- ValueError
outis read-only (output array is read-only, checked first), has the wrong rank, or cannot hold the result; orwherehas more axes thanaor would make it stretch (NumPy's reduction-iterator texts).- ArgumentException
whereis not a bool array (NumPy's TypeError text: the mask must cast to bool under thesaferule); oroutdoes not have the result's shape.- AxisError
axisis out of range.- IncorrectShapeException
whereoroutdoes not broadcast againsta.- SystemError
A
Uarray holding a unit above U+10FFFF.
All(NDArray, int?, bool)
np.all along one axis, or over every axis when axis is null: the boolean reduction
without out= or where=, a fresh array the caller may wrap as NumPy's scalar.
public override NDArray<bool> All(NDArray nd, int? axis, bool keepdims = false)
Parameters
ndNDArrayThe array (any dtype, any layout).
axisint?The reduced axis (negative counts from the end; a 0-d array accepts 0 and -1), or null for every axis.
keepdimsboolWhether the reduced axes stay with length one.
Returns
- NDArray<bool>
The bool result, laid out as NumPy's reduction allocates it. Over every axis it is a fresh, writeable owner (a 0-d array without
keepdims); the publicnp.alloverloads decide whether a 0-d result becomes NumPy's read-only scalar.
Remarks
keepdims and the null axis were added to the contract in 0.80.0 (the np-layer dtype
plan's P1b, decision D2: widened in place; the member took one int axis before).
Exceptions
- ArgumentNullException
ndis null.- AxisError
axisis out of range.- SystemError
A
Uarray holding a unit above U+10FFFF.
AllClose(NDArray, NDArray, double, double, bool)
Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers.The
relative difference (rtol * abs(b)) and the absolute difference
atol are added together to compare against the absolute difference
between a and b.
If either array contains one or more NaNs, False is returned.
Infs are treated as equal if they are in the same place and of the same
sign in both arrays.
public override bool AllClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
Parameters
aNDArraybNDArrayInput array to compare with a.
rtoldoubleThe relative tolerance parameter(see Notes)
atoldoubleThe absolute tolerance parameter(see Notes)
equal_nanboolWhether to compare NaN's as equal. If True, NaN's in
awill be considered equal to NaN's inbin the output array.
Returns
Angle(NDArray, bool)
DefaultEngine's Angle(NDArray, bool), NumPy's np.angle body:
arctan2(z.imag, z.real) for a complex input and arctan2(0, z) (a weak Python int 0) for a real
one, scaled by 180 / pi in place when deg is set. The facade applies the
numpy.matrix rule first and calls this for everything else.
public override NDArray Angle(NDArray z, bool deg = false)
Parameters
zNDArrayThe input (any dtype; text is refused as NumPy's
arctan2refuses it).degboolReturn degrees instead of radians.
Returns
- NDArray
The phase angle: float64 for complex128, else NumPy's tier of
arctan2(0, z)(AngleRealTier(NPTypeCode)).
Remarks
Moved from np.angle by the np-layer dtype plan's P0 pilot, statement for statement; the facade's
np.arctan2 / np.multiply calls became the engine members they forward to (the operands here are
never matrices or chararrays: the facade decides the class first, and the lanes, casts and scalars below are
plain arrays). The plan's phase PE (E1) made it this override of a TensorEngine member; it was an
internal static of DefaultEngine.
The real path computes arctan2 in float64 and casts to the tier: its only values are +0, pi and
NaN, so the cast is exact and matches NumPy computing at the tier (verified against NumPy 2.4.2).
Exceptions
- TypeError
Text:
arctan2has no string loop (theStringDTypeno-loop text naming the weak_PyLongDType, the legacy resolver's text forS/U).
Any(NDArray)
Test whether any array element evaluates to True (non-zero). Supports all 12 dtypes with SIMD optimization for contiguous arrays.
public override bool Any(NDArray nd)
Parameters
ndNDArrayInput array
Returns
- bool
True if any element is non-zero
Remarks
NDAnchoredAttribute: the flat reduction reads nd's raw address, and
np.any(a) / ndarray.any() reach it through this method, which opens no scope; the weaver roots
nd until it returns (the twin of All(NDArray)).
Exceptions
- SystemError
A
Uarray holding a unit above U+10FFFF: NumPy'slogical_or.reducereads a string's truth through the bool cast, which raises there. (A string is otherwise True when non-empty.)
Any(NDArray, int[], NDArray, bool, NDArray)
NumPy's np.any with a tuple axis, the whole call: the reduce prologue (every axis,
then a repeat), the text truth route, the masked reduction and the out= store.
public override NDArray Any(NDArray a, int[] axis, NDArray @out, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayThe array (any dtype, any layout).
axisint[]The reduced axes (an empty tuple reduces nothing).
outNDArrayNumPy's
out=, or null for a fresh result.keepdimsboolWhether the reduced axes stay with length one.
whereNDArrayNumPy's
where=bool mask, or null.
Returns
- NDArray
outitself when given; otherwise the fresh bool array, read-only when 0-d.
Remarks
New in 0.80.0 (the np-layer dtype plan, P1b).
Exceptions
- ArgumentNullException
aoraxisis null.- ValueError
A read-only or misshapen
out, a mask with more axes thana, or an axis that appears twice (duplicate value in 'axis').- ArgumentException
whereis not a bool array, oroutdoes not have the result's shape.- AxisError
An axis is out of range.
- IncorrectShapeException
whereoroutdoes not broadcast againsta.- SystemError
A
Uarray holding a unit above U+10FFFF.
Any(NDArray, int[], bool)
np.any over a tuple of axes: every axis checked, then a repeat refused, then the boolean reduction
(an EMPTY tuple reduces nothing and returns the truth values in the input's shape).
public override NDArray<bool> Any(NDArray nd, int[] axis, bool keepdims = false)
Parameters
ndNDArrayThe array (any dtype, any layout).
axisint[]The reduced axes (negative values count from the end).
keepdimsboolWhether the reduced axes stay with length one.
Returns
Remarks
Abstract since 0.80.0 (the np-layer dtype plan's P1b): DefaultEngine had it as its own
member, which the public np.any reached by a type test.
Exceptions
- ArgumentNullException
ndoraxisis null.- AxisError
An axis is out of range (the first one, in the tuple's order).
- ValueError
An axis appears twice (
duplicate value in 'axis').- SystemError
A
Uarray holding a unit above U+10FFFF.
Any(NDArray, int?, NDArray, bool, NDArray)
NumPy's np.any(a, axis, out, keepdims, *, where), the whole call: logical_or.reduce(a, axis, bool,
out, keepdims=keepdims, where=where) — the reduce prologue in NumPy's order, the text truth route, the masked
reduction and the out= store.
public override NDArray Any(NDArray a, int? axis, NDArray @out, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayThe array (any dtype, any layout).
axisint?The reduced axis, or null for every axis (NumPy's
axis=None).outNDArrayNumPy's
out=: an array of the result's shape and any dtype that receives the bool result with unsafe casting, or null for a fresh result.keepdimsboolWhether the reduced axes stay with length one.
whereNDArrayNumPy's
where=: a bool mask that broadcasts toa's shape (masked-off elements count as False, the identity), or null for no mask.
Returns
- NDArray
outitself when given; otherwise a fresh bool array, read-only when 0-d (NumPy's scalar).
Remarks
The engine owns NumPy's whole call, dtype decisions included (the np-layer dtype plan, P1b): the public
np.any only calls this (the declaration below dispatches a subclass operand to its method). New in
0.80.0. A bare null axis is
ambiguous with the tuple member below: pass a typed int?.
Exceptions
- ArgumentNullException
ais null.- ValueError
outis read-only (output array is read-only, checked first), has the wrong rank, or cannot hold the result; orwherehas more axes thanaor would make it stretch (NumPy's reduction-iterator texts).- ArgumentException
whereis not a bool array (NumPy's TypeError text: the mask must cast to bool under thesaferule); oroutdoes not have the result's shape.- AxisError
axisis out of range.- IncorrectShapeException
whereoroutdoes not broadcast againsta.- SystemError
A
Uarray holding a unit above U+10FFFF.
Any(NDArray, int?, bool)
np.any along one axis, or over every axis when axis is null: the boolean reduction
without out= or where=, a fresh array the caller may wrap as NumPy's scalar.
public override NDArray<bool> Any(NDArray nd, int? axis, bool keepdims = false)
Parameters
ndNDArrayThe array (any dtype, any layout).
axisint?The reduced axis (negative counts from the end; a 0-d array accepts 0 and -1), or null for every axis.
keepdimsboolWhether the reduced axes stay with length one.
Returns
- NDArray<bool>
The bool result, laid out as NumPy's reduction allocates it. Over every axis it is a fresh, writeable owner (a 0-d array without
keepdims); the publicnp.anyoverloads decide whether a 0-d result becomes NumPy's read-only scalar.
Remarks
keepdims and the null axis were added to the contract in 0.80.0 (the np-layer dtype
plan's P1b, decision D2: widened in place; the member took one int axis before).
Exceptions
- ArgumentNullException
ndis null.- AxisError
axisis out of range.- SystemError
A
Uarray holding a unit above U+10FFFF.
AreBroadcastable(params NDArray[])
Checks if the given arrays can be broadcast together.
public static bool AreBroadcastable(params NDArray[] arrays)
Parameters
arraysNDArray[]
Returns
Remarks
Extracts shapes and delegates to Shape.AreBroadcastable
AreBroadcastable(params Shape[])
Checks if the given shapes can be broadcast together.
public static bool AreBroadcastable(params Shape[] shapes)
Parameters
shapesShape[]
Returns
Remarks
Delegates to Shape.AreBroadcastable
AreBroadcastable(params int[][])
Checks if the given dimension arrays can be broadcast together.
public static bool AreBroadcastable(params int[][] shapes)
Parameters
shapesint[][]
Returns
Remarks
Delegates to Shape.AreBroadcastable
ArgMax(NDArray)
public override NDArray ArgMax(NDArray a)
Parameters
aNDArray
Returns
ArgMax(NDArray, int, bool)
public override NDArray ArgMax(NDArray a, int axis, bool keepdims = false)
Parameters
Returns
ArgMin(NDArray)
public override NDArray ArgMin(NDArray a)
Parameters
aNDArray
Returns
ArgMin(NDArray, int, bool)
public override NDArray ArgMin(NDArray a, int axis, bool keepdims = false)
Parameters
Returns
ArgPartition(NDArray, object, int?, string, string)
NumPy's np.argpartition(a, kth, axis, kind, order) and ndarray.argpartition
(PyArray_ArgPartition), the whole call: the int64 indices that partition a along the
axis (see Partition(NDArray, object, int?, string, string)).
public override NDArray ArgPartition(NDArray a, object kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayThe array (only read). A 0-d array ravels to one element first, as NumPy's
PyArray_CheckAxisdoes.kthobjectNumPy's array_like of positions along the axis: a C# int, an int[], an integer index array, or any other object, converted with
np.asanyarray. A negative position counts from the end; every listed position ends where a sorted copy holds its element.axisint?The axis (negative counts from the end), or null for the flattened array.
kindstringNumPy's
kind=: only"introselect"(the default) or null.orderstringNumPy's
order=, a field name, or null: every NumSharp dtype has no fields, so any value is refused.
Returns
- NDArray
A fresh, C-contiguous int64 array of
a's shape (one-dimensional for a null axis): the element at each listed position is where a sorted copy holds it. Text answers with the default argsort (NumPy's generic introsort fallback).
Remarks
New in 0.80.0 (the np-layer dtype plan, phase PE, E5): np.argpartition and
NDArray.argpartition call this.
Exceptions
- ValueError
A
kindother than"introselect"(select kind must be 'introselect' (got 'x')) or anorder, before the array is read; a kth index array of more than one dimension (object too deep for desired array, before the axis) or of bool dtype (Booleans unacceptable as partition index); a position out of bounds (kth(=5) out of bounds (5), skipped for an empty array).- TypeError
A kth index array of a non-integer dtype (
Partition index must be integer).- AxisError
The axis is out of range.
- ArgumentNullException
kthis null, at NumPy's kth stage (after the axis: NumPy's kth=None raises its TypeError there).
ArgSort(NDArray, int?, string, object, bool?)
NumPy's np.argsort(a, axis, kind, order, stable) and ndarray.argsort (PyArray_ArgSort),
the whole call: the int64 indices that sort a along the axis.
public override NDArray ArgSort(NDArray a, int? axis = -1, string kind = null, object order = null, bool? stable = null)
Parameters
aNDArrayThe array (only read). A 0-d array ravels to one element first, as NumPy's
PyArray_CheckAxisdoes: its answer is[0], and an axis other than 0 / -1 reports dimension 1.axisint?The sorted axis (negative counts from the end), or null for the C-order flattening.
kindstringNumPy's
kind=, read from its first character (quicksort,heapsort,mergesort orstable, any case), or null for the default. It changes the answer only where NumPy's does: the stable kind's float value sort keeps every NaN's bits, and StringDType refuses the heapsort kind.orderobjectNumPy's
order=, a field name or a list of them, or null: every NumSharp dtype has no fields, so any value is refused.stablebool?NumPy's keyword-only
stable=: true asks for the stable kind; any non-null value is refused together withkind.
Returns
- NDArray
A fresh, C-contiguous int64 array of
a's shape (one-dimensional for a null axis). Ties keep their order for every numeric kind (NumSharp's numeric argsort is one stable order); text follows NumPy's introsort for the default kind.
Remarks
New in 0.80.0 (the np-layer dtype plan, phase PE, E5): np.argsort and NDArray.argsort
call this.
Exceptions
- ValueError
An unknown
kind(sort kind must be one of 'quick', 'heap', or 'stable' (got 'x')),kindtogether withstable, or anorder, all before the array is read; aStringDTypeline of two or more elements holding an NA whose NA object is neither NaN-like nor a string.- RuntimeError
A
StringDTypearray with the heapsort kind (unsupported sort kind), before the axis: NumPy resolves the argsort loop first.- AxisError
The axis is out of range.
Argwhere(NDArray)
np.argwhere — returns the (N, ndim) int64 array of coordinates of
non-zero elements, traversed in C-order. Equivalent to
np.transpose(np.nonzero(a)) with NumPy's 0-d special case
(truthy → (1,0), falsy → (0,0)), and returned as NumPy returns it: np.transpose stacks
nonzero's index arrays into a fresh (ndim, N) C-order array and hands back its transpose — an
F-contiguous VIEW (OWNDATA false, element strides (1, N)) that keeps that array alive.
Implementation: three IL-emitted kernels keyed off the element type
(GetArgwhereCountKernel(Type),
GetArgwhereFlatKernel(Type),
GetNonZeroPerDimKernel()). The runtime call
site has zero typeof(T) branches: it looks the kernels up in the
per-dtype ConcurrentDictionary<TKey, TValue>
cache and invokes them. Every loop (SIMD body, scalar tail, coord-expand
carry chain) lives inside the emitted IL.
Two-pass pre-size-then-fill: a SIMD popcount sizes the (ndim, N) array
exactly; the SIMD bit-scan writes the flat indices straight into it — its only row for
ndim==1, its LAST row for ndim>1 — and the per-dim expand kernel rewrites the rows in
place (row d = coordinate d of every element). No temporary buffer: the expand reads flat
index i before it writes column i of any row, and later steps read only flat[i+1..].
Routing:
- 0-d → NumPy's
argwhere(atleast_1d(a))[:, :0]: shape(1,0)truthy /(0,0)falsy, a view of the promoted result's buffer. - size == 0 → shape
(0, ndim), the transpose of an empty(ndim, 0)array. - Contiguous → IL count + IL scan + (ndim==1 ? direct write : in-place per-dim expand).
- Non-contiguous → materialize via
ascontiguousarraythen same path as contig.
public override NDArray Argwhere(NDArray nd)
Parameters
ndNDArrayThe array.
Returns
- NDArray
The coordinates (int64): a
(N, ndim)view of the stacked(ndim, N)array.
Remarks
BREAKING (NumPy parity): the result used to be an owning C-contiguous (N, ndim) array. It is
now F-contiguous for ndim >= 2 (row i's coordinates are N elements apart in memory), so
code that reads its raw buffer row by row must go through the strides or take
np.ascontiguousarray first; element access, slicing and every np.* call read it correctly.
Exceptions
- NotSupportedException
The IL kernels cannot be emitted for the dtype.
ArrayEqual(NDArray, NDArray, bool)
DefaultEngine's ArrayEqual(NDArray, NDArray, bool): array_equal(a1, a2, equal_nan) on the
plain views
its callers hand in (np.array_equal's facade and the member array_equal(NDArray, bool)): the
null convention, then NumPy's statements — the shape check; without equal_nan,
bool((a1 == a2).all()); with it, the same object is True, two dtypes that cannot hold NaN compare
plainly, and otherwise isnan runs on both, the NaN positions must agree and every other element must be
equal.
public override bool ArrayEqual(NDArray a1, NDArray a2, bool equal_nan = false)
Parameters
a1NDArrayThe first array, or null.
a2NDArrayThe second array, or null.
equal_nanboolNumPy's
equal_nan: NaNs at the same places count as equal.
Returns
- bool
NumPy's answer: the shapes equal and every element equal. Two nulls are equal, a null and an array are not.
Remarks
Text and StringDType run these statements as they are: == compares two strings of one class and a
StringDType operand with a StringDType or U one (NpyString_cmp: 'a\0c'
equals 'a\0b', the bytes after a NUL both share are not compared; a NaN-like NA equals nothing, itself
included; a None-like NA reads as ''), and answers all-False for any other pair with a string operand;
isnan refuses S / U text and is True at a StringDType NaN-like NA. The default
path is all(a1 == a2) deliberately WITHOUT a same-reference short-circuit: NaN ≠ NaN, so an array
holding a NaN is not equal to itself; the short-circuit is valid only under equal_nan,
where NumPy takes it. No scope: every array made here is disposed before the answer is returned.
Exceptions
- TypeError
With
equal_nan, a fixed-width string operand and two different arrays of one shape (NumPy'sisnanhas no string loop); twoStringDTypeoperands whose NA objects differ (the comparison'sCannot find a compatible null string value for null strings 'nan' and 'None').
ArrayEquiv(NDArray, NDArray)
DefaultEngine's ArrayEquiv(NDArray, NDArray): array_equiv(a1, a2) after the facade's plain
region: NumPy's multiarray.broadcast(a1, a2) check (a failure is "not equivalent"), then
bool((a1 == a2).all()) over the broadcast operands.
public override bool ArrayEquiv(NDArray a1, NDArray a2)
Parameters
Returns
- bool
True when the shapes broadcast together and every element compares equal (NaN never does). Two nulls are equivalent, a null and an array are not.
Remarks
No scope: the one comparison array is disposed before the answer is returned.
Exceptions
- TypeError
Two
StringDTypeoperands whose NA objects differ (NumPy's comparison refuses the pair).
Average(NDArray, int[], NDArray, bool, bool)
DefaultEngine's Average(NDArray, int[], NDArray, bool, bool): average(a, axis, weights, returned, keepdims) after
the facades' checks: the average and, for returned, the sum of weights in the average's
shape.
public override (NDArray avg, NDArray sumOfWeights) Average(NDArray a, int[] axis = null, NDArray weights = null, bool returned = false, bool keepdims = false)
Parameters
aNDArrayThe operand (not null): any dtype and layout; text takes NumPy's text statements.
axisint[]The axes as given (a negative axis counts from the end), or null for every axis.
weightsNDArrayThe weights, or null for the plain mean: of
a's shape, or of the reduced axes' extents in the order ofaxis.returnedboolAlso compute the sum of weights (NumPy's
returned=True); false leaves the pair's second element null.keepdimsboolKeep the reduced axes with length 1.
Returns
- (NDArray Lhs, NDArray Rhs)
The average and the sum of weights (null unless
returned): arrays the caller owns, 0-d for a reduction over every axis without keepdims.
Remarks
NumPy's parameter order (returned before the keyword-only keepdims); the body owns a
boundary scope, so only the returned arrays survive the call.
Exceptions
- AxisError
An axis out of bounds (
axis: axis 9 is out of bounds for array of dimension 2: NumPy names the argument).- ValueError
An axis that appears twice (
repeated axis in); weights not of the reduced axes' shape (axisargumentShape of weights must be consistent with shape of a along specified axis.).- DivideByZeroException
Weights that sum to zero (
Weights sum to zero, can't be normalized), or a mean without weights whose result is empty (division by zero: NumPy'sa.size / avg.size).- TypeError
Weights of another shape without an axis (
Axis must be specified when shapes of a and weights differ.); the weight sum's refusal of a text result dtype (U / S weights beside a number, a fixed-width text operand:The; U weights beside StringDType:dtypeandsignaturearguments to ufuncs only select the general DType ...Cannot pass a new user DType instance ...); a text operand without weights: the mean's add.reduce refusal.- DTypePromotionError
Weights and an operand with no common DType: StringDType beside a number or beside S.
- InvalidOperationException
Not reached: a weight sum in a text result dtype that NumPy refuses but that computed (a wiring error inside NumSharp).
Bartlett(double)
NumPy's np.bartlett(M): the triangular window of M points,
where(n <= 0, 1 + n/(M-1), 1 - n/(M-1)) over n = arange(1-M, M, 2) - zero at both ends, one at
the centre only when the count is odd.
public override NDArray Bartlett(double M)
Parameters
MdoubleThe number of points, NumPy's
_FloatLike_co: a fractional count gives NumPy's lengthlen(arange(1 - M, M, 2)); below one gives an empty array, exactly one givesones(1).
Returns
- NDArray
A new 1-D float64 array.
Remarks
NumPy writes the window in Python; DefaultEngine fuses its ufunc chain into one np.evaluate pass in
NumPy's operation order, so the values are NumPy's bit for bit (float64 add, subtract and divide are
IEEE-exact). The window has no operand to choose an engine by: np.bartlett calls the default engine's
member, so an override is reached through that engine (or called directly).
Exceptions
- ValueError
Mis NaN (arange'sarange: cannot compute length), +infinity or too large for arange to size (Maximum allowed size exceeded).- OutOfMemoryException
A finite count whose window does not fit in memory.
BatchedMatmul(NDArray, NDArray)
Stacked / batched matmul: both operands are ≥2-D (after any 1-D promotion). The trailing
two axes are the matrix dims [n,k]·[k,m]; the leading "stack" axes broadcast against
each other (NumPy treats matmul as a gufunc over those stack dims). Broadcasts ONLY the
stack dims — the matrix dims are left intact — then runs the 2-D kernel per batch element.
protected NDArray BatchedMatmul(NDArray lhs, NDArray rhs)
Parameters
Returns
Bincount(NDArray, NDArray, int)
NumPy's np.bincount(x, weights=None, minlength=0) (arr_bincount,
numpy/_core/src/multiarray/compiled_base.c), the whole call: the number of occurrences of each
non-negative integer in x, or with weights the sum of the weights at
the positions of each value. The result has max(x.max() + 1, minlength) bins.
public override NDArray Bincount(NDArray x, NDArray weights = null, int minlength = 0)
Parameters
xNDArrayA 1-D array of non-negative integers: an integer, bool or char dtype, cast to int64 (a uint64 value at or past 2^63 wraps negative and is refused, as NumPy's cast makes it).
weightsNDArrayNull, or a 1-D array of
x's length, cast to float64.minlengthintThe smallest number of bins (non-negative).
Returns
- NDArray
A new 1-D array: int64 counts without
weights, float64 sums with them. An emptyxgivesminlengthint64 zeros, whatever the weights.
Remarks
New in 0.80.0 (the np-layer dtype plan): the public np.bincount computes a numpy.matrix
operand as a plain array and calls this.
Exceptions
- ArgumentNullException
xis null.- IncorrectShapeException
x, or with values the weights, is not 1-D (NumPy'sobject of too small depth for desired array/object too deep for desired arrayValueError texts).- InvalidCastException
xis not an integer, bool or char array, or the weights are complex or text (NumPy's safe-cast TypeError text).- ValueError
In NumPy's order: a negative
minlength, a negative value, weights of another length.
BitwiseAnd(NDArray, NDArray, DType, NDArray, NDArray)
Execute bitwise AND operation.
public override NDArray BitwiseAnd(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
BitwiseCount(NDArray, DType, NDArray, NDArray)
Element-wise population count of the magnitude (np.bitwise_count): the number of 1-bits in
|x| for each element, always producing a uint8 result. INTEGER/BOOL/CHAR ONLY —
float/complex/decimal/half inputs have no loop and raise (NumPy 2.4.2 parity). Signed negatives
count the magnitude (bitwise_count(-1) == 1, not 8; bitwise_count(int8 -128) == 1).
public override NDArray BitwiseCount(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
ndNDArrayInput array (bool/byte/sbyte/int16/uint16/int32/uint32/int64/uint64/char).
dtypeDTypeOutput dtype request. Only uint8 (or null) is a valid loop; anything else raises the no-loop error.
outNDArrayOptional output (NumPy ufunc out=); the uint8 result is cast same_kind into it (e.g. an int32 out is fine).
whereNDArrayOptional bool write mask (NumPy ufunc where=).
Returns
- NDArray
A uint8 array of set-bit counts (or
outwhen supplied).
Exceptions
- TypeError
An
out/dtype input cannot cast same_kind (verbatim UFuncTypeError text).- ArgumentException
whereis a non-bool mask.- IncorrectTypeException
dtypeis given and is not uint8 (no matching loop).- TypeError
The input dtype is not integer/bool/char and cannot be coerced to a supported loop.
BitwiseOr(NDArray, NDArray, DType, NDArray, NDArray)
Execute bitwise OR operation.
public override NDArray BitwiseOr(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
BitwiseXor(NDArray, NDArray, DType, NDArray, NDArray)
Execute bitwise XOR operation.
public override NDArray BitwiseXor(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Blackman(double)
NumPy's np.blackman(M): the Blackman window of M points, the first three terms of a
cosine sum, 0.42 + 0.5cos(pin/(M-1)) + 0.08cos(2.0pi*n/(M-1)) over n = arange(1-M, M, 2).
public override NDArray Blackman(double M)
Parameters
MdoubleThe number of points, NumPy's
_FloatLike_co(the length and the guards of Bartlett(double)).
Returns
- NDArray
A new 1-D float64 array (its end points are a tiny negative number, -1.3877787807814457e-17, as in NumPy).
Remarks
DefaultEngine's fused pass keeps NumPy's evaluation order ((pi * n) / (M - 1) and
((2.0 * pi) * n) / (M - 1) round in two steps each), and float64 cos is the host CRT's, NumPy's
own on win-amd64; elsewhere a libm can differ in the last bit. np.blackman calls the default engine's
member.
Exceptions
- ValueError
Mis NaN, +infinity or too large for arange to size.- OutOfMemoryException
A finite count whose window does not fit in memory.
BooleanMask(NDArray, NDArray)
Apply a boolean mask to select elements / sub-tensors from an array.
public override NDArray BooleanMask(NDArray arr, NDArray mask)
Parameters
Returns
- NDArray
Array of shape (count_true,) + arr.shape[mask.ndim:].
BooleanMaskSet(NDArray, NDArray, NDArray)
Assign value into arr where the
boolean mask (matching a leading prefix of arr's
shape) is True. value broadcasts to the selection
shape (count_true,) + arr.shape[mask.ndim:] (NumPy semantics).
public override void BooleanMaskSet(NDArray arr, NDArray mask, NDArray value)
Parameters
Broadcast(params NDArray[])
Broadcasts multiple arrays and returns new NDArrays with broadcasted shapes.
public static NDArray[] Broadcast(params NDArray[] arrays)
Parameters
arraysNDArray[]
Returns
- NDArray[]
Remarks
Extracts shapes, delegates to Shape.Broadcast, wraps results in NDArray
Broadcast(Shape, Shape)
Broadcasts two shapes and returns the broadcasted shapes with computed strides.
public static (Shape LeftShape, Shape RightShape) Broadcast(Shape leftShape, Shape rightShape)
Parameters
Returns
Remarks
Delegates to Broadcast(Shape, Shape), but on failure raises
NumPy's ELEMENTWISE-ufunc broadcast error verbatim:
operands could not be broadcast together with shapes (2,3) (2,)
— note the trailing space and Python-tuple shape repr (NumSharp.Shape.ToPythonTuple()).
Every elementwise binary path in the engine (add/sub/mul/div/mod/power/floor_divide/
bitwise, the comparisons, arctan2, the shifts, and np.evaluate) resolves its broadcast
through THIS wrapper — an unqualified Broadcast(...) inside DefaultEngine
binds here, not to Shape.Broadcast. NumPy decides this message at the ufunc layer,
not in the shared shape math, so the message lives here at the caller boundary — exactly
as the out=/where= path does in DefaultEngine.UfuncOut.cs. np.broadcast_arrays,
np.broadcast and np.select call Shape.Broadcast DIRECTLY and so keep
NumPy's DIFFERENT "shape mismatch: … Mismatch is between arg i …" wording. The try/catch
costs nothing on the success path (it only unwinds when the broadcast genuinely fails).
Broadcast(params Shape[])
Broadcasts multiple shapes and returns the broadcasted shapes with computed strides.
public static Shape[] Broadcast(params Shape[] shapes)
Parameters
shapesShape[]
Returns
- Shape[]
Remarks
Delegates to Shape.Broadcast
Cast(NDArray, NPTypeCode, bool)
public NDArray Cast(NDArray nd, NPTypeCode dtype, bool copy)
Parameters
ndNDArraydtypeNPTypeCodecopybool
Returns
Cast(NDArray, Type, bool)
public override NDArray Cast(NDArray nd, Type dtype, bool copy)
Parameters
Returns
Cbrt(NDArray, DType, NDArray, NDArray)
Element-wise cube root using IL-generated kernels. Computes the cube root of each element.
public override NDArray Cbrt(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Ceil(NDArray, DType, NDArray, NDArray)
Element-wise ceiling using IL-generated kernels. NumPy: for integer dtypes, ceil is a no-op that preserves the input dtype.
public override NDArray Ceil(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
ClipNDArray(NDArray, NDArray, NDArray, DType, NDArray, NDArray)
np.clip's engine entry: NumPy's _methods._clip plus the ufunc it routes to. A Python-int
bound that cannot clip anything is dropped. A kept bound that does not fit the loop dtype raises
OverflowException instead of wrapping. The array and the bounds broadcast together
(with out and where), as the ufunc's operands do.
public override NDArray ClipNDArray(NDArray lhs, NDArray min, NDArray max, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe array to clip. Any layout; it may be smaller than the result (it broadcasts).
minNDArrayThe lower bound, or null for none. A 0-d bound is a scalar. A 0-d bound of an integer dtype (any of the eight C# integer primitives, or char) is NumPy's Python int, because a C# integer literal arrives as one. An array bound (ndim ≥ 1) broadcasts with the other operands.
maxNDArrayThe upper bound, or null for none, with the same scalar rules as
min.dtypeDTypeThe loop dtype (NumPy's
dtype=). It replaces the promoted dtype, and every input must reach it by a same_kind cast. The drop rule still useslhs's own range.outNDArrayThe array to write into, or null for a fresh result. The loop dtype must reach it by a same_kind cast. It takes part in the broadcast but is never stretched. It is returned as-is.
whereNDArrayNumPy's
where=mask (bool), or null for everywhere. It broadcasts with the other operands; only the True positions are written. Withoutoutthe other positions of the fresh result are uninitialized, as in NumPy.
Returns
- NDArray
The clipped array:
outwhen given, otherwise a fresh array of the loop dtype in the memory layout NumPy's ufunc allocates (the operands' memory order; C order breaks ties).
Exceptions
- ValueError
outis read-only (checked first, as in NumPy); or the operands do not broadcast together ("operands could not be broadcast together with shapes (3,) (4,) () "); oroutwould have to be stretched ("non-broadcastable output operand with shape ... doesn't match the broadcast shape ...").- TypeError
A
dtypethe inputs cannot reach, or a loop dtypeoutcannot hold, under the same_kind rule (NumPy's UFuncTypeError texts, naming the routed ufunc).- ArgumentException
whereis not a bool array (NumPy's 'safe' cast text).- OverflowException
A kept Python-int bound does not fit an integer loop dtype ("Python integer 1000 out of bounds for int8"), raised before any element is read, so also for an empty
lhs. See CheckPyIntPacksIntoLoop(Int128, NPTypeCode).- TypeError
No bound is left and the loop would be bool: NumPy's
positivehas no bool loop.- INumSharpException
A read-only
out: NumPy's ValueError "output array is read-only", raised first (ThrowIfNotWriteable(Shape, string)).- ValueError
A text
outunderwherewhose current text does not parse into the loop dtype (a text out receives the clipped values as text otherwise).
Compare(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray Compare(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Conjugate(NDArray, DType, NDArray, NDArray)
Element-wise complex conjugate (np.conjugate / np.conj) using the IL-generated unary kernel. Identity at every real dtype (int/char/half/single/double/decimal — the value is copied unchanged, dtype preserved; bool, which has no loop, resolves to int8 without dtype=, as NumPy's ufunc does); for Complex it flips the sign of the imaginary part. Handles every memory layout (contiguous / strided / transposed / broadcast / sliced) through the shared unary dispatch, and honours out=/where=.
public override NDArray Conjugate(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Convolve(NDArray, NDArray, string)
DefaultEngine's Convolve(NDArray, NDArray, string): NumPy's np.convolve statements, the 0-d promotion of
array(x, copy=None, ndmin=1), the two emptiness checks, the swap that makes the longer sequence the data
(convolution is commutative, so no reversal of the result follows), and the correlation of the data with the
reversed kernel.
public override NDArray Convolve(NDArray a, NDArray v, string mode = "full")
Parameters
aNDArrayThe first sequence (any dtype, any layout; a 0-d one is one element).
vNDArrayThe second sequence (likewise).
modestringfull,sameorvalid.
Returns
- NDArray
A fresh 1-D array of the operands' common dtype: the discrete linear convolution.
Remarks
The 0-d promotions and the reversed view are temporaries the [NDScoped] weaver releases when the call ends; the operands themselves are never tracked (the weaver roots them at this entry, so neither is finalized while the kernels read it), and the correlation's result is returned.
Exceptions
- ValueError
a cannot be empty/v cannot be empty(on the operands as given, before the swap), then the correlation's own errors (Correlate(NDArray, NDArray, string): an unknown mode comes AFTER these checks here, as NumPy parses it insidemultiarray.correlate).- UnicodeEncodeError
A
modeholding a lone surrogate (after the emptiness checks).- TypeError
A null
mode(NumPy'sNone, after the emptiness checks), or aStringDTypeoperand's refusal or first-product error.- NotSupportedException
A
StringDTypeoperand whose OBJECT product NumPy computes.
CopySign(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray CopySign(NDArray x1, NDArray x2, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Corrcoef(NDArray, NDArray, bool, DType)
NumPy's np.corrcoef(x, y=None, rowvar=True, *, dtype=None): the Pearson correlation coefficients
R_ij = C_ij / sqrt(C_ii * C_jj) of C = cov(x, y, rowvar, dtype=dtype), the two divisions made in
place, then the result clipped to [-1, 1] in place (the real and the imaginary lanes of a complex result), which
rounding can push a coefficient past.
public override NDArray Corrcoef(NDArray x, NDArray y = null, bool rowvar = true, DType dtype = null)
Parameters
xNDArrayThe variables, a plain array (not null): 1-D or 2-D, a variable per row unless
rowvaris false.yNDArrayAn additional set of variables, or null.
rowvarboolWhether rows are variables (columns observations).
dtypeDTypeThe result dtype, or null for Cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType)'s
result_type(x, y, float64).
Returns
- NDArray
The correlation matrix, a fresh array the caller owns (cov's own matrix, divided and clipped in place). For one variable cov's result is 0-d, which has no diagonal: NumPy's
c / cthen, 1 or NaN (a NaN, infinite or zero variance). No variables give cov's empty(0, 0)float64 array.
Remarks
NumPy writes corrcoef in Python over cov (NumPy 2.x dropped its bias / ddof); DefaultEngine runs
its statements over the operand engine's Cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType), Sqrt(NDArray, DType, NDArray, NDArray), Divide(NDArray, NDArray, DType, NDArray, NDArray) and
ClipNDArray(NDArray, NDArray, NDArray, DType, NDArray, NDArray) and the array object's diagonal and real / imaginary lanes. np.corrcoef calls
it after the null check, a subclass operand handed in as its plain view; an override replaces it for every
array whose engine it is.
Exceptions
- ValueError
More than 2 dimensions; text variables whose
xandyhave different observation counts; text that does not parse into a numericdtype; aStringDTyperequest over no observations (Cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType)'s).- IncorrectShapeException
Numeric variables with different observation counts (cov's concatenate).
- TypeError
Text that cov's mean refuses.
- DTypePromotionError
StringDTypevariables withoutdtype.- ArgumentException
An integer or bool
dtype(cov's in-place centring refuses the cast).- OverflowException
An integer text outside an integer
dtype, or decimal arithmetic out of range.- UnicodeEncodeError
A U → S conversion of non-ASCII text.
- UnicodeDecodeError
An S → U conversion of non-ASCII bytes.
Correlate(NDArray, NDArray, string)
NumPy's multiarray.correlate(a, v, mode) — PyArray_Correlate, the correlation np.convolve
ends with (multiarray.correlate(a, v[::-1], mode)) — the whole call: the mode, the operands'
descriptor lookup (a StringDType operand's answers), their one-dimension check,
_pyarray_correlate's emptiness checks, the result allocation (a fixed-width string type number has no
item size) and the sliding product c_k = Σ_n a[n + k] · v[n] in the operands' common dtype. Unlike
Correlate2(NDArray, NDArray, string) it neither conjugates v nor reverses the result when the operands
are swapped (the longer one is always the data).
public override NDArray Correlate(NDArray a, NDArray v, string mode = "valid")
Parameters
aNDArrayThe first one-dimensional sequence (any dtype, any layout).
vNDArrayThe second one-dimensional sequence, read forward: np.convolve passes its kernel reversed.
modestringvalid(the default),sameorfull, matched exactly.
Returns
- NDArray
A fresh 1-D array of the operands' common dtype, of
max(n1, n2) - min(n1, n2) + 1,max(n1, n2)orn1 + n2 - 1elements.
Remarks
NumPy's function is C (multiarraymodule.c), so the call is an engine member; np.convolve's Python
statements (the 0-d promotion, its own emptiness checks, the swap by length, the reversal) run before it in
Convolve(NDArray, NDArray, string).
Exceptions
- ValueError
First an unknown
mode, with NumPy's two texts:Use one of 'valid', 'same', or 'full' for convolve/correlate modefor a text whose first letter names a mode,mode must be one of 'valid', 'same', or 'full' (got 'x')with the argument in Python'sreprfor any other. Then an operand that is not one-dimensional (object of too small depth for desired arrayfor a 0-d one,object too deep for desired arrayfor two or more dimensions, the first operand first), an empty one (first array argument cannot be empty/second array argument cannot be empty), or a fixed-width string operand after those checks (data type must provide an itemsize).- UnicodeEncodeError
A
modeholding a lone surrogate: CPython's UTF-8 encoding error, raised before the mode is read.- TypeError
A null
mode(NumPy'sNone):convolve/correlate mode not understood. AStringDTypeoperand: NumPy's legacy-only descriptor refusal, or Python's error from the first product of its OBJECT fallback.- NotSupportedException
A
StringDTypeoperand whose OBJECT product NumPy computes (an object array, which NumSharp does not have).
Correlate2(NDArray, NDArray, string)
NumPy's multiarray.correlate2(a, v, mode) — PyArray_Correlate2, the whole body of
np.correlate — the whole call: Correlate(NDArray, NDArray, string)'s statements, with the second operand conjugated
for a complex common dtype before the product (c_k = Σ_n a[n + k] · conj(v[n])) and, when the operands
are swapped because a is the shorter, the result reversed (_pyarray_revert), so
correlate2(v, a) is the reversed conjugate of correlate2(a, v).
public override NDArray Correlate2(NDArray a, NDArray v, string mode = "valid")
Parameters
aNDArrayThe first one-dimensional sequence (any dtype, any layout).
vNDArrayThe second one-dimensional sequence (conjugated for a complex common dtype).
modestringvalid(the default),sameorfull, matched exactly.
Returns
- NDArray
A fresh 1-D array of the operands' common dtype (lengths as for Correlate(NDArray, NDArray, string)).
Remarks
NumPy's function is C, so the call is an engine member; the subclass answer stays with
np.correlate's woven subclass path.
Exceptions
- ValueError
An unknown
mode, then an operand that is not one-dimensional, an empty one, or a fixed-width string one (the texts and order of Correlate(NDArray, NDArray, string)).- UnicodeEncodeError
A
modeholding a lone surrogate.- TypeError
A null
mode(convolve/correlate mode not understood), or aStringDTypeoperand's refusal or first-product error.- NotSupportedException
A
StringDTypeoperand whose OBJECT product NumPy computes.
Cos(NDArray, DType, NDArray, NDArray)
Element-wise cosine using IL-generated kernels.
public override NDArray Cos(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Cosh(NDArray, DType, NDArray, NDArray)
Element-wise hyperbolic cosine using IL-generated kernels.
public override NDArray Cosh(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
CountNonZero(NDArray)
Count the number of non-zero elements in the array.
public override long CountNonZero(NDArray nd)
Parameters
ndNDArrayThe array.
Returns
- long
The number of elements whose truth value is True.
Remarks
A string array is counted by its truth values (a non-empty string counts; never raises).
CountNonZero(NDArray, int, bool)
Count non-zero elements along a specific axis.
public override NDArray CountNonZero(NDArray nd, int axis, bool keepdims = false)
Parameters
ndNDArrayThe array.
axisintThe reduced axis.
keepdimsboolWhether the reduced axis stays with length one.
Returns
- NDArray
The int64 counts: NumPy's read-only scalar stand-in when the result is 0-d (a 1-D or 0-d input without keepdims, empty or not), a fresh writeable array otherwise.
Remarks
A string array is counted by its truth values: NumPy's (a != '').sum(axis) (never raises).
Exceptions
- AxisError
axisis out of bounds — the sum's rule NumPy's count_nonzero inherits (a.astype(bool).sum(axis)), so a 0-d input accepts 0 and -1 and nothing else.
Cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType)
DefaultEngine's Cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType): CovFunction(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType), NumPy's whole body, under this member's scope.
public override 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
mNDArrayThe variables (not null): a 1-D or 2-D array, rows are variables unless
rowvaris false.yNDArrayAn additional set of variables, or null.
rowvarboolWhether rows are variables (columns observations).
biasboolNormalize by N instead of N - 1 (overridden by
ddof).ddofint?The delta degrees of freedom, or null for
bias's default.fweightsNDArrayThe integer frequency weights, or null.
aweightsNDArrayThe analytic weights, or null.
dtypeDTypeThe requested dtype, or null for at least float64.
Returns
- NDArray
The covariance matrix, which survives the scope (every intermediate is reclaimed).
Remarks
The scope was np.cov's until the plan's phase PE (the body was [NDScopedCovered] under it); as a public
entry point the override owns it now, so a direct engine caller's intermediates are reclaimed too. np.cov keeps
its own [NDScoped] (nested scopes).
Exceptions
- Exception
The errors of CovFunction(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType), in its order.
CreateNDArray(Shape, DType, IArraySlice, char)
public override NDArray CreateNDArray(Shape shape, DType dtype = null, IArraySlice buffer = null, char order = 'C')
Parameters
shapeShapedtypeDTypebufferIArraySliceorderchar
Returns
CreateNDArray(Shape, DType, Array, char)
public override NDArray CreateNDArray(Shape shape, DType dtype = null, Array buffer = null, char order = 'C')
Parameters
Returns
Cross(NDArray, NDArray, int, int, int, int?)
NumPy's np.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): the cross product of (arrays of)
2- or 3-vectors taken along axisa / axisb, the other axes broadcast; a
2-vector's missing third component is zero, and two 2-vectors give only the z-component.
public override NDArray Cross(NDArray a, NDArray b, int axisa = -1, int axisb = -1, int axisc = -1, int? axis = null)
Parameters
aNDArrayThe first vector(s), at least 1-D.
bNDArrayThe second vector(s), at least 1-D.
axisaintThe axis of
athat holds the vectors (negative counts from the end).axisbintThe axis of
bthat holds the vectors.axiscintThe axis of the result that holds the 3-vectors; ignored when both inputs are 2-vectors.
axisint?When given, the one axis of both inputs and the result; it overrides the other three.
Returns
- NDArray
A new array in
promote_types(a.dtype, b.dtype)over the broadcast leading axes, plus the 3-vector axis ataxiscunless both inputs are 2-vectors.
Remarks
DefaultEngine composes NumPy's statements over multiply, negative, subtract and moveaxis (no kernel of its own). The 2-vector forms are deprecated in NumPy 2.0; the warning is not modelled.
Exceptions
- NullReferenceException
aorbis null.- ValueError
A 0-D input (
At least one array has zero dimension), or a vector length other than 2 or 3 (incompatible dimensions for cross product).- AxisError
An axis out of range for its operand, reported with its
axisa/axisb/axiscprefix;axiscis checked against the result's rank right after the broadcast.- IncorrectShapeException
Leading axes that do not broadcast (
np.broadcast's text), raised before the dtype promotion.- TypeError
A text operand: multiply has no string loop (raised after the shape checks).
CumSumElementwise<T>(NDArray, NPTypeCode?)
public NDArray CumSumElementwise<T>(NDArray arr, NPTypeCode? typeCode) where T : unmanaged
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
Type Parameters
T
Deg2Rad(NDArray, DType, NDArray, NDArray)
Element-wise degrees to radians conversion using IL-generated kernels. Computes x * (π/180).
public override NDArray Deg2Rad(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Degrees(NDArray, DType, NDArray, NDArray)
NumPy's np.degrees ufunc: the same conversion as Rad2Deg(NDArray, DType, NDArray, NDArray) (radians to degrees), but a ufunc of its
own, so a refusal (text, an operand type with no loop) names degrees.
public override NDArray Degrees(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
ndNDArrayThe angles.
dtypeDTypeThe loop dtype (
dtype=), or null for the operand's float tier.outNDArrayThe array to write into (
out=), or null.whereNDArrayThe bool mask of the positions to compute (
where=), or null for all.
Returns
- NDArray
The converted angles:
outwhen given, else a new array of the float tier (float16 for bool / int8 / uint8, float32 for int16 / uint16, float64 for wider integers; floats keep theirs).
Exceptions
- TypeError
A text or complex operand (no degrees loop), with NumPy's texts.
- ValueError
A read-only
out.- ArgumentException
A non-bool
where, or adtypethe operand cannot reach.
Diff(NDArray, int, int, object, object)
NumPy's np.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>): the n-th
discrete difference along an axis, a = op(a[1:], a[:-1]) repeated n times after concatenating
prepend / append along the axis, where op is != for bool and - otherwise.
public override NDArray Diff(NDArray a, int n = 1, int axis = -1, object prepend = null, object append = null)
Parameters
aNDArrayThe input, at least 1-D (not null).
nintHow many times to difference; 0 returns
aitself.axisintThe axis to difference along (negative counts from the end).
prependobjectValues to put before
aalong the axis (a scalar is broadcast to length 1), or null for none.appendobjectValues to put after
aalong the axis, or null for none.
Returns
- NDArray
aitself forn0; otherwise a new array, the axis shorter byn, in the subtraction's dtype (bool for a bool input).
Exceptions
- ArgumentNullException
ais null.- ArgumentException
A negative
n(order must be non-negative but got -1).- ValueError
A 0-D
a(diff requires input that is at least one dimensional).- AxisError
axisout of range.- TypeError
Text with
nabove 0: subtract has no string loop.
Digitize(NDArray, NDArray, bool)
NumPy's np.digitize(x, bins, right=False): the index of the bin each value of x
falls in, searchsorted on the bins (reversed for decreasing bins) with the side right
selects.
public override NDArray Digitize(NDArray x, NDArray bins, bool right = false)
Parameters
xNDArrayThe values to bin, any shape (not null).
binsNDArrayThe 1-D monotonic bin edges (not null).
rightboolWhether an interval includes its right edge instead of its left one.
Returns
- NDArray
The int64 bin indices, of
x's shape.
Exceptions
- ArgumentNullException
xorbinsis null.- IncorrectTypeException
A complex
x(x may not be complex, checked first).- ValueError
binsnot 1-D, or not monotonic (bins must be monotonically increasing or decreasing).- InvalidCastException
binsthat do not cast 'safely' to float64 (NumPy's TypeError text).- TypeError
A StringDType
xagainst numeric bins: Python cannot order the pair.
DivMod(NDArray, NDArray, DType, (NDArray Quotient, NDArray Remainder), NDArray)
np.divmod — the fused two-output ufunc (floor_divide(lhs, rhs), remainder(lhs, rhs)),
element-wise. Item1 is the floored quotient, Item2 the floored remainder (divisor's sign).
Two routes, both bit-identical to NumPy 2.4.2:
- When
out(a 2-tuple, either slot may be null) orwhereis supplied, or an explicitdtypeloop is requested, NumPy's two-output ufunc call (DivModInto(NDArray, NDArray, NPTypeCode, NPTypeCode?, NDArray, NDArray, NDArray)): ONE iterator over(x1, x2, out1, out2[, where])whose inner loop reads each element pair once and writes both results, so an out that is also an input (np.divmod(a, 2.0, out=(a, r))) still leaves the remainders of the ORIGINAL dividends inr. - Otherwise run the FUSED single-pass IL kernel (GetDivModKernel(NPTypeCode)), which computes both outputs from one NDDivision Divmod* call per element over contiguous, promoted operands — measurably faster than composing (no second pass, one idiv for integers).
Complex raises (NumPy has no complex divmod loop; matches Mod(NDArray, NDArray, DType, NDArray, NDArray)'s refusal).
public override (NDArray Quotient, NDArray Remainder) DivMod(NDArray lhs, NDArray rhs, DType dtype = null, (NDArray Quotient, NDArray Remainder) @out = default, NDArray where = null)
Parameters
lhsNDArrayThe dividends (
x1).rhsNDArrayThe divisors (
x2); broadcasts againstlhs.dtypeDTypeNumPy's
dtype=: the loop both results are computed in (each input must reach it by a same_kind cast), or null for the NEP 50 promotion of the inputs (bool promotes to the int8 loop).out(NDArray Lhs, NDArray Rhs)NumPy's
out=(out1, out2): the arrays the quotient and the remainder are written into (either may be null for a fresh one). Each must take the loop dtype by a same_kind cast and have the broadcast shape (it is never stretched); it may be an input itself.whereNDArrayNumPy's
where=: a bool mask broadcast over the iteration; a False position keeps what a given out held (and is uninitialized in a fresh result, as in NumPy).
Returns
- (NDArray Lhs, NDArray Rhs)
The (quotient, remainder) pair: each given out itself, or a fresh array of the loop dtype laid out the way NumPy's iterator allocates it.
Exceptions
- TypeError
A
dtypenaming more than a DType class ('>f8'), a text operand or request divmod has no loop for, or (out= route) a bool / complexdtype: NumPy'sNo loop matching the specified signature and casting was found for ufunc divmod.- TypeError
A complex operand with no
dtype(divmod has no complex loop): NumPy'sufunc 'divmod' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'', raised before any element is read (a zero-size operand too) and after the outs and the mask are checked; under a realdtypeit is the input cast refusal instead (parity QA-27).- ValueError
A read-only array in
out(output array is read-only, checked for both slots before anything else), or a text out underwherewhose current text does not parse into the loop dtype.- TypeError
An input
dtypecannot take, or an out that cannot take the loop dtype, by a same_kind cast (NumPy'sCannot cast ufunc 'divmod' input 0 / output 2 …texts).- ArgumentException
A non-bool
where; an out or mask that does not broadcast, or an out that would be stretched.- IncorrectShapeException
The inputs do not broadcast together.
- OverflowException
A C# integer literal operand (NumPy's Python int) outside the integer loop's range (
Python integer 1000 out of bounds for int8).
Divide(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise division using IL-generated kernels. Supports all 144 type combinations with automatic type promotion.
public override NDArray Divide(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Dot(NDArray, NDArray, NDArray)
np.dot's whole call (Dot(NDArray, NDArray, NDArray)): the text operands'
answers with out in NumPy's order; with out and a 0-d operand outside
the cblas route, the multiply ufunc's out=; otherwise the product (DotProduct(NDArray, NDArray)), then
new_array_for_sum's strict out= check and the copy into out. A 0-d result of an
out= call is NumPy's scalar (ScalarReturn(NDArray)).
public override NDArray Dot(NDArray left, NDArray right, NDArray @out = null)
Parameters
leftNDArrayThe first operand.
rightNDArrayThe second operand.
outNDArrayThe out array, or null.
Returns
- NDArray
The product, or
outafter the product reached it; for a 0-d result of an out= call, a fresh read-only 0-d copy instead ofout.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.dot.html
NumPy's routes (PyArray_MatrixProduct2, multiarraymodule.c): both operands are
converted to their common dtype; float32 / float64 / complex128 operands of at most two dims each go to
cblas_matrixproduct (strict out=, a 0-d operand included); otherwise a 0-d operand is
multiply(ap1, ap2, out); otherwise the dtype's dot function per output element (strict out=).
array_matrixproduct then returns PyArray_Return(result), so a 0-d result is a scalar even when
it is the caller's out array: np.dot(f8 [0, 1, 2], f8 [0, 1, 2], out=o) is np.float64(5.0), not o.
Exceptions
- ValueError
An out array the strict check refuses (the two texts of Dot(NDArray, NDArray, NDArray)); on the multiply route, a read-only out (
output array is read-only).- IncorrectShapeException
Misaligned operands.
- TypeError
On the multiply route, an out dtype the product cannot be cast into same_kind (
Cannot cast ufunc 'multiply' output from …, NumPy's UFuncTypeError).- ArgumentException
On the multiply route, the ufunc's house type for NumPy's ValueError: an out the product cannot broadcast into (
non-broadcastable output operand with shape …).
DotFunction1D(NDArray, NDArray)
The dtype's dot function itself over two 1-D operands of one length (NumPy's PyArray_ArrFuncs.dotfunc),
without np.dot's cblas_matrixproduct rules: a length-1 pair is summed from +0 like any other, and a
negative or zero stride runs the dot function's own loop instead of being copied. np.vdot ends here
(NumPy's array_vdot calls the dot function directly; Vdot(NDArray, NDArray)).
public override NDArray DotFunction1D(NDArray left, NDArray right)
Parameters
Returns
- NDArray
A fresh 0-d result of the operands' common dtype.
Remarks
np.vdot of a complex128 pair does not end here: VdotFunction1D(NDArray, NDArray) runs CDOUBLE_vdot, which
conjugates inside its sums. A conjugated copy through this function gives the same values (negating every
imaginary part of x negates the two sums that use it exactly) but flips a NaN imaginary part's sign.
Exceptions
- IncorrectShapeException
The vectors' lengths differ.
- DTypePromotionError
The operands have no common dtype.
DotNDMD(NDArray, NDArray)
N-D x M-D dot product: sum product over last axis of lhs and second-to-last axis of rhs. dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
public NDArray DotNDMD(NDArray lhs, NDArray rhs)
Parameters
Returns
Remarks
This replaces the original ~15,880 line implementation that used nested switch statements for every combination of dimension counts. Every layout and dtype runs one walk (DotNDMDStrided(NDArray, NDArray, NDArray, long[], long[], long)): an odometer over both operands' iterated axes and the dtype's dot function per output, four outputs at a time where a row allows. Contiguous float32 / float64 operands had a walker of their own that computed each output's offsets with an index division and read a view from its storage's start; the walk measured 1.05-2.07x faster on them, never slower, with the same bits, and reads a C-contiguous view at its own offset (an np.split / np.unstack child), which the former walker did not.
Ediff1d(NDArray, object, object)
NumPy's np.ediff1d(ary, to_end=None, to_begin=None): the differences between consecutive elements
of the flattened array, with to_begin / to_end (each cast to ary's dtype under
same_kind) put before and after.
public override NDArray Ediff1d(NDArray ary, object to_end = null, object to_begin = null)
Parameters
aryNDArrayThe input, flattened (not null).
to_endobjectValues to append, or null for none.
to_beginobjectValues to prepend, or null for none.
Returns
- NDArray
A new 1-D array in
ary's dtype.
Exceptions
- ArgumentNullException
aryis null.- TypeError
to_begin / to_end that cannot reach
ary's dtype undersame_kind(NumPy's TypeError and text:dtype of).to_beginmust be compatible with inputaryunder thesame_kindrule.- TypeError
Text or bool, which subtract has no loop for (NumPy's texts).
Einsum(string, NDArray[], NDArray, DType, char, string, object)
NumPy's np.einsum(subscripts, *operands, out=None, dtype=None, order='K', casting='safe',
optimize=False): the Einstein summation convention over operands, the whole call
from the argument checks to the copy into out.
public override NDArray Einsum(string subscripts, NDArray[] operands, NDArray @out = null, DType dtype = null, char order = 'K', string casting = "safe", object optimize = null)
Parameters
subscriptsstringComma-separated subscript labels, optionally followed by
->and the output labels ("ij,jk->ik"); spaces are ignored and...broadcasts. Without->the output is every label used once, in ASCII order, after the broadcast dimensions.operandsNDArray[]The arrays the subscripts label, in order (the facade turns NumPy's sublist spelling into a subscripts string first).
outNDArrayAn array to receive the result, or null for a new array. Its rank is checked with the subscripts, its shape and dtype after the contraction.
dtypeDTypeThe loop dtype, or null for the operands' promoted dtype (NEP 50
result_type, not Sum(NDArray, int?, DType, bool)'s widened accumulator:'ij->i'over int32 is int32).ordercharThe result's memory layout:
'C','F','A'or'K', in either case.'A'and'K'give F order when every operand is F-contiguous;'A'gives C order otherwise and'K'keeps the computed layout.castingstringThe rule every operand must meet to reach the loop dtype, and the result to reach
out's dtype:"no","equiv","safe","same_kind"or"unsafe", spelled exactly.optimizeobjectNumPy's
optimize=: null orfalse,true, any string ("greedy","optimal"; NumPy reads another string as greedy), a path fromnp.einsum_path(an EinsumPath or NumPy's raw['einsum_path', ...]list), or a(string, number)tuple. It is checked like NumPy checks it and does not change the result: the contraction always runs left to right.
Returns
- NDArray
One operand, no
outand no label summed: a VIEW of the operand (diagonals and a transpose), writeable when the operand is, never the operand itself;orderanddtypeare ignored there, as NumPy ignores them.Otherwise a new array in the loop dtype, or
outitself holding the result cast to its dtype. A full contraction gives a 0-d array.
Remarks
The contraction is NumPy's optimize= path (bmm_einsum): a left-to-right pairwise
fold, each step one Matmul(NDArray, NDArray) (batched when labels are shared and kept)
after diagonals, sums and a transpose of each term, or one broadcast Multiply(NDArray, NDArray, DType, NDArray, NDArray) when nothing
is contracted. The products dispatch on Blas, so float32 / float64 / complex128
contractions match NumPy's optimize=True byte for byte when the OpenBLAS backend is installed.
Integer and boolean contractions are exact; a float sum outside a product ('ij->i', three or
more operands) follows NumSharp's sum order and can differ from NumPy's default (C) einsum in the last
ULP.
An override replaces the whole call, the checks included; the facade only applies the numpy.matrix and numpy.char.chararray boundaries and converts the sublist spelling before it calls this member.
Exceptions
- ArgumentNullException
subscriptsis null.- ValueError
No operand (
must specify the einstein sum subscripts string and at least one operand); anorderletter or acastingname NumPy refuses, with its texts; subscripts NumPy refuses (malformed labels, a wrong operand count, a bad ellipsis, an output label absent from the inputs, an impossible diagonal, label extents that disagree, anoutof the wrong rank), with its parser's texts; anoutwhose extents differ from the result's; a read-onlyout.- TypeError
castingis null; anoptimizeNumPy does not understand (Did not understand the path: ...); an operand that cannot reach the loop dtype undercasting, or a result that cannot reachout's dtype, with NumPy's iterator texts; a text operand or a textdtypeoutside the view path, which have no sum of products (NumPy's cast, zero-fill and loop refusals, in its order).
EinsumPath(string, NDArray[], object)
NumPy's np.einsum_path(subscripts, *operands, optimize='greedy'): the order in which to contract the
operands pairwise and NumPy's printed cost report, computed from the subscripts and the operands' SHAPES
(no element is read): _parse_einsum_input, then the _greedy_path / _optimal_path
search with the _flop_count cost model, then the info string.
public override (EinsumPath path, string repr) EinsumPath(string subscripts, NDArray[] operands, object optimize)
Parameters
subscriptsstringThe einsum subscripts, as Einsum(string, NDArray[], NDArray, DType, char, string, object) reads them (the facade turns NumPy's sublist spelling into this string first).
operandsNDArray[]The operands the subscripts label; null reads as none. Only their shapes are read.
optimizeobjectNumPy's
optimize=, required here (NumPy's default,'greedy', is the facades': a C# object parameter cannot default to a string), in its decision order:false/ null (no optimization: the operands in order),true,"greedy"or"optimal", a precomputed EinsumPath (an explicit path, checked for completeness), or a("greedy" | "optimal", memory)tuple capping the largest intermediate.
Returns
- (EinsumPath path, string repr)
The path (NumPy's
['einsum_path', (i, j), ...]list as an EinsumPath) and the report; both byte-identical to NumPy's except the placeholder letters an ellipsis expands to in the report, which NumPy draws from a hash-randomized set and NumSharp deterministically.
Remarks
The cost model is BigInteger arithmetic, as NumPy's Python ints are, so products
past 64 bits still compare correctly. An override replaces the plan of np.einsum_path (whose facade
dispatches on the first operand's engine, the default one with none); Einsum(string, NDArray[], NDArray, DType, char, string, object) resolves its own
optimize= separately and contracts left to right whatever the plan.
Exceptions
- ArgumentNullException
subscriptsis null.- ValueError
A null operand (
einsum_path operand {i} is null); subscripts NumPy's Python parser refuses, with its texts (an operand count that differs from the terms', a second->, an invalid symbol, an output label no input has, a term of the wrong rank, extents that disagree).- KeyError
An unknown path name (NumPy's
('Path name %s not found', ...)).- RuntimeError
An explicit path that does not contract every operand.
- TypeError
An
optimizeNumPy does not understand (Did not understand the path: ...,object of type 'int' has no len()).- IndexOutOfRangeException
An ellipsis with no operand to read its rank from (where NumPy fails indexing its operand list).
EmathArccos(NDArray)
NumPy's np.emath.arccos(x): _fix_real_abs_gt_1(x), then arccos. A real element with
|x| > 1 (an infinity included) makes the whole result complex where ACos(NDArray, DType, NDArray, NDArray) returns
NaN.
public override NDArray EmathArccos(NDArray x)
Parameters
xNDArrayThe input, any dtype and layout.
Returns
- NDArray
The inverse cosine: real in
[0, pi]while every real element has|x| <= 1(NaN does not trigger the conversion), complex128 otherwise or for a complex input.
Exceptions
- TypeError
A text operand: the scan's
abs(x)has no text loop, NumPy'sufunc 'absolute' did not contain a loop with signature matching types ... -> None, even for an empty array.
EmathArcsin(NDArray)
NumPy's np.emath.arcsin(x): _fix_real_abs_gt_1(x), then arcsin; a real element with
|x| > 1 makes the whole result complex.
public override NDArray EmathArcsin(NDArray x)
Parameters
xNDArrayThe input, any dtype and layout.
Returns
- NDArray
The inverse sine: real in
[-pi/2, pi/2]while every real element has|x| <= 1, complex128 otherwise or for a complex input.
Exceptions
- TypeError
A text operand, with EmathArccos(NDArray)'s text.
EmathArctanh(NDArray)
NumPy's np.emath.arctanh(x): _fix_real_abs_gt_1(x), then arctanh; a real element with
|x| > 1 makes the whole result complex. |x| == 1 stays real and gives ±inf.
public override NDArray EmathArctanh(NDArray x)
Parameters
xNDArrayThe input, any dtype and layout.
Returns
- NDArray
The inverse hyperbolic tangent: real while every real element has
|x| <= 1, complex128 otherwise or for a complex input.
Exceptions
- TypeError
A text operand, with EmathArccos(NDArray)'s text.
EmathLog(NDArray)
NumPy's np.emath.log(x): _fix_real_lt_zero(x), then log. A negative real element makes
the whole result complex (log(-e) == 1 + pi i) where Log(NDArray, DType, NDArray, NDArray) returns NaN.
public override NDArray EmathLog(NDArray x)
Parameters
xNDArrayThe input, any dtype and layout.
Returns
- NDArray
The natural logarithm: complex128 when
xis complex or a real element is negative (complex64 in NumPy for the narrow dtypes listed on EmathSqrt(NDArray)), else real;log(0)is-infandlog(inf)inf, both real.
Exceptions
- TypeError
A text operand, with EmathSqrt(NDArray)'s text.
EmathLog10(NDArray)
NumPy's np.emath.log10(x): _fix_real_lt_zero(x), then log10; a negative real element
makes the whole result complex.
public override NDArray EmathLog10(NDArray x)
Parameters
xNDArrayThe input, any dtype and layout.
Returns
- NDArray
The base-10 logarithm, complex under EmathLog(NDArray)'s conditions, else real.
Exceptions
- TypeError
A text operand, with EmathSqrt(NDArray)'s text.
EmathLog2(NDArray)
NumPy's np.emath.log2(x): _fix_real_lt_zero(x), then log2; a negative real element
makes the whole result complex.
public override NDArray EmathLog2(NDArray x)
Parameters
xNDArrayThe input, any dtype and layout.
Returns
- NDArray
The base-2 logarithm, complex under EmathLog(NDArray)'s conditions, else real.
Exceptions
- TypeError
A text operand, with EmathSqrt(NDArray)'s text.
EmathLogn(NDArray, NDArray)
NumPy's np.emath.logn(n, x): _fix_real_lt_zero(x), _fix_real_lt_zero(n), then
log(x) / log(n). Each operand is converted on its own, so a negative base alone (logn(-2, 8))
makes log(n) and with it the quotient complex.
public override NDArray EmathLogn(NDArray n, NDArray x)
Parameters
nNDArrayThe base(s), any dtype and layout. NumPy's argument order: the base comes first.
xNDArrayThe value(s), broadcast against
nby the division.
Returns
- NDArray
The quotient of the two logarithms, in the division's promoted dtype. A 0-d log result is read as a weak scalar by the division (the ufuncs' rule on this branch), where NumPy reads it as strong: a 0-d
xbeside a float16ngives float16 here and float64 in NumPy.
Exceptions
- TypeError
A text operand, with EmathSqrt(NDArray)'s text;
xis scanned first, as in NumPy.- IncorrectShapeException
Operands that do not broadcast together (NumPy's ValueError
operands could not be broadcast together with shapes ...), raised by the division after both logarithms.
EmathPower(NDArray, NDArray)
NumPy's np.emath.power(x, p): _fix_real_lt_zero(x), _fix_int_lt_zero(p), then
power(x, p). A negative real base makes the computation complex; a negative real exponent turns
p into a float (p * 1.0), so an integer base with a negative integer exponent
does not hit Power(NDArray, NDArray, DType, NDArray, NDArray)'s "Integers to negative integer powers" error.
public override NDArray EmathPower(NDArray x, NDArray p)
Parameters
xNDArrayThe base(s), any dtype and layout.
pNDArrayThe exponent(s), broadcast against
xby the power ufunc.
Returns
- NDArray
The power ufunc's result in its promoted dtype (complex128 after a negative real base). A 0-d operand is read as a weak scalar by the power ufunc (the ufuncs' rule on this branch), where NumPy reads a 0-d array as strong: a uint16 base with a 0-d int64 exponent gives uint16 here and int64 in NumPy.
Remarks
A negative base with a non-integer exponent takes the complex power, which is allclose to
NumPy's but not bit-exact (the F5 complex-power divergence); integer exponents are exact.
Exceptions
- TypeError
A text operand, with EmathSqrt(NDArray)'s text;
xis scanned first.- IncorrectShapeException
Operands that do not broadcast together, raised by the power ufunc.
EmathSqrt(NDArray)
NumPy's np.emath.sqrt(x): _fix_real_lt_zero(x), then sqrt. A real input with any element
below zero is converted to complex as a whole before the square root, so a negative element gets its
principal complex root where Sqrt(NDArray, DType, NDArray, NDArray) returns NaN.
public override NDArray EmathSqrt(NDArray x)
Parameters
xNDArrayThe input, any dtype and layout (a C# scalar or array converts at the facade).
Returns
- NDArray
The ufunc's result: complex128 when
xis complex or a real element is negative (NumPy picks complex64 for a float32, int8, int16, uint8 or uint16 input; NumSharp has one complex type), else the ordinary real result (integers and bool promote as Sqrt(NDArray, DType, NDArray, NDArray) does).-0.0and NaN never trigger the conversion. A 0-d input gives a 0-d array.
Remarks
The scan reads every element of a real operand once (an early exit at the first negative one); a complex operand skips it, because NumPy's conversion of a complex array is value-identical.
Exceptions
- TypeError
A text operand (S, U or StringDType): the domain scan's
x < 0has no loop for text and a Python int, NumPy'sufunc 'less' did not contain a loop ..., even for an empty array.
Evaluate(NDExpr, NDArray[], NDArray, NDArray, DType, string, char)
Fused evaluation of an NDExpr tree in one iterator pass: np.evaluate's whole call, its
keywords as the caller passed them (the np-layer dtype plan's D11). Virtual with a
NotSupportedException default, so an alternative engine opts in explicitly.
public override NDArray Evaluate(NDExpr expr, NDArray[] operands = null, NDArray @out = null, NDArray where = null, DType dtype = null, string casting = null, char order = 'K')
Parameters
exprNDExprThe tree; its array leaves are embedded NDArrays, or Input(int) leaves naming
operandsby position.operandsNDArray[]The positional operands for a tree of Input(int) leaves, or null for a tree whose leaves embed their arrays.
outNDArrayA pre-allocated result (ufunc
out=rules), or null.whereNDArrayA boolean write mask (ufunc
where=), or null.dtypeDTypeThe result dtype (a root cast), or null for the tree's own.
castingstringThe
out=cast rule name, or null forsame_kind.ordercharThe layout of a fresh result:
'K','C','F'or'A'(either case).
Returns
- NDArray
The evaluated array, or
outholding it.
Remarks
An implementation checks the arguments in np.evaluate's order: a read-only out,
then the keywords (dtype with out, the order letter, the casting name),
then the tree when its program is built (a node over a text operand that it does not compute among them) -
DefaultEngine's does.
Exceptions
- NotSupportedException
This engine has no fused evaluation (the default).
- ValueError
A read-only
out(output array is read-only); acastingname that is not a rule; anorderthat is not 'C' / 'F' / 'A' / 'K'.- StringComputationNotSupportedException
A node takes a text operand (S, U or StringDType) that np.evaluate does not compute yet: the six comparisons compute on text, every other node waits for a later phase of np.evaluate's text support (the message names it).
- TypeError
A comparison of text that NumPy refuses (S with U, text with a number): NumPy's own
UFuncTypeErrortext, raised by the comparison's guard when the call runs.- ArgumentException
Both
dtypeandout; an emptyoperandslist; anoutnot reachable from the result dtype undercasting; awherethat is not boolean.- ArgumentNullException
expris null, or an entry ofoperandsis.- NotSupportedException
dtype, a non-'K'orderor awheremask for a reduction tree.
Evaluate(NDExprProgram, NDArray[], NDArray, in NDEvaluateOptions)
The CompiledExpression entry: a program compiled ahead of time, evaluated
against operands (the program's own embedded arrays, or a positional list
the handle has already matched to the compiled dtype signature).
public override NDArray Evaluate(NDExprProgram program, NDArray[] operands, NDArray @out, in NDEvaluateOptions options = default)
Parameters
programNDExprProgramThe compiled program.
operandsNDArray[]The arrays bound to the program's inputs, in the program's order.
outNDArrayNumPy's
out=, ornullfor a fresh result.optionsNDEvaluateOptionsThe resolved
dtype=/casting=/order=keywords;defaultfor none.
Returns
- NDArray
outwhen given, else a fresh array bound to this engine.
Remarks
An engine derived from this one overrides it to observe or reroute compiled evaluations and calls
base to run them.
Exceptions
- IncorrectShapeException
The operands do not broadcast together.
- ValueError
outor a keyword is refused by NumPy's rules for the program's ufuncs.- NotSupportedException
A node the fused path does not evaluate for these dtypes.
Exp(NDArray, DType, NDArray, NDArray)
Element-wise exponential using IL-generated kernels.
public override NDArray Exp(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Exp2(NDArray, DType, NDArray, NDArray)
Element-wise 2^x using IL-generated kernels.
public override NDArray Exp2(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Expm1(NDArray, DType, NDArray, NDArray)
Element-wise exp(x) - 1 using IL-generated kernels.
public override NDArray Expm1(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
FMax(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise maximum, NaN-ignoring (np.fmax).
public override NDArray FMax(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
FMin(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise minimum, NaN-ignoring (np.fmin).
public override NDArray FMin(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Fabs(NDArray, DType, NDArray, NDArray)
Element-wise floating-point absolute value (np.fabs) — the FLOAT-ONLY sibling of
Abs(NDArray, DType, NDArray, NDArray). Unlike absolute it PROMOTES
integer/bool input to float (NEP50 width tier) and has NO complex loop, so a complex input
(or a dtype=complex request) is refused rather than reduced to a magnitude.
public override NDArray Fabs(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
ndNDArrayInput array (any dtype except Complex).
dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=). fabs has float loops ONLY (efdg), so a bool/integer/char request — or a Complex request — raises the no-loop IncorrectTypeException; a float request runs the loop at that precision and the input must reach it by asame_kindcast (a complex input then raises "Cannot cast ufunc 'fabs' input …").outNDArrayA location into which the result is stored (NumPy ufunc
out=): joins the broadcast without being stretched, must besame_kind-castable from the resolved float loop dtype, and is returned as-is. Ifnull(andwherenull) a freshly allocated float array is returned.whereNDArrayBoolean mask (NumPy ufunc
where=): only mask-true elements are computed/written; masked-offoutslots keep prior contents. Must be bool.
Returns
- NDArray
A float array (dtype per the NEP50 tier: bool/int8/uint8→float16, int16/uint16/char→float32, int32/uint32/int64/uint64→float64, float16/float32/float64/decimal preserved), or
out— each element the magnitude of the input (the sign bit cleared).
Remarks
Port of NumPy 2.4.2's fabs ufunc (generate_umath.py:
TD(flts, f='fabs', astype={'e':'f'}) — float loops only, float16 via float32). fabs
IS absolute on the float loops — the C fabs clears the IEEE sign bit, so the
result is BIT-EXACT including NaN payloads (a negative NaN's sign is cleared, payload kept)
and -0.0 → +0.0. It therefore rides Fabs, which aliases the
fully-SIMD Abs kernel at every emit site (a distinct op only so the
ufunc name is "fabs"); the float output type resolved here (not Abs's dtype-preserving
one) is what makes it fabs. The promoting path casts int→float BEFORE the abs (so fabs(int.MinValue) is the
exact float magnitude, never the wrapped integer abs). Decimal (no NumPy analog) is preserved
and computed via Abs(decimal), consistent with the other float-tier unaries.
Exceptions
- ArgumentException
whereis a non-bool array, or a floatdtypeis requested for a complex input (verbatim NumPy cast texts).- IncorrectTypeException
dtypeis a bool/integer/char or Complex dtype (no matching float loop).- TypeError
The input is Complex and no
dtypewas given (fabs has no complex loop — NumPy's "not supported for the input types" TypeError, same class as signbit/cbrt).
Fix(NDArray, NDArray)
NumPy's np.fix(x, out=None): rounds toward zero, element-wise. In NumPy 2.4.2 its body is the one
statement return nx.trunc(x, out=out), so the dtype is kept (integers and bool unchanged, floats
truncated), NaN and the infinities pass through, the sign of -0.0 survives, and every error is trunc's.
public override NDArray Fix(NDArray x, NDArray @out = null)
Parameters
xNDArrayThe input (not null).
outNDArrayAn array to write the result into and return, or null: it joins the ufunc's broadcast and takes a same_kind cast from the loop dtype.
Returns
- NDArray
A new array of
x's shape and dtype, orout.
Remarks
DefaultEngine's member is that statement over Truncate(NDArray, DType, NDArray, NDArray), so trunc's error texts (they name
trunc, as NumPy's fix leaks them) are fix's. np.fix calls it after its matrix rule; an override
replaces it for every array whose engine it is. Unlike a ufunc it has no where= / dtype=.
Exceptions
- TypeError
An input trunc has no loop for: text (NumPy's no-loop texts), or complex (
ufunc 'trunc' not supported for the input types).- ValueError
A read-only
out(output array is read-only).- TypeError
An
outthe result does not reach under same_kind (Cannot cast ufunc 'trunc' output from ...).- ArgumentException
An
outthe result does not broadcast into.- NullReferenceException
xis null.
FlatNonZero(NDArray)
np.flatnonzero — returns the int64 1-D array of flat indices of
non-zero elements in the raveled (C-order) input.
Equivalent to np.nonzero(np.ravel(a))[0], and returned as NumPy returns it: the single
column of nonzero's (count, 1) multi-index buffer — a unit-stride VIEW (OWNDATA false,
C- and F-contiguous) of that buffer, which the view keeps alive.
Implementation: two IL-emitted kernels keyed off the element type (GetArgwhereCountKernel(Type), GetArgwhereFlatKernel(Type)). Same SIMD popcount and bit-scan as NonZero(NDArray) / Argwhere(NDArray), except we never expand the flat indices into per-axis coords — the flat indices ARE the result. No per-dim allocation, no expand kernel, no coord carry chain.
Routing:
- 0-d → promote via
atleast_1d, recurse (truthy→[0], falsy→[]). - size == 0 → empty int64 1-D view of a
(0, 1)buffer. - Contiguous → IL count + IL flat-scan straight into the
(count, 1)buffer. - Non-contiguous → materialize via
ascontiguousarraythen same path as contig (flat indices into the C-contig buffer ARE the flat indices of the raveled non-contig input — that's what NumPy returns).
This is the cheapest of the three nonzero-family entry points: same SIMD work as NonZero(NDArray), no per-axis NDArray array allocations, no expand IL kernel invocation. Multi-dim inputs cost the same as 1-D inputs of equal size (modulo the non-contig materialization if needed).
public override NDArray<long> FlatNonZero(NDArray nd)
Parameters
ndNDArrayThe array.
Returns
Remarks
BREAKING (NumPy parity): the result used to be a separate owning array. As a view it reports
OWNDATA false and @base is the (count, 1) buffer; its strides are the dense unit stride, so
every reader that walks a C-contiguous array (take, fancy indexing, raw pointers) is unaffected.
Exceptions
- NotSupportedException
The IL kernels cannot be emitted for the dtype.
FloatPower(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise power at a MINIMUM precision of float64 (np.float_power).
float_power is the power KERNEL restricted to NumPy's two floating loops — float64
(dd->d) and complex128 (DD->D) — so it runs that kernel on a forced float
loop rather than a new one: the arithmetic is bit-identical (npy_cpow for complex, the
CRT pow for reals). It does NOT go through Power(NDArray, NDArray, DType, NDArray, NDArray), whose float loops take
NumPy's scalar-exponent fast path (x*x, sqrt, 1/x for a zero exponent step): NumPy's
float_power loop is a plain pow loop with no such branch. The two behaviours that make
float_power DIFFERENT from Power's integer loops are both properties of loop SELECTION,
handled here before computing:
- Every real input (bool/int/float16/float32/decimal/char) promotes to float64 and a complex operand to complex128 — never an integer loop. That is why float_power(2, -1) is 0.5 and does NOT raise Power's "Integers to negative integer powers are not allowed": the loop is float64, and the negative-exponent guard fires only on an INTEGER loop (see Power(NDArray, NDArray, DType, NDArray, NDArray)).
- dtype= may select ONLY float64 or complex128; any other request has no loop.
Error taxonomy and ORDER are NumPy's (probed 2.4.2): read-only out → non-bool where → dtype-has-no-loop → input cannot cast to the loop (complex ->float64) → out cannot cast from the loop → shape. Each error is raised HERE with the 'float_power' ufunc name via the shared validators; the kernel route (ExecuteBinaryOp(NDArray, NDArray, BinaryOp, NDArray, NDArray, NPTypeCode?, bool)) re-runs the identical checks (naming 'power'), but since every one already passed it never raises, so the name never leaks — except the broadcast check, whose text names no ufunc.
public override NDArray FloatPower(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe bases (any dtype; cast to the resolved float loop).
rhsNDArrayThe exponents (any dtype; cast to the resolved float loop).
dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=); only float64 or complex128 are valid.outNDArrayDestination (NumPy ufunc
out=); must be same_kind-castable from the loop dtype.whereNDArrayBoolean write-mask (NumPy ufunc
where=).
Returns
- NDArray
Bases raised to exponents at float64/complex128 precision, or
outwhen supplied.
Exceptions
- IncorrectTypeException
dtypeis neither float64 nor complex128 (no matching loop).- TypeError
A complex input cannot same_kind-cast to a requested float64 loop, or the loop dtype cannot same_kind-cast into
out.- ArgumentException
whereis non-bool;outis read-only; or the operand shapes do not broadcast together.
Floor(NDArray, DType, NDArray, NDArray)
Element-wise floor using IL-generated kernels. NumPy: for integer dtypes, floor is a no-op that preserves the input dtype.
public override NDArray Floor(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
FloorDivide(NDArray, NDArray, DType, NDArray, NDArray)
np.floor_divide — the floored quotient floor(lhs / rhs), element-wise (Python's //), on NumPy's
integer and float loops only: a bool pair promotes to the int8 loop, and complex has no loop at all.
public override NDArray FloorDivide(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe dividends (
x1).rhsNDArrayThe divisors (
x2); broadcasts againstlhs.dtypeDTypeNumPy's
dtype=: the loop the quotient is computed in (each input must reach it by a same_kind cast), or null for the NEP 50 promotion of the inputs. A bool or complex request names no loop.outNDArrayNumPy's
out=: joins the broadcast without being stretched and must take the loop dtype by a same_kind cast; returned itself.whereNDArrayNumPy's
where=: a bool mask; a False position keeps whatoutheld (and is uninitialized in a fresh result, as in NumPy).
Returns
- NDArray
The quotients:
outitself when given, else a fresh array of the loop dtype.
Exceptions
- IncorrectTypeException
A bool or complex
dtype: NumPy'sNo loop matching the specified signature and casting was found for ufunc floor_divide, raised after the out and mask checks and before any input cast or shape check (parity QA-53).- TypeError
A
dtypenaming more than a DType class; a complex operand with nodtype(ufunc 'floor_divide' not supported for the input types, …, a zero-size operand too); an inputdtypecannot take, or a loop dtypeoutcannot take, by a same_kind cast (Cannot cast ufunc 'floor_divide' input 0 / output …).- ValueError
A read-only
out(output array is read-only, checked first).- ArgumentException
A non-bool
where; an out or mask that does not broadcast, or an out that would be stretched.- IncorrectShapeException
The inputs do not broadcast together.
Fmod(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise C-style remainder (np.fmod) using IL-generated kernels.
Unlike Mod(NDArray, NDArray, DType, NDArray, NDArray) (floored — result has the sign of the DIVISOR, Python's %), fmod uses truncated division so the result has the sign of the DIVIDEND (C fmod): fmod(-7, 3) == -1 where mod(-7, 3) == 2. Routes through the same ExecuteBinaryOp(NDArray, NDArray, BinaryOp, NDArray, NDArray, NPTypeCode?, bool) machinery as Mod/FloorDivide — same NEP50 promotion (integer stays integer, bool -> int8), the scalar-only per-element kernel (EmitFmodOperation), and full out=/where=/dtype= support. NumPy's fmod loops are integer and float only: complex has no loop at all.
public override NDArray Fmod(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe dividends (
x1).rhsNDArrayThe divisors (
x2); broadcasts againstlhs.dtypeDTypeNumPy's
dtype=: the loop the remainder is computed in (each input must reach it by a same_kind cast), or null for the NEP 50 promotion of the inputs. A bool or complex request names no loop.outNDArrayNumPy's
out=: joins the broadcast without being stretched and must take the loop dtype by a same_kind cast; returned itself.whereNDArrayNumPy's
where=: a bool mask; a False position keeps whatoutheld (and is uninitialized in a fresh result, as in NumPy).
Returns
- NDArray
The truncated remainders:
outitself when given, else a fresh array of the loop dtype.
Exceptions
- IncorrectTypeException
A bool or complex
dtype: NumPy'sNo loop matching the specified signature and casting was found for ufunc fmod, raised after the out and mask checks and before any input cast or shape check (parity QA-53).- TypeError
A
dtypenaming more than a DType class; a complex operand with nodtype(ufunc 'fmod' not supported for the input types, …, a zero-size operand too); an inputdtypecannot take, or a loop dtypeoutcannot take, by a same_kind cast (Cannot cast ufunc 'fmod' input 0 / output …).- ValueError
A read-only
out(output array is read-only, checked first).- ArgumentException
A non-bool
where; an out or mask that does not broadcast, or an out that would be stretched.- IncorrectShapeException
The inputs do not broadcast together.
Frexp(NDArray, NDArray, NDArray, NDArray)
np.frexp — decompose each element into a normalized fraction and an integer power of two:
returns (mantissa, exponent) with x == mantissa * 2^exponent and the mantissa in
[0.5, 1) (0 / ±inf / NaN pass through as the mantissa). The mantissa carries the input's float
type; the exponent is ALWAYS int32 (NumPy's e->ei / f->fi / d->di loops).
public override (NDArray Mantissa, NDArray Exponent) Frexp(NDArray x, NDArray out1 = null, NDArray out2 = null, NDArray where = null)
Parameters
xNDArrayInput array. Integer/bool inputs promote to a float per NumPy's width rule (bool/int8/uint8->float16, int16/uint16/char->float32, int32+->float64); Half/Single/Double are preserved and Decimal is a NumSharp extension (computed through the double bridge). Complex is rejected.
out1NDArrayThe mantissa output, or null (a TEXT output receives the mantissas as text).
out2NDArrayThe exponent output, or null (a TEXT output receives the exponents as text).
whereNDArrayThe bool write mask, or null.
Returns
- (NDArray Lhs, NDArray Rhs)
A tuple
(Mantissa, Exponent): the mantissa in the promoted float dtype and the int32 exponent, both with the shape ofxand, when fresh, in NumPy's ufunc output layout (the K order of the input and the mask: an F input gives F outputs, a permuted one keeps its memory order; parity QA-36); the given outputs otherwise.
Remarks
Bit-identical to win-amd64 NumPy 2.4.2, including the platform C-runtime quirks its scalar
npy_frexp produces: frexp(±inf) and frexp(NaN) report exponent -1
(not 0), and a signalling NaN mantissa is quieted. See FrexpHelper(double*, double*, int*, long).
Exceptions
- IncorrectTypeException
xis complex — frexp has no complex loop (NumPy raises the same "not supported for the input types" TypeError).- TypeError
An output its loop dtype cannot be cast to under same_kind (NumPy numbers the outputs: "output 1" / "output 2").
- ArgumentException
A non-bool
where.- ValueError
A text output under
wherewhose current text does not parse into its loop dtype.- NotSupportedException
A dtype the frexp kernels do not handle.
Gcd(NDArray, NDArray, DType, NDArray, NDArray)
Execute np.gcd — element-wise greatest common divisor of the operands' magnitudes.
public override NDArray Gcd(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayFirst input array.
rhsNDArraySecond input array.
dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=); must name an integer loop, else the no-loop error.outNDArrayOutput location (NumPy ufunc
out=); the same instance is returned when supplied.whereNDArrayBoolean mask (NumPy ufunc
where=); masked-off elements keep their prior value.
Returns
- NDArray
The element-wise gcd in the promoted integer dtype.
Exceptions
- TypeError
The inputs (or an explicit
dtype) name no integer gcd loop — bool/float/complex/decimal, or a uint64+signed promotion to float64.- TypeError
An input cannot be same_kind-cast to an explicit
dtype, oroutcannot hold the result.- ArgumentException
whereis not boolean, oroutdoes not broadcast.
Geomspace(double, double, long, bool, DType, int)
NumPy's np.geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0) over real scalar ends: a
geometric progression from start to stop, computed as NumPy computes
it - both ends divided by sign(start), logspace(log10(start), log10(stop)), the ends written
back, the whole multiplied by the sign - so the ends are the arguments bit for bit and ends of opposite
signs give NaN between them (the log of a negative value).
public override NDArray Geomspace(double start, double stop, long num = 50, bool endpoint = true, DType dtype = null, int axis = 0)
Parameters
startdoubleThe first sample; not zero.
stopdoubleThe last sample when
endpointis true; not zero.numlongThe number of samples.
endpointboolWhether
stopis the last sample.dtypeDTypeThe result dtype, or null for float64. A complex dtype computes in the complex128 domain, as the Geomspace(Complex, Complex, long, bool, DType, int) overload does (its interior differs from the real path's); a text dtype is refused, as NumPy refuses it (below); any other dtype casts the float64 result (an integer dtype truncates toward zero).
axisintThe destination of NumPy's trailing moveaxis: the same values for the 1-D result, but only 0 and -1 are in range, and -1 returns NumPy's moveaxis view.
Returns
- NDArray
A new 1-D array of
numsamples. Withaxis-1 it is NumPy'smoveaxisview, which does not own its buffer, unless the final cast todtypecopies it; otherwise it owns its buffer.
Remarks
np.geomspace calls this member of the default engine. DefaultEngine's real path is NumPy's float64
result byte for byte (the sign is exactly 1 or -1, and the interior is Pow(double, double)
and Log10(double), the routines NumPy calls on win-amd64); a NaN start makes every
sample NaN, as NumPy's result *= out_sign does.
Exceptions
- ValueError
A zero end (
Geometric sequence cannot include zero, NumPy's first check), then (after the text dtypes) a negativenum(Number of samples, -1, must be non-negative.).- DTypePromotionError
A
StringDTypedtype: NumPy'sresult_type(start, stop, float(num), zeros((), dtype))finds no common DType (its text lists the four DType classes), right after the zero check.- TypeError
An
SorUdtype: the ends promote to text and NumPy'ssign(start)has no string loop (ufunc 'sign' did not contain a loop with signature matching types <class 'numpy.dtypes.StrDType'> -> None), right after the zero check.- AxisError
An
axisother than 0 or -1, checked afternum.- NotSupportedException
dtypehas no storage lane (a datetime descriptor): the final cast refuses it.
Geomspace(Complex, Complex, long, bool, DType, int)
NumPy's np.geomspace over complex scalar ends: a logarithmic spiral in the complex plane from
start to stop, the shortest of the spirals through the two points, as
NumPy computes it (both ends divided by start / |start|, a complex log-space interior, the ends written
back, the whole multiplied by that sign).
public override NDArray Geomspace(Complex start, Complex stop, long num = 50, bool endpoint = true, DType dtype = null, int axis = 0)
Parameters
startComplexThe first sample; not
0+0j(a purely imaginary value is allowed).stopComplexThe last sample when
endpointis true; not0+0j.numlongThe number of samples.
endpointboolWhether
stopis the last sample.dtypeDTypeThe result dtype, or null for complex128; a real dtype drops the imaginary parts in the final cast, as NumPy's
astypedoes; a text dtype is refused, as NumPy refuses it (below).axisintOnly 0 and -1 are in range (NumPy's trailing moveaxis of the 1-D result); -1 returns NumPy's moveaxis view.
Returns
- NDArray
A new 1-D array of
numsamples. Withaxis-1 it is NumPy'smoveaxisview, which does not own its buffer, unless the final cast todtypecopies it; otherwise it owns its buffer.
Remarks
DefaultEngine composes NumSharp's complex power (the npy_cpow port) and complex log10: its values are
within the complex-unary envelope of NumPy's (about 3 ULP) but not NumPy's bits, and the ends are
(start / sign) * sign, which complex division and multiplication need not round back to
start.
Exceptions
- ValueError
A zero end (
Geometric sequence cannot include zero), then (after the text dtypes) a negativenum.- DTypePromotionError
A
StringDTypedtype: no common DType with the complex128 ends (NumPy's text, which listsComplex128DTypetwice), right after the zero check.- TypeError
An
SorUdtype: NumPy'ssign(start)of the ends cast to text has no string loop, right after the zero check.- AxisError
An
axisother than 0 or -1, checked afternum.- NotSupportedException
dtypehas no storage lane (a datetime descriptor): the final cast refuses it.
GetStorage(DType)
Get storage described by the dtype DESCRIPTOR descr (NumPy's PyArray_NewFromDescr
entry — the descriptor becomes the array's dtype, its class supplies the storage lane). The default
routes through GetStorage(Type), which is exact for every builtin (one canonical descriptor
per lane); an engine that carries parametric descriptors overrides it.
public override UnmanagedStorage GetStorage(DType descr)
Parameters
descrDType
Returns
GetStorage(NPTypeCode)
public UnmanagedStorage GetStorage(NPTypeCode typeCode)
Parameters
typeCodeNPTypeCode
Returns
GetStorage(Type)
Get storage for given dtype.
public override UnmanagedStorage GetStorage(Type dtype)
Parameters
dtypeType
Returns
Gradient(NDArray, object[], int[], int)
DefaultEngine's Gradient(NDArray, object[], int[], int): NumPy's gradient(f, *varargs, axis=axis,
edge_order=edge_order), one fresh array per requested axis, second-order central differences inside and
first- or second-order one-sided differences at both ends.
public override np.GradientResult Gradient(NDArray f, object[] varargs, int[] axisArg = null, int edge_order = 1)
Parameters
fNDArrayThe sampled values (a plain array: the facade hands a matrix operand in as its plain view; null is refused here).
varargsobject[]NumPy's
*varargs: no entry (unit steps), one scalar for every axis, or one entry per requested axis, each a scalar step or a 1-D coordinate array as long as its axis.axisArgint[]The axes to differentiate along (negative values count from the end), or null for every axis of
f.edge_orderintThe boundary order: 1 gives first-order ends; any other value up to 2 (0 and negative values included, as NumPy reads them) gives second-order ends.
Returns
- np.GradientResult
One component per requested axis, a single array when exactly one axis was requested (NumPy's bare ndarray), none for a 0-d
fwithout an axis.
Remarks
Scoped by [NDScoped]: every slice view, coefficient array and edge temporary is released when the call
returns, and the output components are yielded to the caller through the returned
np.GradientResult (an INDArrayCarrier).
Exceptions
- ArgumentNullException
fis null.- AxisError
An axis outside
[-f.ndim, f.ndim).- ValueError
A repeated axis; a ragged list spacing (np.ndim's inhomogeneous-shape text); a coordinate array of another rank than 1 or another length than its axis;
edge_orderabove 2; an axis shorter thanedge_order + 1.- NotSupportedException
A list spacing holding None or another object, or a Python int past uint64 (NumPy's object array, a dtype NumSharp does not have).
- TypeError
A spacing count other than 0, 1 or the number of axes ("invalid number of arguments"); a bool
fwith a scalar step or first-order edges (NumPy's boolean subtract: with coordinates and second-order edges a bool input computes); a textf(NumPy's no-loop texts of the subtract or the coefficient multiply); bool coordinates (the boolean negative of the coefficients); a str or None step, refused by Python's2. * ax_dx(can't multiply sequence by non-int of type 'float',unsupported operand type(s) for *: 'float' and 'NoneType').- IndexError
The coordinates of an empty axis (NumPy's
diffx[0]of an empty diff).- DivideByZeroException
A zero step that is a Python number with second-order edges (CPython's ZeroDivisionError of
-1.5 / ax_dx:float division by zero, orcomplex division by zerofor a complex step; a NumPy-scalar or 0-d array zero step gives inf / nan instead, as in NumPy); a decimal input or step divided by zero (decimal has no inf).- OverflowException
A Python int step past the float range (a
BigInteger: CPython'sint too large to convert to floatin2. * ax_dx); a decimal result past decimal's range.
Greater(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray Greater(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
GreaterEqual(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray GreaterEqual(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Hamming(double)
NumPy's np.hamming(M): the Hamming window of M points, the raised cosine
0.54 + 0.46cos(pin/(M-1)) over n = arange(1-M, M, 2) - its ends stay at 0.08, not zero.
public override NDArray Hamming(double M)
Parameters
MdoubleThe number of points, NumPy's
_FloatLike_co(the length and the guards of Bartlett(double)).
Returns
- NDArray
A new 1-D float64 array.
Remarks
DefaultEngine's fused pass keeps NumPy's evaluation order; np.hamming calls the default engine's
member.
Exceptions
- ValueError
Mis NaN, +infinity or too large for arange to size.- OutOfMemoryException
A finite count whose window does not fit in memory.
Hanning(double)
NumPy's np.hanning(M): the Hann window of M points, the raised cosine
0.5 + 0.5cos(pin/(M-1)) over n = arange(1-M, M, 2) - zero at both ends.
public override NDArray Hanning(double M)
Parameters
MdoubleThe number of points, NumPy's
_FloatLike_co(the length and the guards of Bartlett(double)).
Returns
- NDArray
A new 1-D float64 array.
Remarks
DefaultEngine's fused pass keeps NumPy's evaluation order; np.hanning calls the default engine's
member.
Exceptions
- ValueError
Mis NaN, +infinity or too large for arange to size.- OutOfMemoryException
A finite count whose window does not fit in memory.
Heaviside(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray Heaviside(NDArray x1, NDArray x2, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Histogram(NDArray, object, (double, double)?, bool, NDArray)
DefaultEngine's Histogram(NDArray, object, (double, double)?, bool, NDArray): HistogramFunction(NDArray, object, (double, double)?, bool, NDArray) under this member's scope.
public override np.HistogramResult Histogram(NDArray a, object bins, (double, double)? range = null, bool density = false, NDArray weights = null)
Parameters
aNDArrayThe data.
binsobjectAn int, an estimator name, or an NDArray (0-d count or 1-D edges).
range(double, double)?The optional outer edges.
densityboolWhether to normalize to a density.
weightsNDArrayThe optional weights.
Returns
- np.HistogramResult
The counts (or summed weights, or density) and the edges.
Remarks
Owns its scope (a public entry since the plan's phase PE; np.histogram's scope covered the body before): the raveled input and weights, the bin indices, the counting scratch and the density quotients are reclaimed; only the histogram and its edges leave.
Exceptions
- Exception
The errors of HistogramFunction(NDArray, object, (double, double)?, bool, NDArray), in its order.
Histogram2d(NDArray, NDArray, object, (double, double)?[], bool, NDArray)
DefaultEngine's Histogram2d(NDArray, NDArray, object, (double, double)?[], bool, NDArray): Histogram2dFunction(NDArray, NDArray, object, (double, double)?[], bool, NDArray) under this member's scope.
public override np.Histogram2dResult Histogram2d(NDArray x, NDArray y, object bins, (double, double)?[] range = null, bool density = false, NDArray weights = null)
Parameters
xNDArrayThe x coordinates.
yNDArrayThe y coordinates.
binsobjectThe polymorphic bin argument.
range(double, double)?[]Optional per-dimension outer edges.
densityboolWhen true, return the probability density.
weightsNDArrayOptional per-point weights.
Returns
- np.Histogram2dResult
The 2-D histogram and its two edge arrays.
Remarks
Owns its scope (a public entry since the plan's phase PE; the body was [NDScopedCovered] under
np.histogram2d's scope): the stacked column and every binning temporary are reclaimed.
Exceptions
- Exception
The errors of Histogram2dFunction(NDArray, NDArray, object, (double, double)?[], bool, NDArray), in its order.
HistogramBinEdges(NDArray, object, (double, double)?, NDArray)
DefaultEngine's HistogramBinEdges(NDArray, object, (double, double)?, NDArray), histogram_bin_edges: NumPy's
_ravel_and_check_weights then _get_bin_edges. Text data or text
edges are answered inside those two steps, at the statement where NumPy's code first touches them (see
GetBinEdges(NDArray, object, (double, double)?, NDArray)): explicit edges never read the data, so a text a with numeric
edges returns the edges.
public override NDArray HistogramBinEdges(NDArray a, object bins, (double, double)? range = null, NDArray weights = null)
Parameters
aNDArrayThe data.
binsobjectAn int, an estimator name, or an NDArray (0-d count or 1-D edges).
range(double, double)?The optional outer edges.
weightsNDArrayThe optional weights (shape-checked only).
Returns
- NDArray
The bin edges.
Remarks
Owns its scope (a public entry since the plan's phase PE; np.histogram_bin_edges's scope covered it before): the raveled input, the weights' ravel and every estimator / linspace intermediate are reclaimed; an explicit edge array the caller passed comes back as that array.
Exceptions
- ValueError
See GetBinEdges(NDArray, object, (double, double)?, NDArray); a weights shape that differs from
a's.- TypeError
See GetBinEdges(NDArray, object, (double, double)?, NDArray).
Histogramdd(NDArray[], object, (double, double)?[], bool, NDArray)
DefaultEngine's Histogramdd(NDArray[], object, (double, double)?[], bool, NDArray): HistogramddFunction(NDArray[], object, (double, double)?[], bool, NDArray) under this member's scope.
public override np.HistogramddResult Histogramdd(NDArray[] sample, object bins, (double, double)?[] range = null, bool density = false, NDArray weights = null)
Parameters
sampleNDArray[]The D coordinate columns (each 1-D, length N): the facades'
SampleColumns/ColumnsFromSequenceform of NumPy's sample.binsobjectThe bin spec (int, int[], NDArray, NDArray[], or object[]).
range(double, double)?[]Optional per-dimension outer edges.
densityboolWhen true, normalize to a probability density.
weightsNDArrayOptional per-point weights.
Returns
- np.HistogramddResult
The histogram and its per-dimension edges.
Remarks
Owns its scope (a public entry since the plan's phase PE; the body was [NDScopedCovered] under
np.histogramdd's scope): every binning temporary is reclaimed, the histogram and the edges leave.
Exceptions
- Exception
The errors of HistogramddFunction(NDArray[], object, (double, double)?[], bool, NDArray), in its order.
Hypot(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray Hypot(NDArray x1, NDArray x2, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
I0(NDArray)
NumPy's np.i0(x), the modified Bessel function of the first kind, order 0: astype(float) for a
dtype that is not float, abs, then the cephes Chebyshev series (|x| <= 8 and above), each
float width computed in its own precision as NumPy's ufunc chain computes it.
public override NDArray I0(NDArray x)
Parameters
xNDArrayThe input, any dtype but complex, any layout (not null).
Returns
- NDArray
The values: float16 / float32 / float64 kept, float64 for bool, integers, char and parsed text, decimal for decimal (the double bridge).
Remarks
DefaultEngine runs the series per element in one fused np.evaluate pass.
Exceptions
- ArgumentNullException
xis null.- IncorrectTypeException
A complex operand (NumPy's
i0 not supported for complex values).- ValueError
Text that does not parse as a float (NumPy's
astype(float)).- OverflowException
A decimal result past the decimal range (
|x|above about 72).
Interp(NDArray, NDArray, NDArray, object, object, double?)
NumPy's np.interp(x, xp, fp, left=None, right=None, period=None): the piecewise-linear interpolant
through the points (xp, fp), evaluated at x. NumPy picks the loop from fp alone (complex128 for a complex fp,
float64 otherwise); with a period, x and xp are taken modulo it and the fill values are ignored.
public override NDArray Interp(NDArray x, NDArray xp, NDArray fp, object left = null, object right = null, double? period = null)
Parameters
xNDArrayThe coordinates to evaluate at, any shape.
xpNDArrayThe sample points, 1-D, increasing unless a period is given (not checked: NumPy's loop answers other points deterministically).
fpNDArrayThe sample values, 1-D, as many as xp.
leftobjectThe value below
xp[0], NumPy's Python object: null (None, meaningfp[0]), a double (a float) or a Complex (a complex, which the real loop refuses).rightobjectThe value above
xp[-1], asleft(null meansfp[-1]).perioddouble?The period of the x-coordinates, or null; it must not be zero.
Returns
- NDArray
A new array of x's shape (0-d for a 0-d x): complex128 for a complex fp, float64 otherwise.
Exceptions
- ArgumentException
leftorrightis neither null, a double nor a Complex.- NullReferenceException
An operand is null.
- ValueError
fp or xp not 1-D (
object too deep for desired array/object of too small depth for desired array), empty sample points, lengths that differ, a zero period; with a period, points that are not 1-D (Data points must be 1-D sequences) or text that does not parse as a float.- InvalidCastException
Without a period, an operand that does not cast 'safely' to the loop's dtype (NumPy's TypeError text).
- TypeError
A real fp, no period and a complex fill value (
must be real number, not complex), raised after the operand and length checks.
Invert(NDArray, DType, NDArray, NDArray)
Element-wise bitwise NOT using IL-generated kernels. For integers: computes ~x (ones complement). For booleans: computes logical NOT (NumPy behavior).
public override NDArray Invert(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
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 override NDArray<bool> IsClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
Parameters
aNDArrayInput array to compare with b
bNDArrayInput array to compare with a.
rtoldoubleThe relative tolerance parameter(see Notes)
atoldoubleThe absolute tolerance parameter(see Notes)
equal_nanboolWhether to compare NaN's as equal. If True, NaN's in
awill be considered equal to NaN's inbin the output array.
Returns
- NDArray<bool>
Returns a boolean array of where
aandbare equal within the given tolerance.If bothaandbare scalars, returns a single boolean value.
Remarks
Scoped by [NDScoped]: the formula builds a dozen transient arrays (and up to two
dtype-promoted copies of the operands), and the woven scope releases every one of them on return,
exceptions included, so a tight isclose/allclose loop does not pile them up for the finalizer. The
returned typed array survives: the weaver yields it, and it holds its own reference on the buffer it
shares with the last temporary.
A C# number literal operand (NumSharp.NDArray.WasPythonLiteral) is NumPy's Python scalar and stays weak
through the formula — isclose(float32_array, 0.1) compares in float32, with the tolerance
atol + rtol * abs(0.1) computed as Python arithmetic. Any other 0-d operand is a NumPy scalar or 0-d
array, which NEP 50 promotes (isclose(float32_array, np.float64(0.1)) computes in float64, as NumPy
does).
Exceptions
- DTypePromotionError
bholds strings (NumPy's promotion refusal of text with a Python float).- TypeError
Only
aholds strings (subtract's no-loop text).
IsFinite(NDArray, DType, NDArray, NDArray)
Test element-wise for finiteness (not infinity and not NaN). Returns True for all integer types (always finite), and checks float/double values.
public override NDArray IsFinite(NDArray a, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
- NDArray
Boolean array where True indicates the element is finite
Remarks
NumPy behavior:
- Float/Double: True if not infinity and not NaN
- Integer types: Always True (integers cannot be Inf or NaN)
- Empty arrays: Returns empty bool array
IsInf(NDArray, DType, NDArray, NDArray)
Test element-wise for positive or negative infinity.
public override NDArray IsInf(NDArray a, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
- NDArray
Boolean array where True indicates the element is +/-Inf
Remarks
NumPy behavior:
- Float/Double/Half: True if value is +Inf or -Inf
- Complex: True if either real or imaginary part is Inf
- Integer types: Always False (integers cannot be Inf)
- NaN: Returns False (NaN is not infinity)
- Empty arrays: Returns empty bool array
IsNan(NDArray, DType, NDArray, NDArray)
Test element-wise for NaN (Not a Number). Returns False for all integer types (cannot be NaN), and checks float/double values.
public override NDArray IsNan(NDArray a, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
- NDArray
Boolean array where True indicates the element is NaN
Remarks
NumPy behavior:
- Float/Double: True if value is NaN
- Integer types: Always False (integers cannot be NaN)
- Infinity: Returns False (Inf is not NaN)
- Empty arrays: Returns empty bool array
IsNegInf(NDArray, DType, NDArray, NDArray)
Test element-wise for negative infinity (np.isneginf). Result is a bool array where True indicates the element is -Inf.
public override NDArray IsNegInf(NDArray a, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Remarks
NumPy behavior (numpy/lib/_ufunclike_impl.py, isinf(x) & signbit(x)):
- Float/Double/Half: True iff value is -Inf (NaN, +Inf, finite -> False)
- Integer/bool types: Always False
- Complex: refused here, first (as IsPosInf).
Fused single-pass kernel computing
x == -inf.
IsPosInf(NDArray, DType, NDArray, NDArray)
Test element-wise for positive infinity (np.isposinf). Result is a bool array where True indicates the element is +Inf.
public override NDArray IsPosInf(NDArray a, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Remarks
NumPy behavior (numpy/lib/_ufunclike_impl.py, isinf(x) & ~signbit(x)):
- Float/Double/Half: True iff value is +Inf (NaN, -Inf, finite -> False)
- Integer/bool types: Always False (integers cannot be Inf)
- Complex: refused here, first (TypeError, NumPy's signbit is ambiguous on complex).
The fused kernel computes
x == +infin one pass (single-pass SIMD for Single/Double, scalar for Half; cf. NumPy's four-pass isinf/signbit/and).
Iscomplex(NDArray)
NumPy's np.iscomplex(x): for a complex input imag(x) != 0 (True where an element's imaginary
part is not zero: NaN and inf count, -0.0 does not), for any other dtype all False.
public override NDArray Iscomplex(NDArray a)
Parameters
aNDArrayThe input.
Returns
- NDArray
A bool array of
a's shape: for a dtype that is not complex, NumPy'szeros(shape, bool)[()], a view of a fresh buffer (OWNDATA false; the 0-d array itself for a 0-d input).
Exceptions
- ArgumentNullException
ais null.
Isin(NDArray, NDArray, bool, bool, string)
DefaultEngine's Isin(NDArray, NDArray, bool, bool, string): isin(element, test_elements, assume_unique, invert,
kind), the kind check, then the StringDType route, the text route or the numeric
membership, the answer shaped like element.
public override NDArray Isin(NDArray element, NDArray test_elements, bool assume_unique = false, bool invert = false, string kind = null)
Parameters
elementNDArrayThe tested values (not null; the result has their shape).
test_elementsNDArrayThe set (not null; flattened).
assume_uniqueboolNumPy's speed hint: where NumPy takes its sort path, the
np.uniquecalls are skipped, so repeated values get NumPy's answer for them (an element is flagged when an equal value follows it in the elements or lies in the set); the table method and the loop path ignore it.invertboolWhether the answer is
element not in test_elements.kindstringThe algorithm name: null (automatic),
"sort"or"table".
Returns
- NDArray
A bool array of
element's shape: a view of a fresh 1-D answer, as NumPy's reshape returns it.
Remarks
A public entry point since the plan's phase PE, so it owns its scope (it was [NDScopedCovered]
under np.isin's): the ravels, the promoted casts and the sort / table / hash work arrays are released here,
the answer's view escapes.
Exceptions
- ValueError
An unknown
kind(Invalid kind: 'x'. Please use None, 'sort' or 'table'.),kind='table'for an array that is not boolean or integer, orkind='table'over a set whose range is2**63 - 1or more (Maximum allowed dimension exceeded).- InvalidOperationException
kind='table'with a set whose range exceeds its dtype's maximum (NumPy's RuntimeError text).- UnicodeDecodeError
The text route's sort path decodes
Stext holding a byte that is not ASCII besideUtext.- NotSupportedException
A
StringDTypeset whose NA object is a sequence, held by an NA cell (see IsinVString(NDArray, NDArray, bool, string)).
Isreal(NDArray)
NumPy's np.isreal(x), imag(x) == 0: True where an element's imaginary part is zero (a -0.0
too); every element of a dtype that is not complex is real, and no element of text is (NumPy's
'' == 0 has no loop and answers False).
public override NDArray Isreal(NDArray a)
Parameters
aNDArrayThe input.
Returns
- NDArray
A new bool array of
a's shape (C order whatever its layout).
Exceptions
- ArgumentNullException
ais null.
Kaiser(double, double)
NumPy's np.kaiser(M, beta): the Kaiser window of M points,
i0(beta * sqrt(1 - ((n - alpha)/alpha)**2)) / i0(beta) over n = arange(0, M) with
alpha = (M - 1)/2.
public override NDArray Kaiser(double M, double beta)
Parameters
MdoubleThe number of points, NumPy's
_FloatLike_co. Unlike the cosine windows kaiser has noM < 1guard:arange(0, M)is empty forM <= 0but one point for0 < M < 1, and onlyM == 1is special-cased (ones(1), which avoidsalpha == 0). A fractional count past a whole one leaves a trailing NaN where|(n - alpha)/alpha| > 1, as in NumPy.betadoubleThe shape parameter: 0 is a rectangular window and a larger value a narrower one (5 is close to a Hamming window, 6 to a Hann window, 8.6 to a Blackman window). Any double is taken; past about 709.78, where the series'
expoverflows,i0(beta)is infinite, so the window is NaN where its numerator overflows too (inf / inf) and zero elsewhere.
Returns
- NDArray
A new 1-D float64 array.
Remarks
DefaultEngine runs the cephes i0 series NumPy's np.i0 runs once per element of a fused pass, and takes
i0(beta) from its own I0(NDArray) (NumPy's i0(float(beta))), so the values are NumPy's bit for
bit where the host's exp and sqrt are. np.kaiser calls the default engine's member.
Exceptions
- ValueError
Mis NaN, or an infinity or too large for arange to size.- OutOfMemoryException
A finite count whose window does not fit in memory.
Kron(NDArray, NDArray)
NumPy's np.kron(a, b), the whole call: the Kronecker product, a composite array of blocks of
b scaled by the elements of a. For a.shape = (r0, ..., rN) and
b.shape = (s0, ..., sN) the result has shape (r0s0, ..., rNsN) and
kron(a, b)[k0, ..., kN] = a[i0, ..., iN] * b[j0, ..., jN] with kt = it*st + jt.
public override NDArray Kron(NDArray a, NDArray b)
Parameters
aNDArrayThe first operand.
bNDArrayThe second operand. The operand of smaller rank is read as if prepended with length-1 axes (NumPy's
ndmin).
Returns
- NDArray
A fresh, writeable, C-contiguous array in np.multiply's result dtype (NEP 50); with a 0-d operand the element-wise product, the degenerate Kronecker product.
Remarks
New in 0.80.0 (the np-layer dtype plan): the public np.kron applies the numpy.matrix and
numpy.char.chararray rules and calls this.
Exceptions
- NullReferenceException
aorbis null.- TypeError
Operands np.multiply refuses (text has no multiply loop: NumPy's ufunc refusal).
Lcm(NDArray, NDArray, DType, NDArray, NDArray)
Execute np.lcm — element-wise lowest common multiple of the operands' magnitudes
(0 when either is 0; the product wraps the dtype on overflow, matching NumPy).
public override NDArray Lcm(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayFirst input array.
rhsNDArraySecond input array.
dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=); must name an integer loop, else the no-loop error.outNDArrayOutput location (NumPy ufunc
out=); the same instance is returned when supplied.whereNDArrayBoolean mask (NumPy ufunc
where=); masked-off elements keep their prior value.
Returns
- NDArray
The element-wise lcm in the promoted integer dtype.
Exceptions
- TypeError
The inputs (or an explicit
dtype) name no integer lcm loop — bool/float/complex/decimal, or a uint64+signed promotion to float64.- TypeError
An input cannot be same_kind-cast to an explicit
dtype, oroutcannot hold the result.- ArgumentException
whereis not boolean, oroutdoes not broadcast.
Ldexp(NDArray, NDArray, NDArray, NDArray)
np.ldexp — compose x1 * 2^x2 element-wise (the inverse of Frexp(NDArray, NDArray, NDArray, NDArray)).
x1 is the mantissa/base (float family; integer/bool promote per NumPy's
width rule) and x2 is an INTEGER exponent — the two do NOT promote to a
common dtype (NumPy's ei->e / fi->f / di->d loops keep the exponent an int), so the
result dtype is purely x1's float tier.
public override NDArray Ldexp(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null)
Parameters
x1NDArrayMantissa/base values. bool/int8/uint8->float16, int16/uint16/char->float32, int32+->float64; Half/Single/Double preserved; Decimal is a NumSharp extension (double bridge). Complex is rejected.
x2NDArrayInteger exponents (bool, int8/16/32/64, uint8/16/32, or char). An exponent outside the C-int range is clamped, so a huge magnitude overflows to ±inf / underflows to ±0 exactly as NumPy's int64 loop does. uint64, float and complex exponents are rejected.
outNDArraywhereNDArray
Returns
- NDArray
x1 * 2^x2broadcast to the common shape, inx1's float tier: a fresh result in NumPy's ufunc output layout (the operands' K order: F inputs give F, a permuted input keeps its memory order; parity QA-36), oroutwritten.
Remarks
Bit-identical to win-amd64 NumPy 2.4.2 (ScaleB(double, int) IS ldexp).
Exceptions
- IncorrectTypeException
x1is complex, orx2is not a supported integer exponent (uint64/float/complex) — NumPy raises the same "not supported for the input types" TypeError.
LeftShift(NDArray, NDArray, DType, NDArray, NDArray)
Bitwise left shift (x1 << x2), with the ufunc out=/where=/dtype=
parameters. See ExecuteShift(NDArray, NDArray, bool, DType, NDArray, NDArray) for the loop-selection and error contract.
public override NDArray LeftShift(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayValue operand (integer/bool/char).
rhsNDArrayShift-count operand (integer/bool/char).
dtypeDTypeOptional loop dtype override; must be an integer/char loop (a float/complex/decimal request raises NumPy's no-loop TypeError).
outNDArraywhereNDArrayOptional bool write mask.
Returns
- NDArray
The shifted result, or
@outwhen provided.
Less(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray Less(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
LessEqual(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray LessEqual(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
LexSort(NDArray[], int)
NumPy's np.lexsort(keys, axis) (PyArray_LexSort), the whole call: the int64 indices that sort
by several keys at once, the LAST key primary and each earlier one breaking the ties of the keys after it
(a stable sort per key).
public override NDArray LexSort(NDArray[] keys, int axis = -1)
Parameters
keysNDArray[]The keys, every one of the same shape (any dtype; text sorts by code points). The public
np.lexsort(NDArray, int)splits an array along its first axis into this list.axisintThe axis sorted along (negative counts from the end). Keys of rank 0 accept 0 and -1 (NumPy's backwards compatibility) and answer the 0-d
0.
Returns
- NDArray
A fresh int64 array of the keys' shape (zeros for keys of at most one element).
Remarks
New in 0.80.0 (the np-layer dtype plan, phase PE, E5): the public np.lexsort applies its class
boundaries and calls this.
Exceptions
- TypeError
keysis null or empty (need sequence of keys with len > 0 in lexsort).- ArgumentNullException
A key is null.
- ValueError
The keys differ in shape (
all keys need to be the same shape).- AxisError
The axis is out of range.
Linspace(double, double, long, bool, DType, string)
NumPy's np.linspace(start, stop, num, endpoint=True, dtype=None, *, device=None) over scalar ends:
num evenly spaced samples from start to stop. With
endpoint the step is (stop - start) / (num - 1) and the last sample is
stop itself (NumPy overwrites y[-1], so no rounding of start + i * step
reaches it); without it the step is (stop - start) / num and stop is not a sample.
public override NDArray Linspace(double start, double stop, long num, bool endpoint = true, DType dtype = null, string device = null)
Parameters
startdoubleThe first sample.
stopdoubleThe last sample when
endpointis true; otherwise the bound the samples approach.numlongThe number of samples.
endpointboolWhether
stopis the last sample.dtypeDTypeThe result dtype, or null for float64. The samples are computed in float64 and then converted: an integer dtype FLOORS them (NumPy 1.20+'s
_nx.floor(y, out=y)before the cast, not a truncation toward zero; char follows uint16), bool issample != 0, complex128 takes the sample as its real part, and a text dtype (S,U,StringDType) formats them as NumPy'sastypedoes ('0.25', cut to the width of a fixed-width dtype).devicestringNumPy's Array-API
device=: only"cpu"and null are accepted. NumPy reads it after the sample count (it is the ramp's np.arange that checks it), so a negative count is reported first.
Returns
- NDArray
A new 1-D array of
numsamples. A float64 result of two or more samples, or of one sample withendpointfalse, does not own its buffer (OWNDATAfalse: NumPy returns its in-place ramp throughastype(copy=False), which is a view); every other result owns its buffer.
Remarks
np.linspace calls this member of the default engine. An override must keep NumPy's arithmetic, which
code ported from NumPy reads: the floor of the integer dtypes, the exact last sample, one sample as
0 * (stop - start) + start (a NaN when an end is infinite or NaN, +0.0 for a start of -0.0), and a
step that underflows to zero replaced by (i / div) * (stop - start) + start (NumPy's gh-5437 branch,
which keeps a subnormal range spread out).
Exceptions
- ValueError
A negative
num(Number of samples, -1, must be non-negative.), NumPy's first check: before the device and before anything is allocated.- ValueError
deviceis neither null nor"cpu"(NumPy'sDevice not understood. Only "cpu" is allowed, but received: ...).- NotSupportedException
dtypehas no storage lane (a datetime descriptor).
Log(NDArray, DType, NDArray, NDArray)
Element-wise natural logarithm using IL-generated kernels.
public override NDArray Log(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Log10(NDArray, DType, NDArray, NDArray)
Element-wise log base 10 using IL-generated kernels.
public override NDArray Log10(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Log1p(NDArray, DType, NDArray, NDArray)
Element-wise log(1 + x) using IL-generated kernels.
public override NDArray Log1p(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Log2(NDArray, DType, NDArray, NDArray)
Element-wise log base 2 using IL-generated kernels.
public override NDArray Log2(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
LogAddExp(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray LogAddExp(NDArray x1, NDArray x2, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
LogAddExp2(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray LogAddExp2(NDArray x1, NDArray x2, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
LogicalAnd(NDArray, NDArray, DType, NDArray, NDArray)
NumPy's logical_and ufunc, the whole call: the element-wise AND of the operands' truth values, NumPy's
logical_and(x1, x2, /, out=None, *, where=True, dtype=None). A text operand reads true when
non-empty (NumPy's string loop computes over the operands' truth arrays).
public override NDArray LogicalAnd(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe first operand (any dtype, text included; any layout).
rhsNDArrayThe second operand; broadcasts against
lhs.dtypeDTypeThe
dtype=loop request: the logical loops are bool-output only, so it validates and selects nothing; a non-bool request raises NumPy's no-loop error.outNDArrayA location into which the result is stored (any numeric dtype: bool casts same_kind to all, True to 1), or null; returned itself when given.
whereNDArrayA bool mask: only its true elements are computed; masked-off slots of
outkeep their contents (of a fresh result they are unspecified, as in NumPy).
Returns
- NDArray
A bool array of the broadcast shape, or
out.
Remarks
NumPy's loop is C (@TYPE@_logical_and), so the call is an engine member, as every ufunc's is; the
numpy.matrix and numpy.char.chararray answers stay with np.logical_and's woven subclass path.
Exceptions
- IncorrectTypeException
A non-bool
dtype(No loop matching the specified signature and casting was found for ufunc logical_and).- TypeError
A detailed or non-legacy
dtypedescriptor, or a text call NumPy's string loop refuses.- SystemError
A
Uoperand holding a unit above U+10FFFF (NumPy's bool cast of the text).- ValueError
A read-only
out.- TypeError
An
outthe bool result cannot be cast into.- ArgumentException
A
wherethat is not bool, or a mask oroutthat does not broadcast with the operands (NumPy's ValueError text).- IncorrectShapeException
Operands that do not broadcast together.
LogicalNot(NDArray, DType, NDArray, NDArray)
NumPy's logical_not ufunc, the whole call: the element-wise NOT of the operand's truth value (zero is
True, nonzero False; a NaN is truthy), NumPy's logical_not(x, /, out=None, *, where=True, dtype=None).
Unlike the binary three it has no string loop in NumPy, so a text operand is refused.
public override NDArray LogicalNot(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
ndNDArrayThe operand (any numeric dtype; any layout).
dtypeDTypeThe
dtype=loop request: validate-only (bool loops); a non-bool request raises NumPy's no-loop error.outNDArrayA location into which the result is stored (any numeric dtype), or null; returned itself when given.
whereNDArrayA bool mask: only its true elements are computed; masked-off slots of
outkeep their contents.
Returns
- NDArray
A bool array of the operand's shape (broadcast with the mask and
out), orout.
Exceptions
- IncorrectTypeException
A non-bool
dtype(No loop matching the specified signature and casting was found for ufunc logical_not), for a text operand too: the loops are bool-output only.- TypeError
A text operand without
dtype(NumPy's no-loop refusal; a StringDType operand's text names the requested output class), or a detailed or non-legacydtypedescriptor.- ValueError
A read-only
out.- TypeError
An
outthe bool result cannot be cast into, or a fixed-width text operand underdtype=bool(the input cast NumPy refuses, its UFuncTypeError text).- ArgumentException
A
wherethat is not bool, or a mask oroutthat does not broadcast with the operand (NumPy's ValueError text).
LogicalOr(NDArray, NDArray, DType, NDArray, NDArray)
NumPy's logical_or ufunc, the whole call: the element-wise OR of the operands' truth values, NumPy's
logical_or(x1, x2, /, out=None, *, where=True, dtype=None). A text operand reads true when non-empty.
public override NDArray LogicalOr(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe first operand (any dtype, text included; any layout).
rhsNDArrayThe second operand; broadcasts against
lhs.dtypeDTypeThe
dtype=loop request: validate-only (bool loops); a non-bool request raises NumPy's no-loop error.outNDArrayA location into which the result is stored (any numeric dtype), or null; returned itself when given.
whereNDArrayA bool mask: only its true elements are computed; masked-off slots of
outkeep their contents.
Returns
- NDArray
A bool array of the broadcast shape, or
out.
Exceptions
- IncorrectTypeException
A non-bool
dtype(No loop matching the specified signature and casting was found for ufunc logical_or).- TypeError
A detailed or non-legacy
dtypedescriptor, or a text call NumPy's string loop refuses.- SystemError
A
Uoperand holding a unit above U+10FFFF.- ValueError
A read-only
out.- TypeError
An
outthe bool result cannot be cast into.- ArgumentException
A
wherethat is not bool, or a mask oroutthat does not broadcast with the operands (NumPy's ValueError text).- IncorrectShapeException
Operands that do not broadcast together.
LogicalXor(NDArray, NDArray, DType, NDArray, NDArray)
NumPy's logical_xor ufunc, the whole call: the element-wise XOR of the operands' truth values, NumPy's
logical_xor(x1, x2, /, out=None, *, where=True, dtype=None). A text operand reads true when non-empty.
public override NDArray LogicalXor(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe first operand (any dtype, text included; any layout).
rhsNDArrayThe second operand; broadcasts against
lhs.dtypeDTypeThe
dtype=loop request: validate-only (bool loops); a non-bool request raises NumPy's no-loop error.outNDArrayA location into which the result is stored (any numeric dtype), or null; returned itself when given.
whereNDArrayA bool mask: only its true elements are computed; masked-off slots of
outkeep their contents.
Returns
- NDArray
A bool array of the broadcast shape, or
out.
Exceptions
- IncorrectTypeException
A non-bool
dtype(No loop matching the specified signature and casting was found for ufunc logical_xor).- TypeError
A detailed or non-legacy
dtypedescriptor, or a text call NumPy's string loop refuses.- SystemError
A
Uoperand holding a unit above U+10FFFF.- ValueError
A read-only
out.- TypeError
An
outthe bool result cannot be cast into.- ArgumentException
A
wherethat is not bool, or a mask oroutthat does not broadcast with the operands (NumPy's ValueError text).- IncorrectShapeException
Operands that do not broadcast together.
Logspace(double, double, long, bool, double, DType, int)
NumPy's np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0) over scalar
ends: base ** linspace(start, stop, num, endpoint), computed in float64 and only then cast to
dtype (computing in a narrower dtype would round differently).
public override NDArray Logspace(double start, double stop, long num = 50, bool endpoint = true, double @base = 10, DType dtype = null, int axis = 0)
Parameters
startdoublebase ** startis the first sample.stopdoublebase ** stopis the last sample whenendpointis true.numlongThe number of samples.
endpointboolWhether
base ** stopis the last sample (its exponent isstopitself, as NumPy's linspace writesy[-1] = stop).basedoubleThe base of the log space. A negative base with a fractional exponent gives NaN, as NumPy's real power does.
dtypeDTypeThe result dtype, or null for float64. The float64 powers are cast, so an integer dtype TRUNCATES toward zero (unlike Linspace(double, double, long, bool, DType, string), which floors) and a text dtype formats them.
axisintThe destination of NumPy's trailing
moveaxis(y, 0, axis): a no-op for the 1-D result of scalar ends, but only 0 and -1 are in range.
Returns
- NDArray
A new 1-D array of
numsamples that owns its buffer.
Remarks
np.logspace calls this member of the default engine. DefaultEngine fills the powers in one pass with
Pow(double, double), the CRT routine NumPy's npy_pow calls on win-amd64, so
its float64 result is NumPy's byte for byte; an override that computes the powers otherwise loses that.
Exceptions
- ValueError
A negative
num(Number of samples, -1, must be non-negative.), checked beforeaxis.- AxisError
An
axisother than 0 or -1 (destination: axis 1 is out of bounds for array of dimension 1).- NotSupportedException
dtypehas no storage lane (a datetime descriptor): the final cast refuses it.
Matmul(NDArray, NDArray)
Matrix product matching NumPy's matmul gufunc with signature
(n?,k),(k,m?)->(n?,m?) — the ? dims are the optional ones inserted for a
1-D operand:
- both 1-D → inner product (0-D scalar);
- 1-D × 2-D → the 1-D side is prepended a 1, then that dim is removed;
- 2-D × 1-D → the 1-D side is appended a 1, then that dim is removed;
- ≥3-D → batched: the leading "stack" dims broadcast and a 2-D matmul runs on the
trailing
[n,k]·[k,m]of each batch element.
0-D (scalar) operands are rejected (NumPy raises — use * or np.dot).
public override NDArray Matmul(NDArray lhs, NDArray rhs)
Parameters
Returns
Remarks
Matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char)
NumPy's np.matmul(x1, x2, out, axes, axis, keepdims, dtype, casting, order) — the gufunc
(n?,k),(k,m?)->(n?,m?) — the whole call: the argument checks (the order and casting names,
axis with axes, the dtype= class, the loop refusal of text, keepdims /
axis, a read-only out=), the core axes axes= names, the loop dtype= selects (each
input's cast checked under casting), the product (Matmul(NDArray, NDArray)),
the result's core axes placed, the layout order asks for, and the delivery into
out (its cast and its core dimensions checked first).
public override NDArray Matmul(NDArray x1, NDArray x2, NDArray @out, int[][] axes, int? axis, bool? keepdims, DType dtype, string casting, char order)
Parameters
x1NDArrayThe left operand, at least 1-D: a 1-D operand drops its optional core dimension
n?.x2NDArrayThe right operand, at least 1-D: a 1-D operand drops
m?.outNDArrayWhere the product is delivered, or null. Any layout; takes a cast of the product under
casting; its extra leading loop axes receive copies of the product.axesint[][]The axes carrying each operand's core dimensions (
{x1, x2, out}: two for an operand of two or more dimensions, one for a 1-D one; all three entries are required), or null.axisint?Refused for any value (matmul's three core dimensions are distinct), or null.
keepdimsbool?Refused for any value, false included (the output has core dimensions); null when the caller did not pass it.
dtypeDTypeThe loop dtype, or null (the product's own).
castingstringThe rule the input-to-loop and product-to-out casts are checked under:
no,equiv,safe,same_kindorunsafe.ordercharThe result's layout:
'C','F','A'(F when both inputs are F-contiguous, else C) or'K'(the product's own).
Returns
- NDArray
The product, or
outitself holding it.
Remarks
New in 0.80.0 (the np-layer dtype plan, P2): the public np.matmul calls this (the ufunc
mechanism answers for a subclass operand); Matmul(NDArray, NDArray) stays the product kernel
the call ends in.
Exceptions
- ValueError
An order or casting name NumPy refuses; an
axes=list without three entries, or with a repeated axis; a read-onlyout; anoutwhose core dimension differs from the product's, or whose loop axes the product does not broadcast into.- TypeError
axiswithaxes; adtypewith details beyond its class; text operands or a textdtype(no matmul loop);keepdimsoraxisgiven.- AxisError
An
axes=entry whose length is not its operand's core rank, or an axis out of range.- TypeError
A cast
castingrefuses (NumPy's UFuncTypeError text).- IncorrectShapeException
Core dimensions that do not match, or loop axes that do not broadcast (the product's texts).
- InvalidOperationException
A 0-d operand.
- NotSupportedException
dtypeis a class without storage yet.- NullReferenceException
x2is null.
Matvec(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char)
NumPy's np.matvec(x1, x2, out, axes, axis, keepdims, dtype, casting, order) — the gufunc (m,n),(n)->(m) —
the whole call: the argument checks, the core axes axes= names, the core sizes, the loop
dtype selects, the product (Matvec(NDArray, NDArray)), the result's core axis
placed, and the delivery into out.
public override NDArray Matvec(NDArray x1, NDArray x2, NDArray @out, int[][] axes, int? axis, bool keepdims, DType dtype, string casting, char order)
Parameters
x1NDArrayThe matrix operand, at least 2-D.
x2NDArrayThe vector operand, at least 1-D; not conjugated.
outNDArrayWhere the answer is delivered (its cast checked under
casting), or null.axesint[][]The core axes per operand (
{(m,n), (n), (m)}, all three entries), or null.axisint?Refused for any value (the two core dimensions are distinct), or null.
keepdimsboolRefused when true.
dtypeDTypeThe loop dtype, or null.
castingstringThe rule the input-to-loop and answer-to-out casts are checked under:
no,equiv,safe,same_kind(NumPy's default) orunsafe.ordercharThe layout of an allocated answer:
'K'(NumPy's default: the loop axes in the inputs' memory order),'C','F', or'A'(F when both inputs are F-contiguous, else C); ignored without. Lowercase letters are accepted.
Returns
- NDArray
The matrix-vector products, or
outitself holding them.
Remarks
New in 0.80.0 (the np-layer dtype plan, P2): the public np.matvec calls this (the ufunc
mechanism answers for a subclass operand).
Exceptions
- TypeError
axiswithaxes, or either given; adtypewith details beyond its class; text operands or a textdtype;keepdims.- ValueError
An operand with too few dimensions; core axes of different lengths; an
axes=list without three entries; a read-onlyout, or one the answer does not broadcast into.- AxisError
An
axes=entry of the wrong length, or an axis out of range.- TypeError
An input cannot be cast to the loop, or the answer into
out, undercasting(NumPy's UFuncTypeError text).- ValueError
A
castingorordername NumPy refuses (casting must be one of 'no', 'equiv', 'safe', 'same_kind', 'unsafe' (got '…'),order must be one of 'C', 'F', 'A', or 'K' (got '…')), checked casting first.- TypeError
A null
casting(casting must be str, not NoneType).- IncorrectShapeException
Loop axes that do not broadcast (the product's text).
- NotSupportedException
dtypeis a class without storage yet.- NullReferenceException
x2is null.
Maximum(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise maximum, NaN-propagating (np.maximum).
public override NDArray Maximum(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Mean(NDArray, int?, DType, bool)
The mean without out= / where=: ReduceMean(NDArray, int?, bool, DType, NDArray, NDArray) under its shipped (0.70.0) signature, kept
for callers and subclasses of that member.
public override NDArray Mean(NDArray nd, int? axis = null, DType dtype = null, bool keepdims = false)
Parameters
ndNDArrayThe array to average.
axisint?The reduced axis, or null for every axis.
dtypeDTypeThe sum's loop dtype, or null for
_mean's default.keepdimsboolWhether the reduced axes stay with length 1.
Returns
- NDArray
The mean (see ReduceMean(NDArray, int?, bool, DType, NDArray, NDArray)).
Remarks
Footgun: np.mean and ndarray.mean call ReduceMean(NDArray, int?, bool, DType, NDArray, NDArray) since 0.80.0, so an override
of this member no longer intercepts them; override ReduceMean(NDArray, int?, bool, DType, NDArray, NDArray).
Exceptions
- AxisError
axisis out of range.
MeanElementwise<T>(NDArray, NPTypeCode?)
Element-wise mean for typed result. Compatibility method for Std/Var.
public T MeanElementwise<T>(NDArray arr, NPTypeCode? typeCode) where T : unmanaged
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
- T
Type Parameters
T
Median(NDArray, int[], NDArray, bool, bool)
DefaultEngine's Median(NDArray, int[], NDArray, bool, bool): NumPy's np.median body over the given axes (NumPy's
tuple axis; a one-axis call arrives as a one-element array, as NumPy's _ureduce turns an int axis
into a 1-tuple) or the flattened data: the text routes in NumPy's order, then the numeric median through
QuantileCompute(NDArray, double[], int[], NDArray, bool, QuantileMethod, bool, bool, bool, bool, bool, bool, bool?, long[], string, bool, NPTypeCode), several reduced axes merged into one. The facades apply the class rules
(numpy.matrix, numpy.char.chararray) first.
public override NDArray Median(NDArray a, int[] axis = null, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
aNDArrayThe data (bool computes as its 0 / 1 values; text is refused as NumPy refuses it, a
StringDTypearray is sorted first).axisint[]The axes to reduce (negative values count from the end); null reduces the flattened data, an EMPTY array reduces nothing.
outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
keepdimsboolWhether the reduced axes are kept with length one.
Returns
- NDArray
The median over the reduced axes (NaN for an empty slice);
outitself when one is given.
Remarks
Moved from np.median by the np-layer dtype plan's P0 pilot, statement for statement, so the facade
holds no dtype test; since its P1a step 2 every route runs NumPy's one _ureduce prologue
(UReduce(NDArray, int[], NDArray, bool, NDArray)) first (until then each route had its own copy, and the copies disagreed: the plan's
Appendix B1). Until the plan's phase PE a one-axis body of its own served the facade's int?
overload; it ran these statements with the axis as an int?, and the facade now passes the
one-element array instead (the snapshot of every np.median overload is unchanged).
Exceptions
- ArgumentNullException
ais null.- ValueError
An axis repeats; or, for a
StringDTypearray, a None-like NA in a sorted line of two or more elements, an empty reduced axis (the mean's add.reduce has no identity) or a read-onlyout.- AxisError
An axis is out of range for
a.- ValueError
outthat np.median's closingmean(part[indexer], out=out)refuses in its add.reduce prologue, before anything is computed: read-only (output array is read-only), of the wrong rank (output parameter for reduction operation add has the wrong number of dimensions: Found 2 but expected 1) or with a length-1 axis where the result is longer (parity QA-31).- IncorrectShapeException
An
outwhose axes do not broadcast with the result's: the prologue's iterator text over the partition's middle slice (operands could not be broadcast together with remapped shapes [original->remapped]: (3,)->(3) (1,4)), NumPy's ValueError.- TypeError
Text data or a text
outthat NumPy's closing mean refuses (its verbatim text); aStringDTypearray after its sort (its mean's divide refuses the concatenated text).- IncorrectShapeException
Several reduced axes beside a kept axis of length 0, any dtype (NumPy's
_ureducemerge cannot resolve its -1:cannot reshape array of size 0 into shape (0,newaxis)); before the plan's P1a step 2 only aStringDTypearray raised it (plan Appendix B1).- IndexError
keepdimswith anoutNumPy cannot index (_ureduce'sout[(Ellipsis,) + index_out]: too few dimensions, or a reduced axis of length 0), for every dtype and before the text refusals.
Minimum(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise minimum, NaN-propagating (np.minimum).
public override NDArray Minimum(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Mod(NDArray, NDArray, DType, NDArray, NDArray)
np.mod / np.remainder (one NumPy ufunc, named remainder) — the floored remainder, element-wise: the
result takes the DIVISOR's sign (Python's %). IL-generated kernels on NumPy's integer and float loops
only: a bool pair promotes to the int8 loop, and complex has no loop at all.
public override NDArray Mod(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe dividends (
x1).rhsNDArrayThe divisors (
x2); broadcasts againstlhs.dtypeDTypeNumPy's
dtype=: the loop the remainder is computed in (each input must reach it by a same_kind cast), or null for the NEP 50 promotion of the inputs. A bool or complex request names no loop.outNDArrayNumPy's
out=: joins the broadcast without being stretched and must take the loop dtype by a same_kind cast; returned itself.whereNDArrayNumPy's
where=: a bool mask; a False position keeps whatoutheld (and is uninitialized in a fresh result, as in NumPy).
Returns
- NDArray
The remainders:
outitself when given, else a fresh array of the loop dtype.
Exceptions
- IncorrectTypeException
A bool or complex
dtype: NumPy'sNo loop matching the specified signature and casting was found for ufunc remainder(the ufunc's name, for np.mod too), raised after the out and mask checks and before any input cast or shape check (parity QA-53).- TypeError
A
dtypenaming more than a DType class; a complex operand with nodtype(ufunc 'remainder' not supported for the input types, …, a zero-size operand too); an inputdtypecannot take, or a loop dtypeoutcannot take, by a same_kind cast (Cannot cast ufunc 'remainder' input 0 / output …).- ValueError
A read-only
out(output array is read-only, checked first).- ArgumentException
A non-bool
where; an out or mask that does not broadcast, or an out that would be stretched.- IncorrectShapeException
The inputs do not broadcast together.
ModF(NDArray, DType, NDArray, NDArray, NDArray)
Return the fractional and integral parts of an array, element-wise — NumPy's two-output
modf ufunc, with the out=/where=/dtype= parameters.
NumPy behavior (C standard modf; all probed against NumPy 2.4.2):
- modf(1.5) = (0.5, 1.0)
- modf(-2.7) = (-0.7, -2.0) -- the fractional AND integral parts carry the input's sign
- modf(inf) = (+0.0, +inf), modf(-inf) = (-0.0, -inf)
- modf(nan) = (nan, nan)
- modf(-0.0) = (-0.0, -0.0) -- the signed zero is preserved on both outputs
Loop selection (float loops only, e/f/d/g): bool/int8/uint8 to float16,
int16/uint16/char to float32, int32/uint32/int64/uint64 to float64 (NumPy's NEP50
narrowest-float tier, NOT a blanket float64); float16/float32/float64 are preserved, Complex has
NO loop (NumPy's "not supported for the input types" TypeError), and Decimal is a NumSharp
extension (no NumPy analog). An explicit
dtype must itself be one of the float loops or NumPy raises the no-loop
TypeError (dtype=int32/complex128 → "No loop matching …").
public override (NDArray Fractional, NDArray Integral) ModF(NDArray nd, DType dtype = null, NDArray outFrac = null, NDArray outIntegral = null, NDArray where = null)
Parameters
ndNDArrayInput array.
dtypeDTypeOptional loop dtype override; must be Half/Single/Double/Decimal.
outFracNDArrayOptional provided output for the fractional part (NumPy's
out[0]); same_kind-castable from the loop dtype, else "Cannot cast ufunc 'modf' output 1 …".outIntegralNDArrayOptional provided output for the integral part (NumPy's
out[1]); same_kind-castable from the loop dtype, else "… output 2 …".whereNDArrayOptional bool write mask; masked-off slots of BOTH provided outputs keep their prior contents.
Returns
- (NDArray Lhs, NDArray Rhs)
The (fractional, integral) pair — a provided output is returned as-is (reference identity); when neither output is provided, both are fresh loop-dtype arrays in NumPy's ufunc output layout (the K order of the input and the mask: an F-contiguous input yields F-contiguous outputs, a permuted one keeps its memory order; parity QA-36).
Exceptions
- TypeError
Complex input (no loop), or a non-float
dtype.- ValueError
A read-only provided output; a text output under
wherewhose current text does not parse into the loop dtype (a text output receives the parts as text otherwise).- INumSharpException
The read-only output's ValueError ("output array is read-only", ThrowIfNotWriteable(Shape, string)).
- TypeError
An out not same_kind-castable from the loop dtype.
- ArgumentException
A non-bool
where, or an output that would have to be broadcast/stretched.
MoveAxis(NDArray, int[], int[])
NumPy's np.moveaxis: the axes of source moved to the positions of
destination, the other axes keeping their order — a view through
Transpose(NDArray, int[]).
public override NDArray MoveAxis(NDArray nd, int[] source, int[] destination)
Parameters
ndNDArrayThe array.
sourceint[]The axes to move (negative values count from the end).
destinationint[]Their new positions.
Returns
- NDArray
A view with the permuted axes.
Exceptions
- AxisError
An axis is out of range: "source: axis …" or "destination: axis …".
- ValueError
An argument repeats an axis ("repeated axis in
sourceargument"), or the two have different lengths ("sourceanddestinationarguments must have the same number of elements").
Multiply(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise multiplication using IL-generated kernels. Supports all 144 type combinations with automatic type promotion.
public override NDArray Multiply(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
MultiplyMatrix(NDArray, NDArray, NDArray)
Matrix multiplication for 2D arrays: C = A @ B A is [M x K], B is [K x N], result is [M x N]
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
protected NDArray MultiplyMatrix(NDArray left, NDArray right, NDArray @out = null)
Parameters
Returns
Remarks
Every dtype takes a stride-native path — no copies are materialized for transposed or sliced operands: float / double → BLIS-style SIMD GEMM in SimdMatMul (packers handle arbitrary strides). all other dtypes → INumber<T> generic kernel in Default.MatMul.Strided.cs, scalar pointer arithmetic.
NanArgMax(NDArray, int?, NDArray, bool)
NumPy's np.nanargmax(a, axis=None, out=None, *, keepdims=<no value>): argmax of the
array with every NaN replaced by -inf, after NumPy's all-NaN slice guard. Only an inexact array (float16,
float32, float64, complex) has NaNs to replace: NumPy's _replace_nan leaves integers, bool and text
alone (NumSharp's char and decimal too), so theirs is argmax itself.
public override NDArray NanArgMax(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayThe input.
axisint?The axis to reduce, or null for the flattened array; a 0-d array takes 0 and -1.
outNDArrayAn array to write the indices into and return, or null: its shape must equal the result's, its dtype must reach int64 by a safe cast (bool through uint32, and char); the indices are cast unsafely into it.
keepdimsboolWhether the reduced axes stay with length one (every axis for the flattened form).
Returns
- NDArray
The int64 indices (0-d for the flattened form without keepdims), or
out.
Remarks
The result cannot be trusted when a slice holds only NaNs and infinities of the losing sign (NumPy's caveat).
Exceptions
- NullReferenceException
ais null.- AxisError
axisout of range, naming the input's rank for an inexact dtype and the ravelled rank otherwise (the NumPy statement that raises differs).- ValueError
An all-NaN slice (
All-NaN slice encountered); an empty reduced length (attempt to get argmax of an empty sequence); an out of another shape (output array does not match result of np.argmax.); aStringDTypeline of two or more elements holding an NA that is neither a string nor NaN-like.- TypeError
An out whose dtype does not cast safely to int64.
- OutOfMemoryException
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
NanArgMin(NDArray, int?, NDArray, bool)
NumPy's np.nanargmin(a, axis=None, out=None, *, keepdims=<no value>): argmin of the
array with every NaN replaced by +inf, after NumPy's all-NaN slice guard. Only an inexact array (float16,
float32, float64, complex) has NaNs to replace: NumPy's _replace_nan leaves integers, bool and text
alone (NumSharp's char and decimal too), so theirs is argmin itself.
public override NDArray NanArgMin(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayThe input.
axisint?The axis to reduce, or null for the flattened array; a 0-d array takes 0 and -1.
outNDArrayAn array to write the indices into and return, or null: its shape must equal the result's, its dtype must reach int64 by a safe cast (bool through uint32, and char); the indices are cast unsafely into it.
keepdimsboolWhether the reduced axes stay with length one (every axis for the flattened form).
Returns
- NDArray
The int64 indices (0-d for the flattened form without keepdims), or
out.
Remarks
The result cannot be trusted when a slice holds only NaNs and infinities of the losing sign (NumPy's caveat).
Exceptions
- NullReferenceException
ais null.- AxisError
axisout of range, naming the input's rank for an inexact dtype and the ravelled rank otherwise (the NumPy statement that raises differs).- ValueError
An all-NaN slice (
All-NaN slice encountered); an empty reduced length (attempt to get argmin of an empty sequence); an out of another shape (output array does not match result of np.argmin.); aStringDTypeline of two or more elements holding an NA that is neither a string nor NaN-like.- TypeError
An out whose dtype does not cast safely to int64.
- OutOfMemoryException
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
NanCumProd(NDArray, int?, DType, NDArray)
NumPy's np.nancumprod body: a, mask = _replace_nan(a, 1) then np.cumprod(a, axis, dtype,
out), with NumPy's text routes first. The facade applies the numpy.matrix rule and calls this for
everything else.
public override NDArray NanCumProd(NDArray a, int? axis = null, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayThe array (any dtype; text is not inexact, so a numeric dtype= parses it and a parsed 'nan' is MULTIPLIED, not replaced by 1).
axisint?The accumulated axis (negative counts from the end), or null for the flattened array.
dtypeDTypeThe loop / result dtype, or null for NEP 50's accumulator of the input.
outNDArrayNumPy's
out=, or null.
Returns
- NDArray
outitself when given, else a fresh array.
Remarks
Moved from the public np.nancumprod by the np-layer dtype plan's P1b, statement for statement;
its np.cumprod calls became ReduceCumMul(NDArray, int?, DType, NDArray), the member they reach for a plain
operand. The plan's phase PE (E1) made it DefaultEngine's override of NanCumProd(NDArray, int?, DType, NDArray);
it was an internal static.
Exceptions
- AxisError
axisis out of range.- TypeError
A text operand or request NumPy's loop resolution refuses.
- ValueError
A read-only
out, or text a numeric dtype cannot parse.- IncorrectShapeException
outdoes not have the result's shape.
NanCumSum(NDArray, int?, DType, NDArray)
NumPy's np.nancumsum body (numpy/lib/_nanfunctions_impl.py): a, mask = _replace_nan(a, 0)
then np.cumsum(a, axis, dtype, out), with NumPy's text routes first. The facade applies the
numpy.matrix rule and calls this for everything else.
public override NDArray NanCumSum(NDArray a, int? axis = null, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayThe array (any dtype; text is not inexact, so it is np.cumsum's text: StringDType concatenates, fixed-width text is refused or parsed under a numeric dtype=).
axisint?The accumulated axis (negative counts from the end), or null for the flattened array.
dtypeDTypeThe loop / result dtype, or null for NEP 50's accumulator of the input.
outNDArrayNumPy's
out=, or null.
Returns
- NDArray
outitself when given, else a fresh array.
Remarks
Moved from the public np.nancumsum by the np-layer dtype plan's P1b, statement for statement;
its np.cumsum call became the engine member it reaches for a plain operand,
ReduceCumAdd(NDArray, int?, DType, NDArray). The plan's phase PE (E1) made it DefaultEngine's override of
NanCumSum(NDArray, int?, DType, NDArray); it was an internal static.
Exceptions
- AxisError
axisis out of range.- TypeError
A text operand or request NumPy's loop resolution refuses.
- ValueError
A read-only
out, or text a numeric loop cannot parse.- IncorrectShapeException
outdoes not have the result's shape.
NanMax(NDArray, int?, bool, NDArray, object, NDArray)
Return maximum of an array or maximum along an axis, ignoring NaNs — NumPy's np.nanmax, which on an
ndarray IS np.fmax.reduce (see NanMinMax(NDArray, int?, bool, MinMaxOp)).
public override NDArray NanMax(NDArray a, int? axis = null, bool keepdims = false, NDArray @out = null, object initial = null, NDArray where = null)
Parameters
aNDArrayThe array to reduce.
axisint?The axis to reduce (null = all axes).
keepdimsboolKeep the reduced axes as size 1.
outNDArrayNumPy's
out=, or null.initialobjectNumPy's
initial=, or null.whereNDArrayNumPy's
where=bool mask, or null.
Returns
- NDArray
The reduced array (a 0-d scalar for a flat reduction without keepdims), or
outitself when given.
Exceptions
- ArgumentException
The reduction is empty — "zero-size array to reduction operation fmax which has no identity", NumPy's ValueError.
- AxisError
axisis out of bounds.- ValueError
With a keyword, NumPy's keyword errors (see MaxMinNumPy(NDArray, int?, NDArray, bool, object, NDArray, MinMaxOp)).
NanMean(NDArray, int?, DType, bool)
DefaultEngine's NanMean(NDArray, int?, DType, bool): NumPy's nanmean, run by
NanMeanNumPy(NDArray, int?, bool, DType).
public override NDArray NanMean(NDArray a, int? axis = null, DType dtype = null, bool keepdims = false)
Parameters
aNDArrayThe array to reduce, any layout.
axisint?The reduced axis (negative counts from the end), or null for a flat reduction.
dtypeDTypeThe loop of the sum (NumPy's
dtype=), or null for the input's dtype.keepdimsboolKeep the reduced axis as a length-1 dimension.
Returns
- NDArray
The mean of the non-NaN elements (see NanMeanNumPy(NDArray, int?, bool, DType)).
Remarks
A public entry point since the np-layer dtype plan's phase PE (E1), so it owns its scope: the count, the NaN-zeroed copy and the sums are reclaimed here even when no scoped facade called it.
Exceptions
NanMedian(NDArray, int[], NDArray, bool, bool)
DefaultEngine's NanMedian(NDArray, int[], NDArray, bool, bool): NumPy's np.nanmedian body over the given axes
(NumPy's tuple axis; a one-axis call arrives as a one-element array) or the flattened data: the text
routes in NumPy's order, then the NaN-ignoring median through QuantileCompute(NDArray, double[], int[], NDArray, bool, QuantileMethod, bool, bool, bool, bool, bool, bool, bool?, long[], string, bool, NPTypeCode), several reduced
axes merged into one. Like np.median, an even-sized (NaN-free) slice reduces to the MEAN of its two
central values (NumPy's mean-of-middle rule, not np.nanquantile(a, 0.5), which differs by up to 1 ULP);
a slice that is entirely NaN, or empty, gives NaN. The facades apply the numpy.matrix rule first.
public override NDArray NanMedian(NDArray a, int[] axis = null, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
aNDArrayThe data (bool computes as its 0 / 1 values; text is refused as NumPy refuses it, a
StringDTypearray drops its NaN-like NAs and takes the median of the rest).axisint[]The axes to reduce (negative values count from the end); null reduces the flattened data, an EMPTY array reduces nothing.
outNDArrayAn optional output array of the result's shape, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place (NumSharp stages a copy anyway).
keepdimsboolWhether the reduced axes are kept with length one.
Returns
- NDArray
The NaN-ignoring median over the reduced axes;
outitself when one is given. Over aStringDTypearray a median exists only for an all-NaN reduction (its NA object, ornp.float64(nan)).
Remarks
Moved from np.nanmedian (Statistics/np.nanmedian.cs) by the np-layer dtype plan's P1a (step 1),
statement for statement and in the same order, so the facade holds no dtype test (the move Median(NDArray, int[], NDArray, bool, bool)
made in the plan's P0 pilot). Until the plan's phase PE a one-axis body of its own served the facade's
int? overload with the same statements; the facade now passes the one-element array instead.
Exceptions
- ArgumentNullException
ais null.- ValueError
An axis repeats; or, for a
StringDTypearray, a None-like NA in a sorted line of two or more elements, an empty input's mean (no identity), or the store intoout.- AxisError
An axis is out of range for
a.- ValueError
The store
out[...] = result(np.nanmedian's, after the computation): anoutthe result does not broadcast to (could not broadcast input array from shape (4,) into shape (3,)) or a read-only one (assignment destination is read-only); for empty data, np.nanmean's add.reduce prologue texts (parity QA-31).- TypeError
Fixed-width text data that NumPy's NaN test (or, for empty data, its
nanmean) refuses (its verbatim text); aStringDTypearray's median, numpy.ma or keepdims refusals.- NotSupportedException
A
StringDTypereduction along a long axis whose row result NumPy stores in an OBJECT array: NumSharp has no object dtype.- IndexError
Data that is not empty, under
keepdims, with anoutNumPy cannot index (_ureduce's prologue), before the text refusals. (Data that is not empty never fails the prologue's merge; empty data answersnp.nanmeanbefore it.)
NanMin(NDArray, int?, bool, NDArray, object, NDArray)
Return minimum of an array or minimum along an axis, ignoring NaNs — NumPy's np.nanmin, which on an
ndarray IS np.fmin.reduce (see NanMinMax(NDArray, int?, bool, MinMaxOp)).
public override NDArray NanMin(NDArray a, int? axis = null, bool keepdims = false, NDArray @out = null, object initial = null, NDArray where = null)
Parameters
aNDArrayThe array to reduce.
axisint?The axis to reduce (null = all axes).
keepdimsboolKeep the reduced axes as size 1.
outNDArrayNumPy's
out=, or null.initialobjectNumPy's
initial=, or null.whereNDArrayNumPy's
where=bool mask, or null.
Returns
- NDArray
The reduced array (a 0-d scalar for a flat reduction without keepdims), or
outitself when given.
Exceptions
- ArgumentException
The reduction is empty — "zero-size array to reduction operation fmin which has no identity", NumPy's ValueError.
- AxisError
axisis out of bounds.- ValueError
With a keyword, NumPy's keyword errors (see MaxMinNumPy(NDArray, int?, NDArray, bool, object, NDArray, MinMaxOp)).
NanPercentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)
DefaultEngine's NanPercentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray): NanQuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray) named
nanpercentile (q divided by 100 first).
public override NDArray NanPercentile(NDArray a, object q, int[] axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data.
qobjectThe percentiles as NumPy reads them (QuantileQ(object, out QuantileArgument)).
axisint[]The reduced axes, or null for the flattened data; an EMPTY array reduces nothing.
outNDArrayAn optional output array, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place.
methodstringThe estimation method name.
keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=, or null.
Returns
- NDArray
The percentiles of the non-NaN values;
outitself when one is given.
Remarks
An array QuantileQ(object, out QuantileArgument) makes is disposed when the call ends (see Quantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)).
Exceptions
- Exception
The errors of NanQuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray), in its order.
NanProd(NDArray, int?, bool)
np.nanprod: the product of a's elements over axis treating NaN
as one — NumPy's np.prod(where(isnan(a), 1, a), axis, keepdims), so it follows np.prod's rules (the
identity start 1, the result shape). An integer / bool input is plain np.prod.
public override NDArray NanProd(NDArray a, int? axis = null, bool keepdims = false)
Parameters
aNDArrayThe array to reduce; any dtype, any layout.
axisint?The axis to reduce, or null for every axis (a 0-d input also takes 0 / -1, np.prod's rule).
keepdimsboolWhen true the reduced axes stay in the result with length 1.
Returns
- NDArray
The NaN-skipping product (a read-only 0-d scalar for a full reduction).
Remarks
Since parity QA-15 (2026-11-05) every inexact input runs NumPy's two statements
(NanReplacedReduceNumPy(NDArray, int?, bool, bool)): a complex element with a NaN in either part is replaced by 1
(it used to reach np.prod unreplaced), and the product is np.prod's over the replaced copy — so a lone complex
element still inherits np.prod's skipped (1+0j) * x, pinned by
OpenBugsReductionTests.Prod_OneComplexElement_IsTheIdentityTimesTheElement.
NDAnchoredAttribute: the kernels read a's raw address and
np.nanprod(a) reaches them through this method, which opens no scope; the weaver roots
a until it returns (lifetime gap LT30, as NanSum(NDArray, int?, bool)).
Exceptions
- AxisError
axisis out of range.
NanQuantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)
DefaultEngine's NanQuantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray): NanQuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray) named
nanquantile.
public override NDArray NanQuantile(NDArray a, object q, int[] axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data.
qobjectq as NumPy reads it (QuantileQ(object, out QuantileArgument)).
axisint[]The reduced axes, or null for the flattened data; an EMPTY array reduces nothing.
outNDArrayAn optional output array, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place.
methodstringThe estimation method name.
keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=, or null.
Returns
- NDArray
The quantiles of the non-NaN values;
outitself when one is given.
Remarks
An array QuantileQ(object, out QuantileArgument) makes is disposed when the call ends (see Quantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)).
Exceptions
- Exception
The errors of NanQuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray), in its order.
NanStd(NDArray, int?, DType, int, bool)
DefaultEngine's NanStd(NDArray, int?, DType, int, bool): NumPy's nanstd, the square root of
nanvar, run by NanVarStdNumPy(NDArray, int?, bool, int, DType, bool).
public override NDArray NanStd(NDArray a, int? axis = null, DType dtype = null, int ddof = 0, bool keepdims = false)
Parameters
aNDArrayThe array to reduce, any layout.
axisint?The reduced axis (negative counts from the end), or null for a flat reduction.
dtypeDTypeThe loop of both sums (NumPy's
dtype=), or null for the input's dtype.ddofintDelta degrees of freedom.
keepdimsboolKeep the reduced axis as a length-1 dimension.
Returns
- NDArray
The standard deviation of the non-NaN elements (see NanVarStdNumPy(NDArray, int?, bool, int, DType, bool)).
Remarks
A public entry point since the np-layer dtype plan's phase PE (E1), so it owns its scope.
Exceptions
NanSum(NDArray, int?, bool)
np.nansum: the sum of a's elements over axis treating NaN as zero —
NumPy's np.sum(where(isnan(a), 0, a), axis, keepdims) (_replace_nan then np.sum), so it
follows np.sum's rules: the result starts from the identity +0.0 (a sum of -0.0 is +0.0), a complex element
with a NaN in EITHER part counts as zero, and an integer / bool input is plain np.sum.
public override NDArray NanSum(NDArray a, int? axis = null, bool keepdims = false)
Parameters
aNDArrayThe array to reduce; any dtype, any layout.
axisint?The axis to reduce, or null for every axis (a 0-d input also takes 0 / -1, np.sum's rule).
keepdimsboolWhen true the reduced axes stay in the result with length 1.
Returns
- NDArray
The NaN-skipping sum (a read-only 0-d scalar for a full reduction).
Remarks
NDAnchoredAttribute: the flat and axis kernels read a's raw address
(NanReductionElementWise(NDArray, ReductionOp, bool), ExecuteNanAxisReduction(NDArray, int, bool, ReductionOp)), and np.nansum(a) reaches
them through this method, which opens no scope; the weaver roots a until it returns, so a
caller's temporary (np.nansum(a * w, 1)) cannot be collected under the kernel. Without it a collection
during the axis kernel returned a sum of other memory or ended the process with an access violation
(lifetime gap LT30).
Exceptions
- AxisError
axisis out of range.
NanToNum(NDArray, bool, object, object, object)
NumPy's np.nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None): NaN replaced with
nan, +inf with posinf and -inf with neginf, in
the real and imaginary parts of a complex input alike. An input that is not inexact (bool, integers, char,
decimal, text) holds no NaN or inf and comes back as it is.
public override NDArray NanToNum(NDArray x, bool copy = true, object nan = null, object posinf = null, object neginf = null)
Parameters
xNDArrayThe input.
copyboolWhether to work on a copy (true) or in place on
x(false: the result isxitself, its memory written).nanobjectThe fill for NaN: null for NumPy's 0.0, a real scalar (a C# number, bool, char or float16), or an array_like (an NDArray or a C# array) broadcast against
x; cast same_kind to x's real dtype, as NumPy'scopytocasts it, so text and complex fills are refused.posinfobjectThe fill for +inf, as
nan; null for the largest finite value of x's real dtype (float16, float32, or float64 for float64 and complex128).neginfobjectThe fill for -inf, as
nan; null for the smallest finite value.
Returns
- NDArray
The array with its non-finite values replaced: a copy, or
xwhencopyis false.
Remarks
DefaultEngine fills scalar fills into a contiguous target in one fused pass (the
DirectILKernelGenerator.NanToNum kernel); array fills and other layouts run NumPy's three
copyto(where=) statements.
Exceptions
- ArgumentNullException
xis null.- ValueError
An array fill that does not broadcast into
x(np.copyto's text).- InvalidCastException
On an inexact input, a fill NumPy's
copytorefuses to cast same_kind into x's real dtype: text (NumPy's TypeError text,Cannot cast scalar from dtype('<U1') to dtype('float64') according to the rule 'same_kind', np.copyto's house type for it; the text is never parsed), a complex number, a complex or text array. It is raised by thecopytostatement that meets the fill (NaN, then +inf, then -inf; for a complex input the real part's three, then the imaginary part's), as in NumPy, so withcopyfalse the earlier fills are already written. Also a scalar fill of a type that does not convert to a number.
NanVar(NDArray, int?, DType, int, bool)
DefaultEngine's NanVar(NDArray, int?, DType, int, bool): NumPy's nanvar, run by
NanVarStdNumPy(NDArray, int?, bool, int, DType, bool).
public override NDArray NanVar(NDArray a, int? axis = null, DType dtype = null, int ddof = 0, bool keepdims = false)
Parameters
aNDArrayThe array to reduce, any layout.
axisint?The reduced axis (negative counts from the end), or null for a flat reduction.
dtypeDTypeThe loop of both sums (NumPy's
dtype=), or null for the input's dtype.ddofintDelta degrees of freedom.
keepdimsboolKeep the reduced axis as a length-1 dimension.
Returns
- NDArray
The variance of the non-NaN elements (see NanVarStdNumPy(NDArray, int?, bool, int, DType, bool)).
Remarks
A public entry point since the np-layer dtype plan's phase PE (E1), so it owns its scope: the count, the NaN-zeroed copy, the deviations and the sums are reclaimed here even when no scoped facade called it.
Exceptions
Negate(NDArray, DType, NDArray, NDArray)
Element-wise negation using IL-generated kernels.
public override NDArray Negate(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
NextAfter(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray NextAfter(NDArray x1, NDArray x2, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
NonZero(NDArray)
np.nonzero — returns a tuple of ndim int64 arrays of length
N, containing the per-dim coordinates of non-zero elements in C-order.
Implementation: three IL-emitted kernels keyed off the element type
(GetArgwhereCountKernel(Type),
GetArgwhereFlatKernel(Type),
GetArgwhereExpandKernel()). The runtime call
site has zero typeof(T) branches: it looks the kernels up in the
per-dtype ConcurrentDictionary<TKey, TValue>
cache and invokes them. Every loop (SIMD popcount, SIMD bit-scan, coord
expand + carry chain) lives inside the emitted IL.
Two-pass pre-size-then-fill: the SIMD popcount sizes the result
exactly, the SIMD bit-scan writes flat indices either straight into the
ndim==1 result buffer or into a temp long[] which the IL row-expand
kernel walks once to fill the shared (count, ndim) multi-index matrix
whose columns are the result. Mirrors the design of
Argwhere(NDArray), which fills NumPy's transposed
(ndim, count) stack instead.
Routing:
- 0-d → NumPy 2.x's ValueError, every dtype, bool with its longer text (parity QA-02: the numeric
dtypes used to answer like
atleast_1d(a).nonzero(), which NumPy's message points callers to). - size == 0 → tuple of
ndimempty int64 arrays. - Contiguous → IL count + IL flat-scan + (ndim==1 ? direct write : IL per-dim expand).
- Non-contiguous → materialize via
ascontiguousarraythen same path as contig.
public override NDArray<long>[] NonZero(NDArray nd)
Parameters
ndNDArrayThe array.
Returns
Remarks
A string array of at least one dimension is searched by its truth values (a non-empty string is True; the nonzero route never raises).
Exceptions
- ValueError
A 0-d array of any dtype, raised before the element is read (single-argument
np.whereinherits it): NumPy'sCalling nonzero on 0d arrays is not allowed. Use np.atleast_1d(scalar).nonzero() instead., which a bool array follows withIf the context of this error is of the form(NonZero0dMessage(NPTypeCode)).arr[nonzero(cond)], just usearr[cond].
NotEqual(NDArray, NDArray, DType, NDArray, NDArray)
public override NDArray NotEqual(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Outer(NDArray, NDArray, NDArray)
NumPy's np.outer(a, b, out=None): multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out),
every product a[i] * b[j] of the two inputs flattened - one multiply ufunc call, so its loops, its
promotion and its out= rules are outer's.
public override NDArray Outer(NDArray a, NDArray b, NDArray @out = null)
Parameters
aNDArrayThe first input, any shape (flattened; not null).
bNDArrayThe second input, any shape (flattened; not null).
outNDArrayAn array to write the products into, or null: it joins the multiply's broadcast (never stretched) and takes a same_kind cast from the product dtype; it is returned itself.
Returns
- NDArray
A new
(a.size, b.size)array in the multiply's promoted dtype, orout.
Remarks
NumPy writes outer in Python (numpy/_core/numeric.py); DefaultEngine runs its one statement over the
array object's ravel and expand_dims and a's engine's Multiply(NDArray, NDArray, DType, NDArray, NDArray).
np.outer calls it with plain views of subclass operands, and numpy.linalg's Array-API
outer after its one-dimensional check; an override replaces both for every array whose engine it is.
Exceptions
- NullReferenceException
aorbis null.- TypeError
Operands the multiply has no loop for (text with numbers, two texts; NumPy's no-loop texts), or a text product without
out's string multiply.- ValueError
A read-only
out(output array is read-only).- TypeError
An
outthe product dtype does not reach under same_kind (Cannot cast ufunc 'multiply' output from ...).- ArgumentException
An
outthe products do not broadcast into (operands could not be broadcast together with shapes ...).
Packbits(NDArray, int?, string)
NumPy's np.packbits(a, axis=None, bitorder='big') (io_pack / pack_bits,
numpy/_core/src/multiarray/compiled_base.c), the whole call: the elements packed into the bits of a
uint8 array, one bit per element (1 iff it is nonzero), the axis shortened to ceil(len / 8) and the
last byte zero-padded.
public override NDArray Packbits(NDArray a, int? axis = null, string bitorder = "big")
Parameters
aNDArrayA bool or integer array (NumSharp's char included), read in logical order for any layout.
axisint?The axis to pack along, or null to pack the C-order flattened array into a 1-D result. A 0-d input is promoted to
(1,)and accepts only 0 and -1.bitorderstring"big"puts the first element in the most significant bit,"little"in the least; NumPy's prefix rule: a value beginning with"little"is little, one beginning with"big"big, null is big.
Returns
- NDArray
A new uint8 array of
a's rank (1-D for a null axis), F-contiguous when the input is.
Remarks
New in 0.80.0 (the np-layer dtype plan): the public np.packbits applies the numpy.matrix
rule and calls this.
Exceptions
- ArgumentNullException
ais null.- ValueError
bitorderbegins with neither ('order' must be either 'little' or 'big'), checked first.- TypeError
ais neither bool nor integer (Expected an input array of integer or boolean data type).- AxisError
axisis out of bounds fora's rank.
Partition(NDArray, object, int?, string, string)
NumPy's np.partition(a, kth, axis, kind, order) (fromnumeric.partition over
PyArray_Partition), the whole call: a copy of a in which every
kth element is where a sorted copy holds it, with no larger element before it and no
smaller one after it along the axis (introselect). Use PartitionInPlace(NDArray, object, int?, string, string) for
ndarray.partition.
public override NDArray Partition(NDArray a, object kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayThe array (only read). Text has no partition function, so NumPy sorts each line.
kthobjectNumPy's array_like of positions along the axis: a C# int, an int[], an integer index array, or any other object, converted with
np.asanyarray. A negative position counts from the end; every listed position ends where a sorted copy holds its element.axisint?The axis (negative counts from the end), or null for the flattened array.
kindstringNumPy's
kind=: only"introselect"(the default) or null.orderstringNumPy's
order=, a field name, or null: every NumSharp dtype has no fields, so any value is refused.
Returns
- NDArray
A fresh array of
a's dtype laid out ascopy(order='K')lays outa, or the partitioned flattening for a null axis. Float NaNs end each line with their own bits; the arrangement between the listed positions is the introselect's own.
Remarks
New in 0.80.0 (the np-layer dtype plan, phase PE, E5): the public np.partition applies its class
boundaries and calls this; DefaultEngine partitions with its AxisPartition kernels.
Exceptions
- ValueError
A
kindother than"introselect"(select kind must be 'introselect' (got 'x')) or anorder, before the array is read; a kth index array of more than one dimension (object too deep for desired array, before the axis) or of bool dtype (Booleans unacceptable as partition index); a position out of bounds (kth(=5) out of bounds (5), skipped for an empty array).- TypeError
A kth index array of a non-integer dtype (
Partition index must be integer).- AxisError
The axis is out of range.
- ArgumentNullException
kthis null, at NumPy's kth stage (after the axis: NumPy's kth=None raises its TypeError there).
PartitionInPlace(NDArray, object, int?, string, string)
NumPy's ndarray.partition(kth, axis, kind, order) (array_partition over PyArray_Partition),
the whole call: partitions a IN PLACE along the axis (see Partition(NDArray, object, int?, string, string)), in
NumPy's order of checks (the kind, the order, the axis, writeability, then the positions).
public override void PartitionInPlace(NDArray a, object kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayThe array partitioned in place.
kthobjectNumPy's array_like of positions along the axis: a C# int, an int[], an integer index array, or any other object, converted with
np.asanyarray. A negative position counts from the end; every listed position ends where a sorted copy holds its element.axisint?The axis (negative counts from the end), or null: NumSharp's extension that partitions a contiguous array's flattening in place.
kindstringNumPy's
kind=: only"introselect"(the default) or null.orderstringNumPy's
order=, a field name, or null: every NumSharp dtype has no fields, so any value is refused.
Remarks
New in 0.80.0 (the np-layer dtype plan, phase PE, E5): NDArray.partition calls this.
Exceptions
- ValueError
A
kindother than"introselect"(select kind must be 'introselect' (got 'x')) or anorder, before the array is read; a kth index array of more than one dimension (object too deep for desired array, before the axis) or of bool dtype (Booleans unacceptable as partition index); a read-only array (partition array is read-only); a position out of bounds (kth(=5) out of bounds (5), skipped for an empty array).- TypeError
A kth index array of a non-integer dtype (
Partition index must be integer).- AxisError
The axis is out of range.
- ArgumentNullException
kthis null, at NumPy's kth stage (after the axis: NumPy's kth=None raises its TypeError there).
Percentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)
DefaultEngine's Percentile(NDArray, object, int[], NDArray, bool, string, bool, NDArray): QuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray, bool) named
percentile (q divided by 100 first), over a plain operand (a numpy.char.chararray operand
reaches QuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray, bool) from the facade, with its flag).
public override NDArray Percentile(NDArray a, object q, int[] axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data.
qobjectThe percentiles as NumPy reads them (QuantileQ(object, out QuantileArgument)).
axisint[]The reduced axes, or null for the flattened data; an EMPTY array reduces nothing.
outNDArrayAn optional output array, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place.
methodstringThe estimation method name.
keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=, or null.
Returns
- NDArray
The percentiles;
outitself when one is given.
Remarks
An array QuantileQ(object, out QuantileArgument) makes is disposed when the call ends (see Quantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)).
Exceptions
- Exception
The errors of QuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray, bool), in its order.
Poly(NDArray)
NumPy's np.poly(seq_of_zeros): the coefficients (highest degree first, leading 1) of the
polynomial with the given roots, or of a square matrix's characteristic polynomial (its eigenvalues are
the roots).
public override NDArray Poly(NDArray seq_of_zeros)
Parameters
seq_of_zerosNDArrayA 1-D sequence of roots, or a non-empty square 2-D array. A 0-d input is one root (atleast_1d): this is poly's body, which NumPy's np.poly reaches only through its dispatcher, and that refuses a 0-d input first (the np.poly facade raises its TypeError).
Returns
- NDArray
The coefficients, 1-D: float64 for real roots of any dtype but float32 (kept) and complex (kept; the real part when the roots come in conjugate pairs); the 0-d float64
1.0for no roots.
Exceptions
- ValueError
Neither 1-D nor a non-empty square 2-D array (
input must be 1d or non-empty square 2d array.); a 1-D text root that does not parse as a float (NumPy's mintypecode cast to'd').- TypeError
A square text matrix: its eigenvalues' finiteness check has no text loop.
- NotSupportedException
A square matrix with no LAPACK backend (the eigenvalues).
Polyadd(NDArray, NDArray)
NumPy's np.polyadd(a1, a2): the shorter coefficient array (by len(), the first axis)
zero-extended on the high-degree side with zeros of its own dtype, then added.
public override NDArray Polyadd(NDArray a1, NDArray a2)
Parameters
a1NDArrayThe first polynomial's coefficients (a scalar is a constant).
a2NDArrayThe second polynomial's coefficients.
Returns
- NDArray
The sum's coefficients, in the addition's promoted dtype.
Exceptions
- TypeError
Coefficients the addition has no loop for (text with numbers).
- IncorrectShapeException
An N-D operand: the 1-D pad meets np.concatenate's rank error, and equal first axes the addition's broadcast error (NumPy's ValueError texts).
Polyder(NDArray, int)
NumPy's np.polyder(p, m=1): the m-th derivative, each order
p[:-1] * arange(n, 0, -1) with n = len(p) - 1.
public override NDArray Polyder(NDArray p, int m = 1)
Parameters
pNDArrayThe coefficients, highest degree first (null is NumPy's None:
asarray(None)'s refusal). Each order slices the FIRST axis (len(p)) and multiplies by an int64 ramp oflen(p) - 1terms, which broadcasts against the LAST axis ofp[:-1]: a 2-D p is differentiated along its rows, as NumPy's statement does (np.polyder(np.ones((3, 2)))is[[2, 1], [2, 1]]).mintThe order of differentiation: 0 returns
asarray(p)itself, after NumPy's discardedm == 0product has had its chance to raise.
Returns
- NDArray
The derivative's coefficients (int32 coefficients become int64 through the int64 ramp); for
mpast the degree, an empty array.
Remarks
NumPy writes polyder in Python (numpy/lib/_polynomial_impl.py, which also handles a poly1d - NumSharp's
poly1d calls its own derivative); DefaultEngine runs its loop over the array object's slice and multiply.
np.polyder calls it with plain views of subclass operands, on p's engine (the
default one for null); an override replaces it for every array whose engine it is.
Exceptions
- ValueError
A negative
m(Order of derivative must be positive (see polyint)), checked beforepis read.- NotSupportedException
pis null (NumPy's object array of None).- IncorrectShapeException
An N-D p whose
p[:-1]does not broadcast with the ramp at some level, them == 0one included (the multiply'soperands could not be broadcast together with shapes (2,4) (2,), NumPy's ValueError):np.polyder(np.ones((3, 4)), 0)raises.- TypeError
A 0-d p, at every order, 0 included (
len() of unsized object); text coefficients the multiply has no loop for (a fixed-width one; aStringDTypep repeats its strings, as NumPy's string multiply does).
Polydiv(NDArray, NDArray)
NumPy's np.polydiv(u, v): long division of the floated coefficients (u + 0.0, v +
0.0), the scalar quotient coefficients computed with NumPy's scalar arithmetic, the remainder's
leading near-zero coefficients dropped (rtol=1e-14, at least one kept).
public override (NDArray q, NDArray r) Polydiv(NDArray u, NDArray v)
Parameters
uNDArrayThe dividend's coefficients, measured by
len()(its first axis).vNDArrayThe divisor's coefficients, measured by
len().
Returns
- (NDArray Lhs, NDArray Rhs)
The quotient and the remainder, floating or complex; for an N-D u shorter than v, NumPy's
(zeros(1), u)with u's leading near-zero rows dropped.
Exceptions
- TypeError
Coefficients the float conversion has no loop for (text); or a complex quotient coefficient with dimensions (u or v N-D), which NumPy's
q[k] = drefuses through complex() (only 0-dimensional arrays can be converted to Python scalars).- ValueError
A real quotient coefficient with dimensions (
setting an array element with a sequence.).- IncorrectShapeException
Rows of an N-D u and v that do not broadcast: NumPy's first statement
w = u[0] + v[0]raises the add's error, u's row first.- IndexError
An empty u or v (
u[0]/v[0]).
Polyfit(NDArray, NDArray, int, double?, bool, NDArray, object)
NumPy's np.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): the least-squares polynomial
of degree deg through the points, from the Vandermonde matrix of x with
its columns scaled to unit norm, one np.linalg.lstsq solve, and the scale taken back out of the
coefficients.
public override PolyfitResult Polyfit(NDArray x, NDArray y, int deg, double? rcond = null, bool full = false, NDArray w = null, object cov = null)
Parameters
xNDArrayThe sample points, 1-D (null is NumPy's None:
asarray(None)'s refusal);x + 0.0makes them float (float32 stays float32).yNDArrayThe sample values: 1-D, or 2-D with one data set per column, as long as
x.degintThe degree of the polynomial.
rconddouble?The relative condition number of the fit, or null for
len(x) * epsof x's float dtype.fullboolAlso return lstsq's residuals, rank and singular values (NumPy's five-tuple).
wNDArrayWeights applied to the unsquared residuals, one per sample point, or null.
covobjectNumPy's
cov=: null /false(no covariance),true(scaled by the residuals),"unscaled", or any other object, read as Python's truth value (the empty string is false). Ignored withfull.
Returns
- PolyfitResult
The PolyfitResult carrying exactly the arrays NumPy returns: the coefficients (highest degree first, one column per data set); with
full, the residuals, rank and singular values; with a truthycov, the covariance. Every other slot is null.
Remarks
NumPy writes polyfit in Python; DefaultEngine runs its statements over the operand engines' Vander(NDArray, int?, bool),
Sum(NDArray, int?, DType, bool), Sqrt(NDArray, DType, NDArray, NDArray), Dot(NDArray, NDArray, NDArray), Outer(NDArray, NDArray, NDArray) and the
Linalg sub-engine's lstsq and inv. NumPy's RankWarning for a rank-deficient fit is not modelled.
np.polyfit calls it with plain views of subclass operands, on x's engine (the
default one for null); an override replaces it for every array whose engine it is.
Exceptions
- ValueError
A negative
deg(expected deg >= 0); a scaled covariance with no more points than coefficients (the number of data points must exceed order to scale the covariance matrix).- TypeError
NumPy's shape refusals in its order (
expected 1D vector for x,expected non-empty vector for x,expected 1D or 2D array for y,expected x and y to have same length,expected a 1-d array for weights,expected w and y to have the same length); text the float conversion+ 0.0has no loop for; a float16 or decimal x that numpy.linalg refuses (array type float16 is unsupported in linalg).- NotSupportedException
xoryis null (NumPy's object array of None).- OpenBlasMissingBackendException
No LAPACK backend is installed: lstsq needs one.
- LinAlgError
lstsq's SVD does not converge (a NaN or an infinity in the data), or the covariance's inverse meets a singular matrix.
- IncorrectShapeException
Weights that do not broadcast against a 2-D y's columns.
Polyint(NDArray, int, NDArray)
NumPy's np.polyint(p, m=1, k=None): the m-th antiderivative, each integration
dividing the coefficients by their exponents and appending a constant.
public override NDArray Polyint(NDArray p, int m = 1, NDArray k = null)
Parameters
pNDArrayThe coefficients, highest degree first, measured by
len()(its first axis: an N-D p meets the division's broadcast or the concatenation's rank error, as in NumPy).mintThe order of the antiderivative.
kNDArrayThe integration constants, highest order first, measured by
len(): null for zeros, one value for every order, or at leastmvalues.
Returns
- NDArray
The antiderivative's coefficients (floating or complex: the division by the exponents); for
m0,pas an array.
Exceptions
- ValueError
A negative
m, or fewer constants thanm.- TypeError
With
mabove 0: a 0-dp(len() of unsized object), or text, whose division by the exponents has no loop.- IncorrectShapeException
An N-D p or k whose shapes the division, the constants' broadcast or the concatenation refuses (NumPy's ValueError texts).
Polymul(NDArray, NDArray)
NumPy's np.polymul(a1, a2): each input's leading zeros dropped (NumPy wraps it in poly1d),
then the full convolution of the coefficients.
public override NDArray Polymul(NDArray a1, NDArray a2)
Parameters
Returns
- NDArray
The product's coefficients.
Exceptions
- ValueError
An input of rank above 1 (
Polynomial must be 1d only., the first input's first); fixed-width text otherwise (data type must provide an itemsize).
Polysub(NDArray, NDArray)
NumPy's np.polysub(a1, a2): the shorter coefficient array (by len(), the first axis)
zero-extended on the high-degree side with zeros of its own dtype, then a1 - a2.
public override NDArray Polysub(NDArray a1, NDArray a2)
Parameters
Returns
- NDArray
The difference's coefficients, in the subtraction's promoted dtype.
Exceptions
- TypeError
Coefficients the subtraction has no loop for (text, bool).
- IncorrectShapeException
An N-D operand: the 1-D pad meets np.concatenate's rank error, and equal first axes the subtraction's broadcast error (NumPy's ValueError texts).
Polyval(NDArray, NDArray)
NumPy's np.polyval(p, x): Horner's scheme, y = y * x + pv for each pv in
p, from y = zeros_like(x).
public override NDArray Polyval(NDArray p, NDArray x)
Parameters
pNDArrayThe coefficients, highest degree first. NumPy iterates its first axis (
len(p)coefficients): an N-D p's coefficients are its rows, each broadcast against x.xNDArrayThe points, any shape.
Returns
- NDArray
The values, of dtype
result_type(p, x); ofx's shape for a 1-D p, of the broadcast of x's shape and a row's for an N-D p; with no coefficient,zeros_like(x).
Exceptions
- TypeError
A 0-d
p(iteration over a 0-d array), or text, which has no multiply (inx) or add (inp) loop.- IncorrectShapeException
An N-D p whose rows do not broadcast with x (the add's
operands could not be broadcast togethertext, NumPy's ValueError).
Positive(NDArray, DType, NDArray, NDArray)
NumPy 'positive' — identity at every numeric dtype (returns +x, a copy). Full ufunc surface: out=/where= ride the iterator Into-path with the identity kernel (Positive emits nothing — the same masked-copy vehicle Default.Round uses), dtype= selects the loop.
public override NDArray Positive(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
ndNDArrayThe input (any numeric dtype but bool, any layout).
dtypeDTypeThe loop dtype (
dtype=), or null for the input's own.outNDArrayNumPy's
out=, or null for a fresh result.whereNDArrayNumPy's
where=mask, or null.
Returns
- NDArray
outwhen given; else a fresh copy in NumPy's ufunc output layout (the input's K order; parity QA-36).
Exceptions
- TypeError
A bool loop (positive has none), or text.
- TypeError
A
dtypethe input cannot reach by a same_kind cast, or an out that cannot take the loop dtype.- ArgumentException
A mask the ufunc refuses (not bool), or an out / mask that does not broadcast.
Power(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise power: x1 ** x2, NumPy-aligned.
Promotion / dispatch (NEP50, matches numpy 2.x):
- int^int → integer result, dtype-native wrap (e.g. uint8 ** 8 = 0). Negative exponent rejected: NumPy raises ValueError unconditionally ("Integers to negative integer powers are not allowed.").
- int^float → float64 (mirrors NumPy's int-base / np-float-exp rule).
- float^np.int → float64 (NEP50 strict promotion: float32 ** np.int32 → float64).
- float^float → wider float; float32 ** float32 → float32.
- complex^* → complex128 (via Complex.Pow).
- decimal^* → decimal (via DecimalMath.Pow).
Stride/layout: routes through ExecuteBinaryOp, which handles
contiguous + sliced + broadcast + F-contig via the IL kernel's
SimdFull/SimdScalarRight/SimdScalarLeft/SimdChunk/General paths.
The integer kernel calls NDIntegerPower for
exact dtype wrapping (replaces the previous double round-trip).
float32 / float64 loops are NumPy's DOUBLE_power / FLOAT_power: when the exponent's step in NumPy's inner-loop call is 0, an exponent of -1, 0, 0.5, 1 or 2 gives 1/x, 1, sqrt(x), x or x*x, otherwise pow — on every route (plain, out=, where=, dtype=), decided by NumPy's own trivial-loop and iterator rules (PowerFloatLoop(NDArray, NDArray, NPTypeCode, NPTypeCode?, NDArray, NDArray)). float16 is NumPy's HALF_power (powf, no fast path).
public override NDArray Power(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayThe bases.
rhsNDArrayThe exponents.
dtypeDTypeThe loop dtype (NumPy's
dtype=), or null to promote the inputs.outNDArrayThe out= array, or null for a fresh result.
whereNDArrayThe bool where= mask, or null.
Returns
- NDArray
The powers, or
outwhen one is given.
Exceptions
- ArgumentException
An integer loop meets a negative integer exponent ("Integers to negative integer powers are not allowed."), a cast is not allowed, a mask is not bool, or the out is read-only.
- INumSharpException
A read-only
out: NumPy's ValueError "output array is read-only" (ThrowIfNotWriteable(Shape, string)).- ValueError
A text
outunderwherewhose current text does not parse into the loop dtype (read before the loop, as NumPy's buffered iteration does).- IncorrectShapeException
The operands do not broadcast together, or the out cannot hold the broadcast result.
Ptp(NDArray, int[], NDArray, bool)
NumPy's np.ptp(a, axis=(…)) body: maximum.reduce(a, axis) - minimum.reduce(a, axis) over the axes
of a tuple, with NumPy's text routes and tuple checks first.
public override NDArray Ptp(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayThe array.
axisint[]The reduced axes (negative values count from the end), or null for every axis. An empty array reduces nothing (the result is
a - a).outNDArrayAn optional output; the result is written into it and it is returned.
keepdimsboolWhether the reduced axes stay with length one.
Returns
- NDArray
The range, dtype preserved (integer overflow wraps as in NumPy);
outitself when given, the subtraction then in NEP 50's loop over the out's dtype and the minima's.
Remarks
Moved from the public tuple-axis np.ptp by the np-layer dtype plan's P1b, statement for
statement; its re-entries into the one-axis overload call the one-axis member above, through virtual
dispatch since phase PE made both of them DefaultEngine's overrides of
Ptp(NDArray, int[], NDArray, bool) and its one-axis sibling.
Exceptions
- ArgumentNullException
ais null.- AxisError
An axis is out of range (a 0-d input has no axis for a tuple to name).
- ValueError
An axis appears twice ("duplicate value in 'axis'").
- TypeError
Fixed-width text, or a text out (NumPy's loop refusal); an out that is a C# scalar turned into a 0-d array (
return arrays must be of ArrayType).- ValueError
A read-only out, or one of the wrong rank or with a length-1 axis where the result is longer: maximum.reduce's prologue texts (parity QA-31), before the axes are reduced.
- IncorrectShapeException
An out whose axes do not broadcast with the result's (maximum.reduce's
operands could not be broadcast together with remapped shapes ...).- TypeError
An out the range cannot reach by a same_kind cast: subtract's UFuncTypeError, raised after the maxima were stored into it (parity QA-55).
Ptp(NDArray, int?, NDArray, bool)
NumPy's np.ptp body (_methods._ptp): subtract(maximum.reduce(a, axis, out, keepdims),
minimum.reduce(a, axis, keepdims), out), with NumPy's text routes first. The facade applies the
numpy.matrix rule and calls this for everything else.
public override NDArray Ptp(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayThe array (any dtype; StringDType computes both extremes, fixed-width text is refused).
axisint?The reduced axis (negative counts from the end; a 0-d array accepts 0 and -1), or null for every axis.
outNDArrayAn optional output of the result's shape; the result is written into it and it is returned.
keepdimsboolWhether the reduced axis stays with length one.
Returns
- NDArray
The range, dtype preserved (integer overflow wraps as in NumPy):
outitself when given (the subtraction then runs in NEP 50's loop over the out's dtype and the minima's, so an int8 range into an int64 out does not wrap), else a fresh array, read-only when 0-d (NumPy's scalar).
Remarks
Moved from the public np.ptp(a, int? axis, out, keepdims) by the np-layer dtype plan's P1b, statement for
statement; the facade's np.amax / np.amin calls became the engine members they reach for a
plain operand (ReduceAMax(NDArray, int?, bool, DType, NDArray, object, NDArray) / ReduceAMin(NDArray, int?, bool, DType, NDArray, object, NDArray): no
out=, initial= or where=, and the matrix rule has already been applied). The plan's phase
PE (E1) made it DefaultEngine's override of Ptp(NDArray, int?, NDArray, bool); it
was an internal static.
Exceptions
- ArgumentNullException
ais null.- AxisError
axisis out of range.- TypeError
Fixed-width text, or a text out: NumPy's maximum.reduce refuses the loop with its verbatim text.
- ValueError
A read-only out (NumPy parses out first), an empty reduction (no identity), or a StringDType subtraction NumPy refuses; an out of the wrong rank or with a length-1 axis where the result is longer: maximum.reduce's texts (
output parameter for reduction operation maximum has the wrong number of dimensions: Found 2 but expected 1, parity QA-31), checked before anything is computed.- IncorrectShapeException
An out whose axes do not broadcast with the result's: maximum.reduce's iterator text (
operands could not be broadcast together with remapped shapes [original->remapped]: (3,)->(3) (3,4)), NumPy's ValueError under the house type of a broadcast failure.- TypeError
An out that is a C# scalar turned into a 0-d array (NumPy's
return arrays must be of ArrayType).- TypeError
An out the range cannot reach by a same_kind cast: subtract's UFuncTypeError (
Cannot cast ufunc 'subtract' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'), raised after maximum.reduce stored the maxima into it, as NumPy leaves them (parity QA-55).
Quantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray)
DefaultEngine's Quantile(NDArray, object, int[], NDArray, bool, string, bool, NDArray): QuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray, bool) named
quantile, over a plain operand (a numpy.char.chararray operand reaches
QuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray, bool) from the facade, with its flag).
public override NDArray Quantile(NDArray a, object q, int[] axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false, NDArray weights = null)
Parameters
aNDArrayThe data.
qobjectq as NumPy reads it (QuantileQ(object, out QuantileArgument)).
axisint[]The reduced axes, or null for the flattened data; an EMPTY array reduces nothing.
outNDArrayAn optional output array, written and returned itself.
overwrite_inputboolWhether the data may be partitioned in place.
methodstringThe estimation method name.
keepdimsboolWhether the reduced axes are kept with length one.
weightsNDArrayNumPy's
weights=, or null.
Returns
- NDArray
The quantiles;
outitself when one is given.
Remarks
An array QuantileQ(object, out QuantileArgument) makes from q is read into the quantile list and never
returned, so it is disposed when the call ends; the caller's own arrays are never disposed.
Exceptions
- Exception
The errors of QuantileFunction(string, NDArray, QuantileArgument, int[], NDArray, bool, string, bool, NDArray, bool), in its order.
Rad2Deg(NDArray, DType, NDArray, NDArray)
Element-wise radians to degrees conversion using IL-generated kernels. Computes x * (180/π).
public override NDArray Rad2Deg(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Radians(NDArray, DType, NDArray, NDArray)
NumPy's np.radians ufunc: the same conversion as Deg2Rad(NDArray, DType, NDArray, NDArray) (degrees to radians), but a ufunc of its
own, so a refusal (text, an operand type with no loop) names radians.
public override NDArray Radians(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
ndNDArrayThe angles.
dtypeDTypeThe loop dtype (
dtype=), or null for the operand's float tier.outNDArrayThe array to write into (
out=), or null.whereNDArrayThe bool mask of the positions to compute (
where=), or null for all.
Returns
- NDArray
The converted angles:
outwhen given, else a new array of the float tier (float16 for bool / int8 / uint8, float32 for int16 / uint16, float64 for wider integers; floats keep theirs).
Exceptions
- TypeError
A text or complex operand (no radians loop), with NumPy's texts.
- ValueError
A read-only
out.- ArgumentException
A non-bool
where, or adtypethe operand cannot reach.
RavelMultiIndex(NDArray[], int[], object, char)
NumPy's np.ravel_multi_index(multi_index, dims, mode='raise', order='C') (arr_ravel_multi_index,
numpy/_core/src/multiarray/compiled_base.c), the whole call: the flat index each coordinate tuple has in
an array of dimensions dims, the inverse of UnravelIndex(NDArray, int[], char).
public override NDArray<long> RavelMultiIndex(NDArray[] multi_index, int[] dims, object mode = null, char order = 'C')
Parameters
multi_indexNDArray[]The coordinate arrays, one per dimension of
dims: integer or bool, any layout; they broadcast against each other, and the broadcast shape is the result's. A null entry is NumPy'sNone, refused.dimsint[]The shape the coordinates index. An empty shape (NumPy's
()) takes no coordinate array and gives the flat index 0.modeobjectNumPy's mode argument: a string for every axis -
"raise"(an out-of-range coordinate raises),"wrap"(modulo, with sign correction) or"clip"(saturate) -, a sequence of such strings other than a string (NumPy's tuple or list: one mode per axis, a null entry raising on its axis), or null (NumPy'sNone: raise on every axis).orderchar'C'(row-major, the default) or'F'(column-major), in either case: the stride order the coordinates fold with.
Returns
- NDArray<long>
The int64 flat indices in the coordinates' broadcast shape, laid out as NumPy's iterator allocates them (KEEPORDER over the coordinate arrays: F-ordered coordinates give an F-ordered result, a transposed set the same permutation, mixed or broadcast ones C order). Coordinates that are all 0-d give NumPy's scalar: a fresh read-only 0-d array.
Remarks
New in 0.80.0 (the np-layer dtype plan): the public np.ravel_multi_index array overloads compute
a numpy.matrix operand as a plain array and call this; the scalar overload
np.ravel_multi_index(long[], int[], string, char) computes its one index itself.
Exceptions
- ArgumentNullException
multi_indexordimsis null.- ValueError
In NumPy's order: an order letter that is not C / F / A / K in either case; a mode sequence of another length (
list of clipmodes has wrong length (1 instead of 2)) or a mode string NumPy's clipmode parser refuses; an'A'or'K'order (only 'C' or 'F' order is permitted); a dims product that overflows int64 (invalid dims: array size defined by dims is larger than the maximum possible size.); a coordinate count that differs fromdims' length (parameter multi_index must be a sequence of length N); a zero dimension while there is a coordinate to fold (cannot unravel if shape has zero entries (is empty)., whatever the mode); and (moderaise) a coordinate out of range (invalid entry in coordinates array).- TypeError
A mode that is neither a string, null nor a sequence of strings and nulls (
clipmode not understood; NumPy's integer modes have no C# spelling here), checked with the modes; a coordinate array that is neither integer nor bool, or a null entry (only int indices permitted), checked in order after the count.- IncorrectShapeException
The coordinate arrays do not broadcast together (NumPy's
ValueErrortext from its iterator, every coordinate shape listed).- NotSupportedException
Runtime code generation is unavailable (the IL kernel cannot be emitted).
RealIfClose(NDArray, double)
NumPy's np.real_if_close(a, tol=100): a complex input whose every imaginary part is strictly within
tol of zero becomes its real part; anything else is returned as it is.
public override NDArray RealIfClose(NDArray a, double tol = 100)
Parameters
aNDArrayThe input.
toldoubleAbove 1, a multiple of the complex dtype's machine epsilon (float64's, 2^-52); at most 1, an absolute bound. At 0 or below nothing collapses: a magnitude is never strictly below it.
Returns
- NDArray
A float64 view of the real parts (sharing
a's memory, as NumPy'sa.real) when every imaginary part is within the bound (an empty complex array always is); otherwiseaitself.
Remarks
DefaultEngine decides in one early-exit pass over the imaginary parts (NaN and inf never collapse).
Exceptions
- NullReferenceException
ais null.
Reciprocal(NDArray, DType, NDArray, NDArray)
Element-wise reciprocal (1/x) using IL-generated kernels. NumPy: for integer dtypes, the result preserves the input dtype with C-style truncated integer division (so 1/x is 0 for |x| >= 2, and 0 for x == 0 per NumPy seterr=ignore semantics).
public override NDArray Reciprocal(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
ReduceAMax(NDArray, int?, bool, DType, NDArray, object, NDArray)
NumPy's np.max / np.amax (np.maximum.reduce) over axis_, or over
every axis when it is null.
public override NDArray ReduceAMax(NDArray arr, int? axis_, bool keepdims = false, DType dtype = null, NDArray @out = null, object initial = null, NDArray where = null)
Parameters
arrNDArrayThe array.
axis_int?The reduced axis (negative values count from the end), or null for every axis. A 0-d input accepts 0 and -1 (NumPy's backward-compatibility rule) and nothing else.
keepdimsboolWhether the reduced axes stay with length one.
dtypeDTypeThe loop dtype (
dtype=), or null for the input's.outNDArrayNumPy's
out=, or null; any keyword takes MaxMinNumPy(NDArray, int?, NDArray, bool, object, NDArray, MinMaxOp).initialobjectNumPy's
initial=, or null.whereNDArrayNumPy's
where=bool mask, or null.
Returns
- NDArray
The maximum (a read-only 0-d scalar for a full reduction), or
outitself when given.
Remarks
NDAnchoredAttribute: the reduction engines read arr's raw address
(the float16 walks and the exact schedules among them), and every front door — np.max,
np.amax, ndarray.max, AMax(NDArray, int?, DType, bool) — reaches them through this method, which opens no
scope; the weaver roots arr until it returns, so a caller's temporary cannot be collected
under the kernel.
Exceptions
- NotSupportedException
dtypetogether with a keyword.- AxisError
axis_is out of range — checked before any shortcut.- ArgumentException
An empty reduction ("zero-size array to reduction operation maximum which has no identity", NumPy's ValueError).
- TypeError
Fixed-width text, or a string
dtype: NumPy's refusal (its verbatim text). AStringDTypeinput computes.- ValueError
A numeric
dtypeover text that does not parse as that number (NumPy casts the text first:could not convert string to float).
ReduceAMin(NDArray, int?, bool, DType, NDArray, object, NDArray)
NumPy's np.min / np.amin (np.minimum.reduce) over axis_, or over
every axis when it is null.
public override NDArray ReduceAMin(NDArray arr, int? axis_, bool keepdims = false, DType dtype = null, NDArray @out = null, object initial = null, NDArray where = null)
Parameters
arrNDArrayThe array.
axis_int?The reduced axis (negative values count from the end), or null for every axis. A 0-d input accepts 0 and -1 (NumPy's backward-compatibility rule) and nothing else.
keepdimsboolWhether the reduced axes stay with length one.
dtypeDTypeThe loop dtype (
dtype=), or null for the input's.outNDArrayNumPy's
out=, or null; any keyword takes MaxMinNumPy(NDArray, int?, NDArray, bool, object, NDArray, MinMaxOp).initialobjectNumPy's
initial=, or null.whereNDArrayNumPy's
where=bool mask, or null.
Returns
- NDArray
The minimum (a read-only 0-d scalar for a full reduction), or
outitself when given.
Remarks
NDAnchoredAttribute: the reduction engines read arr's raw address,
and every front door — np.min, np.amin, ndarray.min, AMin(NDArray, int?, DType, bool) — reaches them
through this method, which opens no scope; the weaver roots arr until it returns (see
ReduceAMax(NDArray, int?, bool, DType, NDArray, object, NDArray)).
Exceptions
- NotSupportedException
dtypetogether with a keyword.- AxisError
axis_is out of range — checked before any shortcut.- ArgumentException
An empty reduction ("zero-size array to reduction operation minimum which has no identity", NumPy's ValueError).
- TypeError
Fixed-width text, or a string
dtype: NumPy's refusal (its verbatim text). AStringDTypeinput computes.- ValueError
A numeric
dtypeover text that does not parse as that number (NumPy casts the text first:could not convert string to float).
ReduceAdd(NDArray, int?, bool, DType, NDArray, object, NDArray)
np.sum / ndarray.sum / np.add.reduce: the add reduction of arr
over axis_ (every axis when null), computed the way NumPy's
PyUFunc_ReduceWrapper computes it — the result is first assigned the loop's IDENTITY (+0.0 for an
inexact loop, 0 / False otherwise) and only then does the add loop run over every element. A sum of only
negative zeros is therefore +0.0 (each part of a complex), including the one-element and length-1-axis
reductions that look like a plain copy.
public override NDArray ReduceAdd(NDArray arr, int? axis_, bool keepdims = false, DType dtype = null, NDArray @out = null, object initial = null, NDArray where = null)
Parameters
arrNDArrayThe array to reduce; any dtype and any layout (contiguous, strided, reversed, F, broadcast, 0-d).
axis_int?The axis to reduce (negative counts from the last), or null to reduce every axis. A 0-d array also accepts 0 and -1, which ufunc.reduce reads as "every axis" (NumPy's backward-compatibility rule).
keepdimsboolWhen true the reduced axes stay in the result with length 1.
dtypeDTypeNumPy's
dtype=: the LOOP dtype — every element is cast to it (unsafely, element by element) before it is added, and the sum is computed and returned in it. Null selects the NEP 50 accumulator (int64 for bool and signed integers, uint64 for unsigned integers and Char, the input dtype otherwise).outNDArrayNumPy's
out=, an array of the result's shape that receives the sum and is returned, or null for a fresh result. With it the call is NumPy'sadd.reducewith an out operand (ReduceIntoOut(string, NDArray, int?, bool, DType, NDArray)): the reduce prologue checks it first (read-only, rank, length: NumPy's texts), the loop isdtype, elsepromote_types(out.dtype, arr.dtype)WITHOUT the NEP 50 widening (an int8 sum into a bool out wraps in int8 and stores False for [100, 100, 56]; a float32 sum into a float64 out adds in float64), and the result reaches it with an unsafe cast (see the remarks for the one residual).initialobjectNumPy's
initial=: the start value of every output instead of the identity, or null. With it (or withwhere) the call is PyUFunc_ReduceWrapper's keyword path (AddMulNumPy(NDArray, int?, bool, DType, NDArray, object, NDArray, bool)).whereNDArrayNumPy's
where=mask of the elements to add, or null (a 0-d true mask is no mask).
Returns
- NDArray
The sum: a read-only 0-d scalar for a full reduction without keepdims, otherwise a fresh array (or
out).
Remarks
The loop dtype decides the arithmetic, so three dtype relations are told apart before anything is summed:
the default accumulator (or a dtype= naming it) and the input's own dtype keep the existing
same-type / widening kernels; any OTHER loop casts the input first (ReduceAddInCastLoop(NDArray, int?, bool, NPTypeCode, NDArray)),
exactly NumPy's semantics (its buffered iterator casts each element before the add loop sees it). The
kernels only ever converted per element for a few widening pairs: float→int accumulated in double and
truncated the TOTAL, a negative int saturated into an unsigned loop, and a complex / float16 loop read the
input buffer as its own dtype (out-of-bounds reads, a CLR crash for complex→real).
The bool loop is NumPy's logical-OR add (True + True is True), i.e. np.any.
With out the sum is computed in the loop dtype and copied into out with an unsafe cast, so
an out of another dtype receives NumPy's cast of the loop's result. NumPy differs in one place: past one buffer
fill (np.getbufsize() elements) its iterator carries the partial sum through out's dtype between fills,
where this route rounds into out once.
Exceptions
- AxisError
axis_is out of range forarr's rank.- ValueError
outis read-only, or has the wrong rank or a length that cannot hold the result (the reduce prologue's texts); aninitialthe loop cannot hold.- IncorrectShapeException
outorwheredoes not broadcast against the input (NumPy's "remapped shapes" text).- ArgumentException
whereis not a bool array (NumPy's TypeError text).- OverflowException
An integer
initialpast the loop's range.- TypeError
A C# scalar as
out, a complexinitialfor a real loop, or NumPy's text refusals.
ReduceArgMax(NDArray, int?, bool, NDArray)
NumPy's np.argmax(a, axis=None, out=None, *, keepdims=False) (PyArray_ArgMaxWithKeepdims), the
whole call: the int64 index of the largest element along axis_ (its first occurrence), or
of the C-order flattened array, written into out when one is given.
public override NDArray ReduceArgMax(NDArray arr, int? axis_, bool keepdims = false, NDArray @out = null)
Parameters
arrNDArrayThe array (any dtype: fixed-width text is compared as NumPy's
STRING_argmax/UNICODE_argmaxcompare it, aStringDTypearray by its dtype's compare, a NaN-like NA greater than any text).axis_int?The reduced axis (negative counts from the end), or null for the flattened array (a 0-d input ravels first, so it accepts 0 and -1).
keepdimsboolWhether the reduced axis stays with length one (with
axis_null, every axis: the shape(1,) * arr.ndim).outNDArrayNumPy's
out=: an array of exactly the result's shape whose dtype casts safely to int64 (bool through uint32, and NumSharp's char); the int64 indices are cast into it unsafely (an int8 out wraps an index of 200 to -56, a bool out reads index != 0) and it is returned itself. Null for a fresh result.
Returns
- NDArray
outitself when given; otherwise the int64 indices, a read-only 0-d array (NumPy's scalar) for the flattened form without keepdims.
Remarks
Widened with out in 0.80.0 (the np-layer dtype plan): NumPy's out= contract
was np's NanArgWriteOut, which np.argmax and np.nanargmax called around this member. Its two checks run
in NumPy's order, the shape before the dtype, and both before an element is compared
(_PyArray_ArgMinMaxCommon): an out error comes before a StringDType comparison's
refusal.
Exceptions
- AxisError
axis_is outside the input's rank (rank 1 for a 0-d input), checked before anything else, for every dtype.- ValueError
An empty reduced line (
attempt to get argmax of an empty sequence); anoutof another shape (output array does not match result of np.argmax.); aStringDTypecomparison that meets a None-like NA (Cannot compare null that is not a nan-like value).- TypeError
out's dtype does not cast safely to int64 (uint64, the floats, complex, text: NumPy'sCannot cast array data from dtype('uint64') to dtype('int64') according to the rule 'safe', which names a 0-d out ascalar).- OutOfMemoryException
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
ReduceArgMin(NDArray, int?, bool, NDArray)
NumPy's np.argmin(a, axis=None, out=None, *, keepdims=False) (PyArray_ArgMinWithKeepdims), the
whole call: the int64 index of the smallest element along axis_ (its first occurrence), or
of the C-order flattened array, written into out when one is given.
public override NDArray ReduceArgMin(NDArray arr, int? axis_, bool keepdims = false, NDArray @out = null)
Parameters
arrNDArrayThe array (any dtype: fixed-width text is compared as NumPy's
STRING_argmin/UNICODE_argmincompare it, aStringDTypearray by its dtype's compare, a NaN-like NA greater than any text).axis_int?The reduced axis (negative counts from the end), or null for the flattened array (a 0-d input ravels first, so it accepts 0 and -1).
keepdimsboolWhether the reduced axis stays with length one (with
axis_null, every axis: the shape(1,) * arr.ndim).outNDArrayNumPy's
out=: an array of exactly the result's shape whose dtype casts safely to int64 (bool through uint32, and NumSharp's char); the int64 indices are cast into it unsafely (an int8 out wraps an index of 200 to -56, a bool out reads index != 0) and it is returned itself. Null for a fresh result.
Returns
- NDArray
outitself when given; otherwise the int64 indices, a read-only 0-d array (NumPy's scalar) for the flattened form without keepdims.
Remarks
Widened with out in 0.80.0 (the np-layer dtype plan): NumPy's out= contract
was np's NanArgWriteOut, which np.argmin and np.nanargmin called around this member. Its two checks run
in NumPy's order, the shape before the dtype, and both before an element is compared
(_PyArray_ArgMinMaxCommon): an out error comes before a StringDType comparison's
refusal.
Exceptions
- AxisError
axis_is outside the input's rank (rank 1 for a 0-d input), checked before anything else, for every dtype.- ValueError
An empty reduced line (
attempt to get argmin of an empty sequence); anoutof another shape (output array does not match result of np.argmin.); aStringDTypecomparison that meets a None-like NA (Cannot compare null that is not a nan-like value).- TypeError
out's dtype does not cast safely to int64 (uint64, the floats, complex, text: NumPy'sCannot cast array data from dtype('uint64') to dtype('int64') according to the rule 'safe', which names a 0-d out ascalar).- OutOfMemoryException
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
ReduceCumAdd(NDArray, int?, DType, NDArray)
NumPy's np.cumsum (np.add.accumulate), the whole call: the running sums along
axis_ (or along the flattened array when it is null), stored into out
when one is given.
public override NDArray ReduceCumAdd(NDArray arr, int? axis_, DType dtype = null, NDArray @out = null)
Parameters
arrNDArrayThe array.
axis_int?The accumulated axis (negative values count from the end), or null for the flattened array. A 0-d input is treated as 1-D (NumPy's
PyArray_CheckAxis), so only 0 and -1 address it.dtypeDTypeThe accumulator dtype (
dtype=), or null: then the loop ispromote_types(out.dtype, arr.dtype)whenoutis given (no NEP 50 widening: AccumulateLoop(NDArray, DType, NDArray)), NEP 50's accumulator of the input otherwise.outNDArrayNumPy's
out=: an array of the result's shape (any layout and dtype; the result is stored with unsafe casting), or null for a fresh result.
Returns
- NDArray
outitself when given; otherwise a fresh array of the accumulator dtype: the input's shape with an axis, 1-D for the flattened form (a 0-d input gives shape (1,)).
Remarks
The statements are np.cumsum's, in its order (moved from APIs/np.cumsum.cs by the np-layer dtype
plan's P0 pilot): the StringDType route, then add.accumulate's loop resolution on (out, arr) for text (an
out or a string dtype decides it), then the accumulation
(CumSumCore(NDArray, int?, DType)) and the out store (WriteScanToOut(NDArray, NDArray, NDArray, int?, DType)).
CumSumCore(NDArray, int?, DType) repeats the StringDType check without out, as the engine did
before the move, so a StringDType input with a numeric out still concatenates and then
casts the text into it.
Exceptions
- AxisError
axis_is out of range — checked before every shortcut (empty, 0-d and one-element inputs included).- TypeError
Fixed-width text (input or
out), or a stringdtype, where NumPy's loop resolution refuses: its verbatim text. AStringDTypeinput computes (the concatenations), and a numeric loop over text with anoutaccumulates in the loop dtype with the text cast around it.- ValueError
outis read-only (output array is read-only, checked first), or text that a numeric loop must parse does not parse.- IncorrectShapeException
outdoes not have the result's shape and NumPy's accumulate refuses it: the text of the statement that refuses (parity QA-31, StoreIntoMisfitOut(NDArray, NDArray, NDArray, int?, DType)): NpyIter'soperands could not be broadcast together with remapped shapes [original->remapped]: (4,3)->(4,3) (3,4)->(3,4)(or itsop_axes/ non-broadcastable-output siblings) on NumPy's iterator path, an input of more than one dimension among its triggers;provided out is the wrong size for the accumulation.on the direct 1-D path. The outs NumPy accepts are written where its iterator writes (more trailing out axes at index 0, an extent-1 input broadcast, the accumulated axis cut to the input's extent), and an empty input or out comes back untouched (parity QA-54).
ReduceCumMul(NDArray, int?, DType, NDArray)
NumPy's np.cumprod (np.multiply.accumulate), the whole call: the running products along
axis_ (or along the flattened array when it is null), stored into out
when one is given.
public override NDArray ReduceCumMul(NDArray arr, int? axis_, DType dtype = null, NDArray @out = null)
Parameters
arrNDArrayThe array.
axis_int?The accumulated axis (negative values count from the end), or null for the flattened array. A 0-d input is treated as 1-D (NumPy's
PyArray_CheckAxis), so only 0 and -1 address it.dtypeDTypeThe accumulator dtype (
dtype=), or null: then the loop ispromote_types(out.dtype, arr.dtype)whenoutis given (no NEP 50 widening: AccumulateLoop(NDArray, DType, NDArray)), NEP 50's accumulator of the input otherwise.outNDArrayNumPy's
out=: an array of the result's shape (any layout and dtype; the result is stored with unsafe casting), or null for a fresh result.
Returns
- NDArray
outitself when given; otherwise a fresh array of the accumulator dtype: the input's shape with an axis, 1-D for the flattened form (a 0-d input gives shape (1,)).
Remarks
The statements are np.cumprod's, in its order (moved from APIs/np.cumprod.cs by the np-layer dtype
plan's P0 pilot): multiply.accumulate's loop resolution on (out, arr) answers FIRST for text or a string
request, then a numeric dtype over text parses the text, then NumPy's refusal for what is
left, then the accumulation (CumProdCore(NDArray, int?, DType)) and the out store
(WriteScanToOut(NDArray, NDArray, NDArray, int?, DType)).
Exceptions
- AxisError
axis_is out of range — checked before every shortcut (empty, 0-d and one-element inputs included).- TypeError
Text, or a string
dtype: NumPy's refusal (its verbatim text; no multiply loop accumulates text). A numeric loop over text with anoutaccumulates in the loop dtype with the text cast around it.- ValueError
A numeric
dtypeover text that does not parse as that number, or a read-onlyout(output array is read-only).- IncorrectShapeException
outdoes not have the result's shape and NumPy's accumulate refuses it: the text of the statement that refuses (parity QA-31, StoreIntoMisfitOut(NDArray, NDArray, NDArray, int?, DType)): NpyIter'soperands could not be broadcast together with remapped shapes [original->remapped]: (4,3)->(4,3) (3,4)->(3,4)(or itsop_axes/ non-broadcastable-output siblings) on NumPy's iterator path, an input of more than one dimension among its triggers;provided out is the wrong size for the accumulation.on the direct 1-D path. The outs NumPy accepts are written where its iterator writes (more trailing out axes at index 0, an extent-1 input broadcast, the accumulated axis cut to the input's extent), and an empty input or out comes back untouched (parity QA-54).
ReduceMean(NDArray, int?, bool, DType, NDArray, NDArray)
np.mean / ndarray.mean: NumPy's _methods._mean — the add reduction (identity-seeded, see
ReduceAdd(NDArray, int?, bool, DType, NDArray, object, NDArray)) divided by the count of the reduced elements. A mean of only negative zeros is
therefore +0.0, and a complex mean divides with NumPy's complex loop (Smith's algorithm with the divisor
n+0j), so an infinite or NaN part poisons the other one even for a single element.
public override NDArray ReduceMean(NDArray arr, int? axis_, bool keepdims = false, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
arrNDArrayThe array to average; any dtype, any layout.
axis_int?The axis to reduce, or null for every axis. Unlike np.sum, a 0-d array takes no axis (np.mean normalizes it against rank 0 and raises).
keepdimsboolWhen true the reduced axes stay in the result with length 1.
dtypeDTypeThe dtype the sum is computed in and the mean returned in; null selects float64 for bool / integers / char and the input's own dtype for float16 / float32 / float64 / complex128 / decimal.
outNDArrayNumPy's
out=, an array of the result's shape, or null for a fresh result:_meanwith an out (MeanIntoOut(NDArray, int?, bool, DType, NDArray)) — the sum stored into it, then divided in place, both with an unsafe cast.whereNDArrayNumPy's
where=mask, or null. A mask (anything but the C#trueliteral, NumPy'swhere=True) takes_mean's masked statements (MeanWhereNumPy(NDArray, int?, bool, DType, NDArray, NDArray)): per-output counts, the masked sum, the division.
Returns
- NDArray
outitself when given; otherwise the mean: a read-only 0-d scalar for a full reduction without keepdims, a fresh array else.
Exceptions
- AxisError
axis_is out of range (every axis is, for a 0-d input without a mask).- ValueError
outis read-only or does not have the result's shape (the reduce prologue's texts).- IncorrectShapeException
outdoes not broadcast against the input, orwheredoes not broadcast to its shape.- ArgumentException
whereis not a bool array (NumPy's TypeError text).- TypeError
Text NumPy's loop resolution refuses (a text out has no division loop).
ReduceProduct(NDArray, int?, bool, DType, NDArray, object, NDArray)
NumPy's np.prod (np.multiply.reduce): the product of arr's elements over
axis_, or over every axis when it is null, in NEP 50's accumulator dtype.
public override NDArray ReduceProduct(NDArray arr, int? axis_, bool keepdims = false, DType dtype = null, NDArray @out = null, object initial = null, NDArray where = null)
Parameters
arrNDArrayThe array.
axis_int?The reduced axis (negative values count from the end), or null for every axis. A 0-d input accepts 0 and -1 (NumPy's backward-compatibility rule) and nothing else.
keepdimsboolWhether the reduced axes stay with length one.
dtypeDTypeThe loop dtype (
dtype=), or null for the accumulator of the input (forpromote_types(out, arr)whenoutis given).outNDArrayNumPy's
out=, an array of the result's shape, or null for a fresh result: NumPy'smultiply.reducewith an out operand (ReduceIntoOut(string, NDArray, int?, bool, DType, NDArray)) — the text routes, the reduce prologue, the out= loop rule, the unsafe store.initialobjectNumPy's
initial=: the start value of every output instead of the identity 1, or null. With it (or withwhere) the call is PyUFunc_ReduceWrapper's keyword path (AddMulNumPy(NDArray, int?, bool, DType, NDArray, object, NDArray, bool)): NumPy's sequential multiply loop, which can differ in the last bit of a float product from this call's own flat loop (NL3).whereNDArrayNumPy's
where=mask of the elements to multiply, or null (a 0-d true mask is no mask).
Returns
- NDArray
outitself when given; otherwise the product (a read-only 0-d scalar for a full reduction).
Remarks
A complex128 or float16 loop takes the keyword path's reduction iterator even without a keyword (whenever more
than one element meets an output), because NumPy's result there depends on which inner-loop calls its iterator
makes: the reduce form (contracted loop_scalar for complex, a float32 accumulator per call for float16)
against the elementwise form (simd_cmul, a float16 rounding per product). The other loops keep the flat /
axis kernels.
Exceptions
- AxisError
axis_is out of range — checked before any shortcut.- TypeError
Text, or a string
dtype: NumPy's refusal (its verbatim text; no multiply loop reduces text into itself); a C# scalar asout; a complexinitialfor a real loop.- ValueError
A numeric
dtypeover text that does not parse as that number, a read-only / misshapenout(the reduce prologue's texts), or aninitialthe loop cannot hold.- ArgumentException
whereis not a bool array (NumPy's TypeError text).- IncorrectShapeException
outorwheredoes not broadcast against the input.- OverflowException
An integer
initialpast the loop's range.
ReduceStd(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?)
np.std: NumPy's _std — the _var port (VarStdNumPy(NDArray, int?, bool, int, DType, bool, NDArray)) followed by NumPy's
square root step, so ddof= and dtype= work at every size and every input gives NumPy's value,
dtype and NaN / +inf.
public override NDArray ReduceStd(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, DType dtype = null, NDArray @out = null, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
arrNDArrayThe operand (any dtype, any layout).
axis_int?The reduced axis (negative counts from the end), or null for every axis.
keepdimsboolWhen true the reduced axes stay in the result with length 1.
ddofint?Delta degrees of freedom (null is 0): the divisor is
max(n - ddof, 0).dtypeDTypeThe loop of both sums (an integer or bool input defaults to float64, every other input to its own dtype); it decides the result dtype.
outNDArrayNumPy's
out=, a float or complex array of the result's shape, or null for a fresh result:_stdruns_varinto it and takes the square root in place (StdIntoOut(NDArray, int?, bool, int, DType, NDArray)).whereNDArrayNumPy's
where=mask, or null (see ReduceVar(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?)).meanNDArrayNumPy's
mean=, or null to compute it (see ReduceVar(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?)).correctionint?NumPy's
correction=, or null (see ReduceVar(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?)).
Returns
- NDArray
outitself when given; otherwise the standard deviation: a read-only 0-d scalar when the result has no dimensions, a fresh array else.
Remarks
The boundary scope reclaims every intermediate of the port and yields only the result (the
uninitialized-shape sentinel passes through, and out, where and
mean, inputs, are never tracked).
Exceptions
- AxisError
axis_is outside the operand (a 0-d operand included, without a mask).- TypeError
A bool input with
dtype=boolor a boolmeanof a bool input (NumPy's boolean-subtract TypeError), or a text out for a float or complex input.- TypeError
An integer or bool
dtypewith a result that has dimensions, or an integer or boolout: NumPy'ssqrtoutput-cast error (a 0-d result without out truncates the root instead).- ArgumentException
A non-bool
where.- ValueError
outis read-only or does not have the result's shape; a nonzeroddoftogether withcorrection.- IncorrectShapeException
out,whereormeandoes not broadcast against the input.
ReduceVar(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?)
np.var: NumPy's _var statement for statement (VarStdNumPy(NDArray, int?, bool, int, DType, bool, NDArray)), so ddof= and
dtype= work at every size and every input gives NumPy's value, dtype and NaN / +inf.
public override NDArray ReduceVar(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, DType dtype = null, NDArray @out = null, NDArray where = null, NDArray mean = null, int? correction = null)
Parameters
arrNDArrayThe operand (any dtype, any layout).
axis_int?The reduced axis (negative counts from the end), or null for every axis.
keepdimsboolWhen true the reduced axes stay in the result with length 1.
ddofint?Delta degrees of freedom (null is 0): the divisor is
max(n - ddof, 0), soddof >= ngives +inf (NaN when every deviation is 0), never a negative variance.dtypeDTypeThe loop of both sums (an integer or bool input defaults to float64, every other input to its own dtype); it decides the result dtype, and an integer dtype truncates the mean as in NumPy.
outNDArrayNumPy's
out=, an array of the result's shape, or null for a fresh result:_varhands it to its LAST sum only and divides it in place (VarianceIntoOut(NDArray, int?, bool, int, DType, NDArray)).whereNDArrayNumPy's
where=mask, or null. A mask (anything but the C#trueliteral) takes_var's masked statements (VarStdKeywordsNumPy(NDArray, int?, bool, int, DType, NDArray, NDArray, NDArray, bool)): per-output counts, means and divisors.meanNDArrayNumPy's
mean=, the mean subtracted as given, or null to compute it (VarStdKeywordsNumPy(NDArray, int?, bool, int, DType, NDArray, NDArray, NDArray, bool) when given).correctionint?NumPy's
correction=: replaces a null or 0ddof(DdofWithCorrection(int?, int?), checked first), or null.
Returns
- NDArray
outitself when given; otherwise the variance: a read-only 0-d scalar when the result has no dimensions, a fresh array else.
Remarks
The boundary scope reclaims every intermediate of the port — the keepdims mean, the squared deviations and
the quotient temporaries — and yields only the result (the uninitialized-shape sentinel passes through, and
out, where and mean, inputs, are never tracked).
Exceptions
- AxisError
axis_is outside the operand (a 0-d operand included, without a mask).- TypeError
A bool input with
dtype=boolor a boolmeanof a bool input (NumPy's boolean-subtract TypeError), or a text out for a float or complex input (the last sum's loop resolution).- ValueError
outis read-only or does not have the result's shape (the reduce prologue's texts); a nonzeroddoftogether withcorrection.- ArgumentException
whereis not a bool array (NumPy's TypeError text).- IncorrectShapeException
out,whereormeandoes not broadcast against the input.
ResolveReturnShape(params NDArray[])
Resolves the output shape when broadcasting multiple arrays together.
public static Shape ResolveReturnShape(params NDArray[] arrays)
Parameters
arraysNDArray[]
Returns
Remarks
Extracts shapes and delegates to Shape.ResolveReturnShape
ResolveReturnShape(Shape, Shape)
Resolves the output shape when broadcasting two shapes together.
public static Shape ResolveReturnShape(Shape leftShape, Shape rightShape)
Parameters
Returns
Remarks
Delegates to Shape.ResolveReturnShape
ResolveReturnShape(params Shape[])
Resolves the output shape when broadcasting multiple shapes together.
public static Shape ResolveReturnShape(params Shape[] shapes)
Parameters
shapesShape[]
Returns
Remarks
Delegates to Shape.ResolveReturnShape
ResolveUnaryFloatReturnType(NDArray, NPTypeCode?, string)
Resolve the result dtype for a float-producing unary ufunc (sqrt/cbrt/exp/log/trig/…) using NumPy's width-based promotion (NEP50), rather than always widening to float64. NumPy picks the narrowest float that fits the input's integer width:
- bool / int8 / uint8 → float16
- int16 / uint16 / char → float32
- int32 / uint32 / int64 / uint64 → float64
- float16/float32/float64/decimal/complex → preserved
An explicit override dtype is honored (must be a float/complex
loop, matching NumPy's "no loop matching signature" error for integer targets;
ufunc is the NumPy ufunc name quoted in that error).
public NPTypeCode ResolveUnaryFloatReturnType(NDArray nd, NPTypeCode? @override, string ufunc = "sin")
Parameters
ndNDArrayoverrideNPTypeCode?ufuncstring
Returns
ResolveUnaryReturnType(NDArray, NPTypeCode?, string)
public NPTypeCode ResolveUnaryReturnType(NDArray nd, NPTypeCode? @override, string ufunc = "sin")
Parameters
ndNDArrayoverrideNPTypeCode?ufuncstring
Returns
ResolveUnaryReturnType(NDArray, Type)
public NPTypeCode ResolveUnaryReturnType(NDArray nd, Type @override)
Parameters
Returns
RightShift(NDArray, NDArray, DType, NDArray, NDArray)
Bitwise right shift (x1 >> x2), with the ufunc out=/where=/dtype=
parameters. Arithmetic shift for signed types (sign bit extended); logical shift for unsigned.
public override NDArray RightShift(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
lhsNDArrayValue operand (integer/bool/char).
rhsNDArrayShift-count operand (integer/bool/char).
dtypeDTypeOptional loop dtype override; must be an integer/char loop.
outNDArraywhereNDArrayOptional bool write mask.
Returns
- NDArray
The shifted result, or
@outwhen provided.
Rint(NDArray, DType, NDArray, NDArray)
Element-wise round-half-to-even (NumPy np.rint) using IL-generated kernels.
rint is a FLOAT-tier unary ufunc: it has no integer/bool loops (only e/f/d/g and the complex loops in NumPy), so integer/bool inputs promote to the smallest matching float — bool/int8/uint8 -> float16, int16/uint16/char -> float32, int32/uint32/int64/uint64 -> float64, floats/complex/decimal preserved (ResolveUnaryFloatReturnType(NDArray, NPTypeCode?, string)). This is the dtype behavior of sqrt/sin, NOT of np.round/around (which keep integer dtype).
The VALUE computation is round-half-to-even == Round's existing kernel (Math.Round/MathF.Round default to MidpointRounding.ToEven; complex rounds real and imag separately; decimal uses decimal.Round). Reusing that op means no new kernel: UfuncName(UnaryOp.Round) is already "rint", so out=/dtype= cast errors name 'rint'.
out=/where=/dtype= compose exactly like the other unary ufuncs (probed 2.4.2): dtype= selects the loop (must be a float/complex loop — an integer dtype raises the verbatim "No loop matching the specified signature ..."), inputs reach the loop via a same_kind cast, and a provided out receives a same_kind-cast write-back.
public override NDArray Rint(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
RollAxis(NDArray, int, int)
NumPy's np.rollaxis: axis moved to lie before position start,
the other axes keeping their order.
public override NDArray RollAxis(NDArray nd, int axis, int start = 0)
Parameters
ndNDArrayThe array.
axisintThe axis to roll (negative values count from the end).
startintThe position the axis is rolled to:
[-ndim, ndim], negative values counting from the end.
Returns
- NDArray
A view of
nd(a new view object even when no axis moves, NumPy'sa[...]).
Exceptions
- AxisError
axisis out of range, orstartis outside its range: "'start' arg requires {-n} <= start < {n + 1}, but {start} was passed in" (the start after its negative wrap, as NumPy prints it).
Roots(NDArray)
NumPy's np.roots(p): the roots of the polynomial with coefficients p (highest
degree first), the eigenvalues of its companion matrix after the leading and trailing zeros are stripped
(each trailing zero a root at 0).
public override NDArray Roots(NDArray p)
Parameters
pNDArrayThe coefficients, 1-D after
atleast_1d. This is roots' body: a 0-d input is one coefficient here, while the np.roots facade refuses it first with NumPy's dispatcher TypeError.
Returns
- NDArray
The roots: complex128 or float64 (LAPACK's eigenvalues), with the zero roots appended; an empty float64 array for no non-zero coefficient or a single one.
Exceptions
- ValueError
p is not rank 1 (
Input must be a rank-1 array.), or a text coefficient between the first and last non-empty one does not parse as a float.- NotSupportedException
Two or more non-zero coefficients and no LAPACK backend.
Round(NDArray, DType, NDArray, NDArray)
Element-wise round-half-to-even to decimals==0 places — NumPy's np.round/np.around
with no decimals argument, i.e. the rint ufunc but WITH np.round's dtype rules
(probed 2.4.2): integer/char inputs are an IDENTITY copy that PRESERVES the integer dtype (unlike
np.rint, whose float-tier would widen an int to float), floats/complex/decimal PRESERVE their
dtype, and a bool input takes the float16 tier (np.round(bool) → float16, matching the
rint ufunc's bool loop — NOT the ResolveUnaryReturnType(NDArray, Type) default of float64).
np.round is a FUNCTION, not a ufunc, so it accepts out= only — there is no
where=/dtype= ufunc kwarg (the where/dtype here are
NumSharp conveniences carried for the engine's uniform unary signature).
public override NDArray Round(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
ndNDArrayInput array; any layout (contiguous / strided / broadcast) is read correctly.
dtypeDTypeOptional NumSharp dtype-target convenience (NumPy's np.round has none); must be a float/complex loop when supplied, else the "No loop matching …" error fires (via ResolveUnaryReturnType(NDArray, Type)).
outNDArrayOptional destination; returned as-is (same instance), joined by broadcast but never stretched, and written under a same_kind cast from the loop dtype.
whereNDArrayOptional bool mask (NumSharp convenience); validated for dtype only.
Returns
- NDArray
The rounded array —
outwhen supplied, otherwise a fresh array whose dtype follows the rules above.
Exceptions
- IncorrectTypeException
A
dtypebelow Single selects no rint loop.
Round(NDArray, int, DType, NDArray)
Element-wise round to decimals places — a faithful port of NumPy 2.4.2's
PyArray_Round (numpy/_core/src/multiarray/calculation.c). For decimals != 0 NumPy is
NOT a scaled Math.Round(x, digits) (which cannot express negative digits and rounds by a different
algorithm): it composes op2(rint(op1(x, f)), f) with f = 10^|decimals| — op1=multiply,
op2=true_divide for positive decimals, op1=true_divide, op2=multiply for negative — evaluated
AT the input's own float precision (so a float32 stays float32, a float16 stays float16, and a complex
rounds its real/imag parts). This is why the values differ from a naive per-place rounder and why they are
bit-identical to NumPy (verified against 2.4.2 across float16/32/64, complex128 and integer negative
decimals). The previous implementation THREW on negative decimals (Math.Round's 0..15 digit limit)
and silently left Complex unrounded — both fixed here.
public override NDArray Round(NDArray nd, int decimals, DType dtype = null, NDArray @out = null)
Parameters
ndNDArrayInput array; any layout is read correctly (densified by Cast(NDArray, Type, bool)).
decimalsintPlaces to round to.
0routes to therintpath above. Positive rounds after the decimal point, negative to the left of it (tens, hundreds, …). MinValue is NumPy's sentinel meaning MaxValue (its own magnitude cannot be negated), which makesfoverflow to +∞ and the result NaN, matching NumPy.dtypeDTypeOptional NumSharp dtype-target (must be float/complex when supplied).
outNDArrayOptional destination. NumPy runs the composition op-by-op, so the CAST error names the FIRST op —
multiplyfor positive decimals,dividefor negative (probed 2.4.2:round(f8, 1, out=i4)→ "Cannot cast ufunc 'multiply' …";round(i4, -1, out=i4)→ "… 'divide' …", since an integer negative-decimals result is a float64 that cannot castsame_kindinto an integer out even though the no-out form succeeds). One documented micro-divergence: for a WIDENING cross-dtype out (e.g.round(float32, 1, out=float64)) NumSharp computes wholly at the INPUT precision then widens the final value, whereas NumPy chains the ufuncs into the wide out buffer (op1 at input precision, rint+op2 at out precision) — so NumPy's1.6vs NumSharp's(float64)(1.6f). This exotic combination is not exercised by the round oracle (out=null); the no-out and same-dtype-out results are bit-identical to NumPy.
Returns
- NDArray
The rounded array —
outwhen supplied, otherwise fresh.
Exceptions
- TypeError
A bool input with
decimals != 0and nodtypeoverride: NumPy raises because the float64 composition result cannot castsame_kindback to bool (message reproduced verbatim, naming multiply/divide by sign).- TypeError
An
outwhose dtype the loop result cannot reach by asame_kindcast (via ValidateOutCast(NPTypeCode, NPTypeCode, string, NPY_CASTING)).- ValueError
An
outof another SIZE thannd: PyArray_Round'sinvalid output shape, checked first (parity QA-31). Integer data atdecimals >= 0copies into the out with np.copyto's statement (assignment destination is read-only,could not broadcast input array from shape (3,4) into shape (4,3)); complex data refuses an out its parts do not broadcast to with that assignment's text.- InvalidCastException
Integer data at
decimals >= 0into an out its dtype does not cast to under same_kind (np.copyto's text, the house type of that refusal).- ArgumentException
Float data at
decimals != 0whose out does not broadcast with it:multiply(a, 10**decimals, out)'s iterator texts, the Python float listed as()(operands could not be broadcast together with shapes (3,4) () (4,3); the house type of a ufunc out's shape refusal).
SearchSorted(NDArray, NDArray, string, NDArray)
NumPy's np.searchsorted(a, v, side, sorter) (PyArray_SearchSorted): the indices at which the
elements of v would be inserted into the sorted 1-D a to keep it sorted,
the whole call — the descriptor both operands are converted to (numbers: their common dtype; text: the common
string dtype, a number formatted; StringDType without a common descriptor: Python objects), NumPy's checks in
its order, and its binary search, its monotonic carry and its sorter checks included.
public override NDArray SearchSorted(NDArray a, NDArray v, string side = "left", NDArray sorter = null)
Parameters
aNDArrayThe haystack: 1-D, sorted ascending unless
sorteris given. Any dtype, text included; any layout.vNDArrayThe keys: any dtype, shape and layout (a 0-d array for one key).
sidestring"left"(the first suitable index) or"right"(the last).sorterNDArrayIndices that sort
a, or null: 1-D, integer, ofa's size.
Returns
- NDArray
A fresh int64 array of
v's shape (0-d for a 0-d key).
Remarks
New in 0.80.0 (the np-layer dtype plan, P2): the public np.searchsorted calls this, a subclass
operand handed in as its plain view.
Exceptions
- ArgumentException
sideis not"left"/"right".- ValueError
See SearchSorted(NDArray, int, string, NDArray); or a StringDType comparison that touched a None-like NA.
- TypeError
A sorter refusal; a U array converted to StringDType (NumPy's 'safe' cast refusal); the first comparison Python refuses on the object path (
'<' not supported between instances of 'str' and 'int').- UnicodeDecodeError
A text search converts bytes that are not ASCII to the common
Udtype.- DTypePromotionError
Text with an operand that has no common dtype with it.
- NullReferenceException
aorvis null.
SearchSorted(NDArray, double, string, NDArray)
NumPy's np.searchsorted(a, v, side, sorter) (PyArray_SearchSorted) for a Python float key: the
index at which v would be inserted into the sorted 1-D a to keep it
sorted, the whole call.
public override long SearchSorted(NDArray a, double v, string side = "left", NDArray sorter = null)
Parameters
aNDArrayThe haystack: 1-D, sorted ascending unless
sorteris given. Any dtype, text included; any layout.vdoubleThe key, read as NumPy's Python float (the search runs in
promote_types(a, float64): a float32 haystack is searched in float64, as NumPy does).sidestring"left"(the first suitable index) or"right"(the last).sorterNDArrayIndices that sort
a, or null: 1-D, integer, ofa's size.
Returns
- long
The insertion index (0 to
a.size).
Remarks
New in 0.80.0 (the np-layer dtype plan, P2): the public np.searchsorted calls this, a subclass
operand handed in as its plain view.
Exceptions
- ArgumentException
sideis not"left"/"right".- ValueError
- TypeError
A sorter refusal (see the int member), or a StringDType haystack whose first comparison with the float Python refuses (
'<' not supported between instances of 'str' and 'float').- NullReferenceException
ais null.
SearchSorted(NDArray, int, string, NDArray)
NumPy's np.searchsorted(a, v, side, sorter) (PyArray_SearchSorted) for a Python int key: the
index at which v would be inserted into the sorted 1-D a to keep it
sorted, the whole call (NumPy's argument checks in its order, then the search in the operands' common dtype).
public override long SearchSorted(NDArray a, int v, string side = "left", NDArray sorter = null)
Parameters
aNDArrayThe haystack: 1-D, sorted ascending unless
sorteris given (an unsorted one gets NumPy's bisection's answer, not an error). Any dtype, text included; any layout.vintThe key, read as NumPy's Python int (a strong int32 descriptor: the search runs in
promote_types(a, int32), never casting the key down toa's dtype).sidestring"left"(the first suitable index) or"right"(the last).sorterNDArrayIndices that sort
a(typically its argsort), or null: 1-D, integer, ofa's size.
Returns
- long
The insertion index (0 to
a.size).
Remarks
New in 0.80.0 (the np-layer dtype plan, P2): the public np.searchsorted calls this, a subclass
operand handed in as its plain view. A member of its own, not the array form over a 0-d key: the key stays on
the stack, about 15x cheaper per call.
Exceptions
- ArgumentException
sideis not"left"/"right"(NumPy's two ValueError texts).- ValueError
ais not 1-D, a sorter of uint64, a sorter whose size differs froma's, or a sorter index outsideathat the search reaches.- TypeError
A sorter that is not 1-D (
could not parse sorter argument) or not integer (sorter must only contain integers), or a StringDType haystack whose first comparison with the int Python refuses ('<' not supported between instances of 'str' and 'int').- NullReferenceException
ais null.
Setdiff1d(NDArray, NDArray, bool)
NumPy's np.setdiff1d(ar1, ar2, assume_unique=False): the values of ar1 not in
ar2, ar1[isin(ar1, ar2, assume_unique=True, invert=True)] after making both
unique (or only flattening ar1 when assume_unique).
public override NDArray Setdiff1d(NDArray ar1, NDArray ar2, bool assume_unique = false)
Parameters
ar1NDArrayThe values to keep or drop.
ar2NDArrayThe values to drop.
assume_uniqueboolWhether both operands are already unique (the result is then in ar1's order, its duplicates kept).
Returns
- NDArray
A new 1-D array in
ar1's dtype, sorted unlessassume_unique; a surviving float32 / float64 NaN is NumPy's canonical positive quiet NaN.
Exceptions
- UnicodeDecodeError
The membership test's sort path decodes
Stext holding a byte that is not ASCII.- ValueError
A
StringDTypearray whose sort compares a None-like NA.
Setxor1d(NDArray, NDArray, bool)
NumPy's np.setxor1d(ar1, ar2, assume_unique=False): the sorted values found in exactly one of the
operands (each made unique first unless assume_unique).
public override NDArray Setxor1d(NDArray ar1, NDArray ar2, bool assume_unique = false)
Parameters
ar1NDArrayThe first operand.
ar2NDArrayThe second operand.
assume_uniqueboolWhether both operands are already unique (their values then are not made unique; a repeated value is then not exclusive).
Returns
- NDArray
A new 1-D array; a surviving float32 / float64 NaN is NumPy's canonical positive quiet NaN.
Exceptions
- UnicodeDecodeError
A
Uresult overStext holding a byte that is not ASCII.- DTypePromotionError
A
StringDTypeoperand beside a class the concatenation finds no common DType with.- ValueError
A
StringDTypearray whose sort compares a None-like NA.
Sign(NDArray, DType, NDArray, NDArray)
Element-wise sign function using IL-generated kernels. Returns -1, 0, or 1 based on input sign. NumPy behavior: preserves input dtype.
public override NDArray Sign(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
SignBit(NDArray, DType, NDArray, NDArray)
Test element-wise whether the IEEE sign bit is set (np.signbit). A full ufunc:
signbit(x, /, out=None, *, where=True, dtype=None), result always bool.
public override NDArray SignBit(NDArray a, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
aNDArrayInput array (any dtype except Complex).
dtypeDTypeValidate-only (NumPy parity): signbit has bool-output loops ONLY, so a non-bool request raises the no-loop IncorrectTypeException;
boolis a legal no-op.outNDArrayA location into which the result is stored; any numeric dtype (bool casts same_kind to all, True→1). The same instance is returned. If
null(andwherenull), a freshly allocated boolean array is returned.whereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
Returns
- NDArray
A boolean array (or
out), True where the element's sign bit is set.
Remarks
NumPy behaviour (numpy/_core, the signbit ufunc), all probed against 2.4.2:
- Half/Single/Double: the raw IEEE sign bit —
-0.0and a NEGATIVE NaN are True,+0.0/+inf/positive NaN False (this is NOTx < 0). - Signed integers:
x < 0(the two's-complement MSB IS the sign bit). - Unsigned integers / bool: always False.
- Decimal (no NumPy analog): strictly-negative test;
-0.0m→ False.
Single/Double take the dedicated SIMD predicate kernel (per-lane MSB extract + packed bool store); signed Int32/Int64 too (same MSB extract). Every other dtype resolves through the general unary scalar route — which already beats NumPy's own scalar signbit loops.
Exceptions
- TypeError
The input dtype is Complex — signbit has no complex loop (NumPy raises the same "not supported for the input types" TypeError; its signbit is ambiguous on complex).
- IncorrectTypeException
dtypeis a non-bool dtype (no matching loop).
Sin(NDArray, DType, NDArray, NDArray)
Element-wise sine using IL-generated kernels.
public override NDArray Sin(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Sinc(NDArray)
NumPy's np.sinc(x), the normalized sinc sin(pix) / (pix): y = pi * x, every exact
zero of y replaced by the machine epsilon of y's dtype (1e-20 for a dtype that is not float),
then sin(y) / y, so the removable singularity gives its limit 1.
public override NDArray Sinc(NDArray x)
Parameters
xNDArrayThe input, any dtype and layout (not null).
Returns
- NDArray
The values, of
pi * x's dtype: float64 for bool, integers and char; float16 / float32 / float64 kept; complex128 for complex; decimal for decimal (the double bridge).
Remarks
DefaultEngine runs the four statements as one fused np.evaluate pass.
Exceptions
- ArgumentNullException
xis null.- TypeError
A text operand:
pi * xhas no loop (NumPy's no-loop texts).- OverflowException
A decimal
xwhosepi * xleaves the decimal range.
Sinh(NDArray, DType, NDArray, NDArray)
Element-wise hyperbolic sine using IL-generated kernels.
public override NDArray Sinh(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Sort(NDArray, int?, string, object, bool?)
NumPy's np.sort(a, axis, kind, order, stable) (fromnumeric.sort over PyArray_Sort), the
whole call: a sorted copy of a, which is only read. Use SortInPlace(NDArray, int?, string, object, bool?) for
ndarray.sort.
public override NDArray Sort(NDArray a, int? axis = -1, string kind = null, object order = null, bool? stable = null)
Parameters
aNDArrayThe array (any dtype: text sorts by code points,
StringDTypein NumPy's NA order).axisint?The sorted axis (negative counts from the end), or null for the C-order flattening.
kindstringNumPy's
kind=, read from its first character (quicksort,heapsort,mergesort orstable, any case), or null for the default. It changes the answer only where NumPy's does: the stable kind's float value sort keeps every NaN's bits, and StringDType refuses the heapsort kind.orderobjectNumPy's
order=, a field name or a list of them, or null: every NumSharp dtype has no fields, so any value is refused.stablebool?NumPy's keyword-only
stable=: true asks for the stable kind; any non-null value is refused together withkind.
Returns
- NDArray
A fresh array of
a's dtype laid out ascopy(order='K')lays outa(an F input stays F), or the sorted flattening for a null axis.
Remarks
New in 0.80.0 (the np-layer dtype plan, phase PE, E5): the public np.sort applies its class
boundaries and calls this; DefaultEngine sorts with its AxisSort kernels.
Exceptions
- ValueError
An unknown
kind(sort kind must be one of 'quick', 'heap', or 'stable' (got 'x')),kindtogether withstable, or anorder, all before the array is read; aStringDTypeline of two or more elements holding an NA whose NA object is neither NaN-like nor a string.- RuntimeError
A
StringDTypearray with the heapsort kind (unsupported sort kind).- AxisError
The axis is out of range (a 0-d array refuses every axis: NumPy's sort does not ravel it first).
SortComplex(NDArray)
NumPy's np.sort_complex(a): a sorted copy along the last axis (b = array(a, copy=True);
b.sort()), in the input's own dtype, then converted to complex (astype('D')) unless it is.
public override NDArray SortComplex(NDArray a)
Parameters
aNDArrayThe input (not null).
Returns
- NDArray
A new complex128 array of
a's shape, sorted along its last axis (complex values lexicographically: real part, then imaginary part).
Remarks
The sort runs in the original dtype, so an int64 past 2^53 orders by its exact value, not by its double image; only the sorted result is widened.
Exceptions
- AxisError
A 0-d array (
axis -1 is out of bounds for array of dimension 0, which NumPy'sb.sort()raises).- ValueError
Text that is not a complex number (
complex() arg is a malformed string).
SortInPlace(NDArray, int?, string, object, bool?)
NumPy's ndarray.sort(axis, kind, order, stable) (array_sort over PyArray_Sort), the whole
call: sorts a IN PLACE along the axis, in NumPy's order of checks (the arguments, the axis,
writeability, then the sort). Use Sort(NDArray, int?, string, object, bool?) for a sorted copy.
public override void SortInPlace(NDArray a, int? axis = -1, string kind = null, object order = null, bool? stable = null)
Parameters
aNDArrayThe array sorted in place (any dtype).
axisint?The sorted axis (negative counts from the end), or null: NumSharp's extension that sorts a contiguous array's flattening in place.
kindstringNumPy's
kind=, read from its first character (quicksort,heapsort,mergesort orstable, any case), or null for the default. It changes the answer only where NumPy's does: the stable kind's float value sort keeps every NaN's bits, and StringDType refuses the heapsort kind.orderobjectNumPy's
order=, a field name or a list of them, or null: every NumSharp dtype has no fields, so any value is refused.stablebool?NumPy's keyword-only
stable=: true asks for the stable kind; any non-null value is refused together withkind.
Remarks
New in 0.80.0 (the np-layer dtype plan, phase PE, E5): NDArray.sort calls this.
Exceptions
- ValueError
An unknown
kind(sort kind must be one of 'quick', 'heap', or 'stable' (got 'x')),kindtogether withstable, or anorder, all before the array is read; a read-only array (sort array is read-only); aStringDTypeline of two or more elements holding an NA whose NA object is neither NaN-like nor a string.- RuntimeError
A
StringDTypearray with the heapsort kind (unsupported sort kind).- AxisError
The axis is out of range.
Spacing(NDArray, DType, NDArray, NDArray)
Element-wise np.spacing: the distance from each value to the adjacent representable
value in the direction AWAY from zero (one ULP). IL-generated kernels — SIMD for
float32/float64 (a bit-increment + zero-mask), scalar for the promoted-int/Half/Decimal
paths. See NumSharp.Utilities.NDSpacingMath for the exact per-dtype semantics.
public override NDArray Spacing(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
ndNDArrayInput array; its dtype selects the float loop (see the promotion table below).
dtypeDTypeExplicit loop dtype (NumPy ufunc
dtype=): must be a FLOAT loop (Half/Single/Double, or NumSharp's Decimal extension). An integer/bool or COMPLEX request has no loop — spacing is float-only — and raises NumPy's "No loop matching the specified signature" error.outNDArrayA location into which the result is stored (must be same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
Returns
- NDArray
Array of the same shape as
nd, dtype promoted per NumPy's width rule (bool/int8/uint8→float16, int16/uint16/char→float32, int32+→float64; float/decimal preserved).
Exceptions
- IncorrectTypeException
A complex
dtyperequest (no complex loop → "No loop matching …"), a complex INPUT with no dtype override (→ "ufunc 'spacing' not supported for the input types …"), an integer/booldtype(→ "No loop matching …"), or a complex input that cannot same_kind-cast to a requested real loop (→ "Cannot cast ufunc 'spacing' input …").
Sqrt(NDArray, DType, NDArray, NDArray)
Element-wise square root using IL-generated kernels.
public override NDArray Sqrt(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Square(NDArray, DType, NDArray, NDArray)
Element-wise square (x*x) using IL-generated kernels. NumPy behavior: preserves input dtype (unlike trig functions which promote to float).
public override NDArray Square(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
StdElementwise<T>(NDArray, NPTypeCode?, int?)
The flat standard deviation as a C# value of T: ReduceStd(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?) over every
element, then a value conversion.
public T StdElementwise<T>(NDArray arr, NPTypeCode? typeCode, int? ddof) where T : unmanaged
Parameters
arrNDArrayThe operand.
typeCodeNPTypeCode?NumPy's
dtype=(null: the input's own float dtype, float64 for an integer or bool input).ddofint?Delta degrees of freedom (null is 0).
Returns
- T
The standard deviation converted to
T.
Type Parameters
TThe C# type to convert the standard deviation to.
Subtract(NDArray, NDArray, DType, NDArray, NDArray)
Element-wise subtraction using IL-generated kernels. Supports all 144 type combinations with automatic type promotion.
public override NDArray Subtract(NDArray lhs, NDArray rhs, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Sum(NDArray, int?, DType, bool)
The sum without out= / initial= / where=: ReduceAdd(NDArray, int?, bool, DType, NDArray, object, NDArray) under its shipped (0.70.0)
signature, kept for callers and subclasses of that member.
public override NDArray Sum(NDArray nd, int? axis = null, DType dtype = null, bool keepdims = false)
Parameters
ndNDArrayThe array to sum.
axisint?The reduced axis, or null for every axis.
dtypeDTypeThe loop dtype, or null for NEP 50's accumulator.
keepdimsboolWhether the reduced axes stay with length 1.
Returns
Remarks
Footgun: np.sum and ndarray.sum call ReduceAdd(NDArray, int?, bool, DType, NDArray, object, NDArray) since 0.80.0, so an override of
this member no longer intercepts them; override ReduceAdd(NDArray, int?, bool, DType, NDArray, object, NDArray).
Exceptions
- AxisError
axisis out of range.
SwapAxes(NDArray, int, int)
NumPy's PyArray_SwapAxes: a view with axis1 and axis2
exchanged.
public override NDArray SwapAxes(NDArray nd, int axis1, int axis2)
Parameters
ndNDArrayThe array.
axis1intThe first axis (negative values count from the end).
axis2intThe second axis.
Returns
- NDArray
A view with the two axes swapped.
Exceptions
- AxisError
An axis is out of range: "axis1: axis …" or "axis2: axis …" (axis1 checked first).
Tan(NDArray, DType, NDArray, NDArray)
Element-wise tangent using IL-generated kernels.
public override NDArray Tan(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Tanh(NDArray, DType, NDArray, NDArray)
Element-wise hyperbolic tangent using IL-generated kernels.
public override NDArray Tanh(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Tensordot(NDArray, NDArray, int)
NumPy's np.tensordot(a, b, axes=2) with an integer axes: the sum of products over the
last axes axes of a and the first axes axes of
b - NumPy's axes_a = list(range(-axes, 0)), axes_b = list(range(0, axes)),
then the statements of Tensordot(NDArray, NDArray, int[], int[]).
public override NDArray Tensordot(NDArray a, NDArray b, int axes = 2)
Parameters
aNDArrayThe first tensor (not null).
bNDArrayThe second tensor (not null).
axesintThe number of axes to contract: 0 is the outer (tensor) product, 1 the matrix product, 2 the double contraction. A negative count contracts nothing (NumPy's
range(-axes, 0)is empty).
Returns
- NDArray
A new array of
a's kept axes followed byb's, the dot product's dtype.
Remarks
NumPy writes tensordot in Python (numpy/_core/numeric.py); DefaultEngine builds the two axis lists and
runs the list form. np.tensordot calls it after the matrix and chararray boundaries, and numpy.linalg's
Array-API tensordot directly; an override replaces both for every array whose engine it is.
Exceptions
- IndexError
More axes than an operand has (
tuple index out of range).- ValueError
Contracted extents that differ (
shape-mismatch for sum), and the final dot's refusals of text (data type must provide an itemsize).- TypeError
The final dot's refusals of text operands (NumPy's texts).
- NotSupportedException
A
StringDTypeoperand beside a number, which NumPy computes as Python objects (an object array NumSharp does not have).- NullReferenceException
aorbis null.
Tensordot(NDArray, NDArray, int[], int[])
NumPy's np.tensordot(a, b, axes=(axes_a, axes_b)): the sum of products pairing axis
axesA[k] of a with axis axesB[k] of b - each operand
transposed so its contracted axes meet, reshaped to a matrix, one dot product, and the result reshaped to the
kept axes.
public override NDArray Tensordot(NDArray a, NDArray b, int[] axesA, int[] axesB)
Parameters
aNDArrayThe first tensor (not null).
bNDArrayThe second tensor (not null).
axesAint[]The axes of
ato contract, in pairing order (negative counts from the end).axesBint[]The axes of
bto contract, paired element by element withaxesA.
Returns
- NDArray
A new array of
a's kept axes followed byb's, the dot product's dtype.
Remarks
DefaultEngine runs NumPy's statements over the operand engines' Transpose(NDArray, int[]) and
Dot(NDArray, NDArray, NDArray) and the array object's reshape, so the product takes the OpenBLAS backend when one is
installed. np.tensordot's list and (int, int) forms call it (the pair as two one-element lists,
NumPy's [axes_a] / [axes_b]), and numpy.linalg's Array-API tensordot directly.
Exceptions
- ValueError
A list that repeats a RAW axis value (
duplicate axes are not allowed in tensordot, checked first); lists of different lengths or contracted extents that differ (shape-mismatch for sum); the final dot's refusals of text.- IndexError
An axis out of range (
tuple index out of range: NumPy indexes the shape tuple with the raw axis). A mismatched extent earlier in the lists settles as the shape mismatch first, hiding a later out-of-range axis.- TypeError
The final dot's refusals of text operands (NumPy's texts).
- NotSupportedException
A
StringDTypeoperand beside a number, which NumPy computes as Python objects.- NullReferenceException
a,bor an axis list is null.
Trace(NDArray, int, int, int, DType, NDArray)
NumPy's np.trace(a, offset, axis1, axis2, dtype, out) (PyArray_Trace), the whole call: the sums
along the diagonals diagonal(NDArray, int, int, int) returns, add.reduce over its
last axis with
dtype and out.
public override NDArray Trace(NDArray a, int offset = 0, int axis1 = 0, int axis2 = 1, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayThe array (at least 2-D; any dtype, text included).
offsetintThe diagonal's offset from the main one.
axis1intThe first axis of the 2-D sub-arrays.
axis2intThe second axis of the 2-D sub-arrays.
dtypeDTypeThe sum's dtype (
dtype=), or null: then the loop ispromote_types(out.dtype, a.dtype)whenoutis given (no NEP 50 widening), NEP 50's accumulator ofaotherwise (signed integers and bool to int64, unsigned integers to uint64).outNDArrayNumPy's
out=, an array of the result's shape that receives it with unsafe casting, or null for a fresh result: the add reduction's out operand, checked by the reduce prologue (read-only first, then its rank, then its length).
Returns
- NDArray
outitself when given; otherwise the sums: a read-only 0-d result (NumPy's scalar) for 2-Da,a's shape without the two axes otherwise.
Remarks
New in 0.80.0 (the np-layer dtype plan, P1b): the public np.trace calls this, a subclass operand
handed in as its plain view.
Exceptions
- ArgumentNullException
ais null.- ValueError
diagonal(NDArray, int, int, int)'s refusals; a StringDType diagonal that cannot be reduced (empty: no identity; an NA under the None-like rule); a read-only
out("output array is read-only") or one of the wrong rank ("output parameter for reduction operation add has the wrong number of dimensions: ...").- AxisError
An axis is out of range.
- TypeError
NumPy's loop resolution refuses text: a text operand with another out class, a text out for numbers, a string
dtype.- IncorrectShapeException
out's length does not broadcast against the diagonal (NumPy's "operands could not be broadcast together with remapped shapes" text).
Transpose(NDArray, int[])
NumPy's PyArray_Transpose: a VIEW of nd whose axis i is the source axis
premute[i], or with the axes reversed when premute is null.
public override NDArray Transpose(NDArray nd, int[] premute = null)
Parameters
ndNDArrayThe array.
premuteint[]The axes in their new order (NumPy's
axes), or null foraxes=None. An empty array is NumPy'saxes=(), which only a 0-d array matches.
Returns
- NDArray
A new view sharing
nd's buffer, with permuted dimensions and strides; it keeps the source's writeability (a read-only broadcast or memmap stays read-only).
Exceptions
- ValueError
The permutation has another length than the array's rank ("axes don't match array") or names an axis twice ("repeated axis in transpose").
- AxisError
An entry of the permutation is out of range.
Trapezoid(NDArray, NDArray, double, int)
DefaultEngine's Trapezoid(NDArray, NDArray, double, int): NumPy's trapezoid for an array
y: the text route, the spacing (dx, the 1-D
points' difference reshaped along the axis, or an N-D x's difference along its own axis), the slices
y[1:] / y[:-1], the layout NumPy's reduction input has, the fused half and its sum.
public override NDArray Trapezoid(NDArray y, NDArray x = null, double dx = 1, int axis = -1)
Parameters
yNDArrayThe integrand (not null; the facade checks it and handles a numpy.matrix operand).
xNDArrayThe sample points, or null for evenly spaced samples.
dxdoubleThe spacing when
xis null.axisintThe caller's axis, read against each statement's array as NumPy reads it.
Returns
- NDArray
The integral (see trapezoid(NDArray, NDArray, double, int)): a fresh array the caller owns.
Remarks
Moved from np.trapezoid statement for statement by the np-layer dtype plan's P2. Until its phase
PE it ran under the facade's scope ([NDScopedCovered]); as a public entry point it owns its
[NDScoped] now, which reclaims what this body leaves at its own return (np.trapezoid keeps its scope
for what its own body leaves).
Exceptions
- IndexError
The axis is outside
y's rank (TrapezoidAxis(int, int)).- AxisError
An N-D
xhas no axisaxis(np.diff'snormalize_axis_index).- ValueError
A 0-D
x(np.diff's "at least one dimensional"), or a StringDTypeywhose concatenation meets an NA it cannot add.- IncorrectShapeException
The spacing does not broadcast against
y[1:] + y[:-1].- TypeError
A text
yorx: the refusal of the first NumPy statement that has no loop for it (TrapezoidText(NDArray, NDArray, double, int)).
TrimZeros(NDArray, string, int[])
NumPy's np.trim_zeros(filt, trim='fb', axis=None): filt cut to the bounding box of
its nonzero elements along the trimmed axes - the leading ('f') and / or trailing ('b')
hyperplanes that hold only zeros removed. The values decide which view comes back, so it is a computation
(the plan's borderline decision), though nothing is computed into a new buffer.
public override NDArray TrimZeros(NDArray filt, string trim = "fb", int[] axis = null)
Parameters
filtNDArrayThe input, a plain array:
np.trim_zerosdecides thenumpy.matrixandnumpy.char.chararrayclasses before it calls this member. A text array is trimmed by its truth values (an empty string is a zero), as NumPy'sargwherereads them through the dtype'snonzero.trimstringThe sides to trim:
"f"(front),"b"(back),"fb"or"bf"(both), in any case; null reads as the empty string, which is refused.axisint[]The axes to trim (a negative axis counts from the end), or null for every axis; an empty array trims nothing.
Returns
- NDArray
A view of
filtwith the zero hyperplanes cut from the sidestrimnames (an axis without a nonzero element is cut to length 0, whatevertrimsays), orfiltitself when no axis is trimmed (an emptyaxis, or a 0-dfiltwithaxisnull). The dtype and the number of dimensions arefilt's.
Remarks
NumPy's _arg_trim_zeros takes the edges from argwhere(filt)'s minimum and maximum. The
bounding box is separable, so DefaultEngine takes each trimmed axis' first and last index from
nonzero(any(filt, other axes)) instead: the same view, without every nonzero coordinate.
Exceptions
- ValueError
trimholds another spelling (unexpected character(s) in, checked first), or an axis is repeated (trim: 'fx'repeated axis in).axisargument- AxisError
An axis is out of range for
filt(axis: axis 3 is out of bounds for array of dimension 2), checked for every axis before the repeat.- NullReferenceException
filtis null (read after the trim check).
Truncate(NDArray, DType, NDArray, NDArray)
Element-wise truncation (toward zero) using IL-generated kernels. NumPy: for integer dtypes, trunc is a no-op that preserves the input dtype.
public override NDArray Truncate(NDArray nd, DType dtype = null, NDArray @out = null, NDArray where = null)
Parameters
Returns
Union1d(NDArray, NDArray)
NumPy's np.union1d(ar1, ar2), unique(concatenate((ar1, ar2), axis=None)): the sorted unique
values found in either flattened operand.
public override NDArray Union1d(NDArray ar1, NDArray ar2)
Parameters
Returns
- NDArray
A new 1-D array in the concatenation's promoted dtype; a surviving float32 / float64 NaN is NumPy's canonical positive quiet NaN, as NumPy's sort leaves it.
Exceptions
- UnicodeDecodeError
A
Uunion overStext holding a byte that is not ASCII.- DTypePromotionError
A
StringDTypeoperand beside a class the concatenation finds no common DType with.- ValueError
A
StringDTypearray whose sort compares a None-like NA.
Unique(NDArray, bool, bool, bool, int?, bool, bool)
DefaultEngine's Unique(NDArray, bool, bool, bool, int?, bool, bool): np.unique's statements on its plain views,
the checks NumPy makes before it reads text, then the computation inside a boundary scope that keeps only
the returned outputs.
public override NDArray[] 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
arNDArrayThe plain operand (only read).
return_indexboolAlso return the first-occurrence indices (along the axis, if given).
return_inverseboolAlso return the reconstruction indices.
return_countsboolAlso return the counts.
axisint?The axis, or null to flatten the operand first.
equal_nanboolNumPy's
equal_nan(the flat numeric path only).sortedboolNumPy's
sorted: accepted, the values always come back sorted (see UniqueCompute(NDArray, bool, bool, bool, int?, bool, bool)).
Returns
- NDArray[]
[values, index?, inverse?, counts?], NumPy's order; each array yielded from the scope.
Remarks
Also the body of both NDArray.unique members since the plan's phase PE (they were the unscoped
Bare and UniqueCompute calls; the checks and the outputs are the same, the internals are now
reclaimed at this method's return).
Exceptions
- AxisError
axisis out of range.- TypeError
A
StringDTypeoperand with an axis over two or more dimensions.- ValueError
A
StringDTypeoperand whose sort compares a None-like NA.
UniqueAll(NDArray)
DefaultEngine's UniqueAll(NDArray): np.unique_all's statements after its class
boundary, unique(x, return_index=True, return_inverse=True, return_counts=True, equal_nan=False), the
inverse reshaped to the operand's shape.
public override NDArray[] UniqueAll(NDArray x)
Parameters
xNDArrayThe plain operand (only read).
Returns
- NDArray[]
[values, indices, inverse_indices, counts]; the inverse has
x's shape.
Remarks
Owns its scope (a public entry since the plan's phase PE). The flat inverse that the reshape views is not returned, so the scope disposes it at this method's return (np.unique_all's scope did, before); the view holds its own reference and keeps the buffer alive.
Exceptions
- ValueError
A
StringDTypeoperand whose sort compares a None-like NA.- OutOfMemoryException
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
UniqueCounts(NDArray)
DefaultEngine's UniqueCounts(NDArray): np.unique_counts' statements after its class
boundary, unique(x, return_counts=True, equal_nan=False). Text computes through
UniqueCompute(NDArray, bool, bool, bool, int?, bool, bool); numbers take uniqueCountsFast(NDArray).
public override NDArray[] UniqueCounts(NDArray x)
Parameters
xNDArrayThe plain operand (only read).
Returns
- NDArray[]
[values, counts].
Remarks
Owns its scope (a public entry since the plan's phase PE): the internals are reclaimed at this method's return, both outputs are yielded.
Exceptions
- ValueError
A
StringDTypeoperand whose sort compares a None-like NA.- OutOfMemoryException
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
UniqueInverse(NDArray)
DefaultEngine's UniqueInverse(NDArray): np.unique_inverse's statements on its
plain views, unique(x, return_inverse=True, equal_nan=False), the inverse reshaped to the operand's
shape.
public override NDArray[] UniqueInverse(NDArray x)
Parameters
xNDArrayThe plain operand (only read).
Returns
- NDArray[]
[values, inverse_indices]; the inverse has
x's shape.
Remarks
Owns its scope (a public entry since the plan's phase PE). The flat inverse that the reshape views is not returned, so the scope disposes it at this method's return (np.unique_inverse's scope did, before); the view holds its own reference and keeps the buffer alive.
Exceptions
- ValueError
A
StringDTypeoperand whose sort compares a None-like NA.- OutOfMemoryException
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
UniqueValues(NDArray)
DefaultEngine's UniqueValues(NDArray): np.unique_values' statements after its class
boundary, unique(x, equal_nan=False, sorted=False) over the flattened operand. Text computes through
UniqueCompute(NDArray, bool, bool, bool, int?, bool, bool); numbers take the hash and sort routes of uniqueValuesFast(NDArray).
public override NDArray UniqueValues(NDArray x)
Parameters
xNDArrayThe plain operand (only read).
Returns
- NDArray
The unique values, sorted (NumPy returns its hash set's order for integers, complex and text: the documented divergence).
Remarks
Owns its scope (a public entry since the plan's phase PE): the hash / sort internals are reclaimed at this method's return instead of the facade's, the values are yielded.
Exceptions
- OutOfMemoryException
A corrupt
StringDTypecell (NumPy'sMemoryErrortext).
Unpackbits(NDArray, int?, long?, string)
NumPy's np.unpackbits(a, axis=None, count=None, bitorder='big') (io_unpack /
unpack_bits), the whole call: each uint8 element unpacked into eight 0 / 1 uint8 elements along the
axis, the inverse of Packbits(NDArray, int?, string).
public override NDArray Unpackbits(NDArray a, int? axis = null, long? count = null, string bitorder = "big")
Parameters
aNDArrayA uint8 array, read in logical order for any layout.
axisint?The axis to unpack along, or null to unpack the C-order flattened array into a 1-D result. A 0-d input is promoted to
(1,)and accepts only 0 and -1.countlong?The number of output elements along the axis: null unpacks every bit (
8 * len); a non-negative count takes that many bits (truncating, or zero-padding past the available bits); a negative count trims that many bits off the end.bitorderstring"big"or"little"; NumPy's unpack rule reads only the first character ('l'is little,'b'big), null is big.
Returns
- NDArray
A new uint8 array of 0 / 1 values of
a's rank (1-D for a null axis), F-contiguous when the input is.
Remarks
New in 0.80.0 (the np-layer dtype plan): the public np.unpackbits applies the numpy.matrix
rule and calls this. An empty input with a count that asks for elements gives zeros, where NumPy leaks
uninitialised memory.
Exceptions
- ArgumentNullException
ais null.- ValueError
bitorderis empty or begins with neither ('order' must begin with 'l' or 'b'), checked first; or-countexceeds the available bits (-count larger than number of elements).- TypeError
ais not uint8 (Expected an input array of unsigned byte data type).- AxisError
axisis out of bounds fora's rank.
UnravelIndex(NDArray, int[], char)
NumPy's np.unravel_index(indices, shape, order='C') (arr_unravel_index,
numpy/_core/src/multiarray/compiled_base.c), the whole call: the coordinates of each flat index in an
array of dimensions shape.
public override NDArray<long>[] UnravelIndex(NDArray indices, int[] shape, char order = 'C')
Parameters
indicesNDArrayAn integer (or bool) array of flat indices, of any rank and layout. Read as int64: a uint64 index at or past 2^63 wraps negative and is out of bounds, as NumPy's same_kind cast to intp makes it.
shapeint[]The dimensions to unravel into. An empty shape (NumPy's
()) is legal: its one valid index is 0, and only a 0-d index array may use it.orderchar'C'(row-major, the default) or'F'(column-major), in either case.
Returns
- NDArray<long>[]
One int64 array per dimension of
shape, each ofindices' shape: the columns of one interleaved buffer of shapeindices.shape + (len(shape),)laid out along the indices' iteration order, so every array is a strided view of that shared buffer. A 0-dindicesgives NumPy's scalars instead (fresh read-only 0-d arrays); an emptyshapewith a 0-d index gives an empty array.
Remarks
New in 0.80.0 (the np-layer dtype plan): the public np.unravel_index(NDArray, int[], char) computes
a numpy.matrix operand as a plain array and calls this.
Exceptions
- ArgumentNullException
indicesorshapeis null.- ValueError
In NumPy's order: an order letter that is not C / F / A / K in either case; a product of the dimensions that overflows int64 or is exactly -1 (
dimensions are too large; ...); then, after the TypeError, an'A'or'K'order (only 'C' or 'F' order is permitted); the first index outside[0, prod(shape))in the iteration order (index N is out of bounds for array with size M); and, for an emptyshape, an index array of rank 1 or more (multiple indices are not supported for 0d arrays, after the indices).- TypeError
indicesis neither integer nor bool (only int indices permitted).- NotSupportedException
Runtime code generation is unavailable (the IL kernel cannot be emitted).
Unwrap(NDArray, double?, int, object)
NumPy's np.unwrap(p, discont=None, axis=-1, *, period=6.283185307179586): along the axis, every jump
between neighbours larger than max(discont, period / 2) is corrected by multiples of the period
(the cumulative correction added to p[1:]).
public override NDArray Unwrap(NDArray p, double? discont = null, int axis = -1, object period = null)
Parameters
pNDArrayThe input, at least 1-D, not complex (not null).
discontdouble?The largest jump left alone, or null for
period / 2(a smaller one acts asperiod / 2).axisintThe axis to unwrap along (negative counts from the end).
periodobjectNumPy's period, a Python float or int: a boxed double (or null for
2 pi) takes the float path, a boxed long or int NumPy's integer path for an integer or bool input.
Returns
- NDArray
A new array of
p's shape: float64 (or the input's float dtype) on the float path, the integer dtype on the integer path.
Exceptions
- ArgumentNullException
pis null.- ArgumentException
periodis neither null, a double, a long nor an int.- ValueError
A 0-D
p.- AxisError
axisout of range.- TypeError
A complex
p.- OverflowException
On the integer path, a bound or the period that does not fit the input dtype (NumPy's OverflowError).
Vander(NDArray, int?, bool)
NumPy's np.vander(x, N=None, increasing=False): the Vandermonde matrix of a 1-D x,
whose columns are powers of x - x^(N-1) down to x^0, or x^0 up to
x^(N-1) when increasing is set. NumPy makes the powers with
multiply.accumulate in promote_types(x.dtype, int), so an integer matrix wraps where NumPy's
does and every float power is the product NumPy rounds, not x ** k.
public override NDArray Vander(NDArray x, int? N = null, bool increasing = false)
Parameters
xNDArrayThe 1-D input, a plain array:
np.vandercomputes anumpy.matrixoperand as a plain array before it calls this member. A 0-d or N-D array is refused.Nint?The number of columns, or null for a square matrix (
len(x)columns).increasingboolWhether the powers increase from left to right.
Returns
- NDArray
A new C-contiguous matrix of shape
(len(x), N)that owns its buffer, inpromote_types(x.dtype, int64): int64 for bool, char and the integers up to int64, float64 for uint64 and every float dtype, decimal and complex128 as they are. A fixed-width textxgives a 21-character text matrix (NumPy promotes int64 to text): the text'1'in every row for one column, an empty matrix for no column.
Remarks
NumPy's statements: v = empty((len(x), N), dtype=promote_types(x.dtype, int)); the first column
(or the last, decreasing) is 1; the others start as x and multiply.accumulate along the
columns turns column k into x^(k+1). An override must keep that product order: a float
power computed another way rounds differently.
Exceptions
- ValueError
xis not one-dimensional (x must be a one-dimensional array or sequence.), orNis negative (the allocation'snegative dimensions are not allowed).- TypeError
A fixed-width text
x(SorU) with two or more columns: the powers come frommultiply, which has no string loop (NumPy's no-loop text).- DTypePromotionError
A
StringDTypex, whateverN:promote_types(StringDType, int64)finds no common DType, before the allocation.- OverflowException
Nis null andxhas more than MaxValue elements (the column count is an int).
VarElementwise<T>(NDArray, NPTypeCode?, int?)
The flat variance as a C# value of T: ReduceVar(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?) over every element,
then a value conversion.
public T VarElementwise<T>(NDArray arr, NPTypeCode? typeCode, int? ddof) where T : unmanaged
Parameters
arrNDArrayThe operand.
typeCodeNPTypeCode?NumPy's
dtype=(null: the input's own float dtype, float64 for an integer or bool input).ddofint?Delta degrees of freedom (null is 0).
Returns
- T
The variance converted to
T.
Type Parameters
TThe C# type to convert the variance to.
VdotFunction1D(NDArray, NDArray)
np.vdot's last step (NumPy's array_vdot): a complex128 common dtype runs CDOUBLE_vdot
(ComplexDotc(Complex*, long, Complex*, long, long): zdotc for positive strides, the conjugating own loop otherwise) on the
first operand as it is; every other common dtype runs its dot function (DotFunction1D(NDArray, NDArray), the
first operand's conjugate being itself).
public override NDArray VdotFunction1D(NDArray left, NDArray right)
Parameters
leftNDArrayThe first vector (
ip1), the one conjugated.rightNDArrayThe second vector (
ip2), the same length.
Returns
- NDArray
A fresh 0-d result of the common dtype.
Remarks
Why: the former route conjugated a copy of the first operand and ran zdotu - the same sums, but the
copy flipped a NaN imaginary part's sign (NumPy: np.vdot([1+nan j], [2+3j]) is the positive NaN in
both parts) and cost a pass and an allocation.
Exceptions
- IncorrectShapeException
The vectors' lengths differ (a direct call only).
- DTypePromotionError
The operands have no common dtype.
VdotReadsFirstInPlace(NPTypeCode, long, long)
Whether np.vdot reads its first operand in place when NumPy's flattening keeps it a view at a stride other than 1 (a reversed, broadcast or stepped run), as NumPy does: true by default, NumPy's arithmetic. An engine whose dot function is slower over such a run than over a contiguous copy may answer false: the operand is then copied (C order) and the result is the dot function's over the copy, within the usual reordering bound of NumPy's.
public override bool VdotReadsFirstInPlace(NPTypeCode dtype, long stride, long n)
Parameters
dtypeNPTypeCodeThe first operand's dtype (the dot function's when it is the operands' common dtype).
stridelongThe flattened view's element stride (not 1).
nlongThe number of elements.
Returns
- bool
True to read the view in place (NumPy's bits), false to copy it first.
Remarks
Footgun: answering false gives up NumPy's exact bits for that operand - the result is the dot function's over the copy, which can differ from NumPy's in the last bits.
Vecdot(NDArray, NDArray)
The np.vecdot gufunc (n),(n)->() — x1 conjugated when
complex. Operands arrive validated; leading axes broadcast.
public override NDArray Vecdot(NDArray x1, NDArray x2)
Parameters
Returns
Remarks
float32, float64 and complex128 loops run NumPy's FLOAT_vecdot / DOUBLE_vecdot /
CDOUBLE_vecdot: each output is FLOAT_dot / DOUBLE_dot (FloatDotFor(long, long),
DoubleDotFor(long, long)) or the conjugating CDOUBLE_dotc (ComplexDotcFor(long, long))
over the core runs at the strides NumPy's gufunc gives them: an operand of the loop dtype at its own core
stride (a reversed or broadcast core takes the dot function's own loop, as in NumPy), an operand cast to the
loop dtype at unit stride (the iterator's copy lays an input's core axes out innermost,
npyiter_new_temp_array), and stride 0 for a core of one element (NumPy forces it, so the own loop runs:
a complex infinite imaginary part leaves the real part alone there). The outputs are written in C order over
the broadcast loop axes, which the gufunc member relabels into NumPy's layout.
Every other loop takes the base composition, whose values are NumPy's: the integers' dot functions wrap as the in-dtype product and sum do, bool's ORs the ANDs, float16 runs HALF_dot through the matmul kernel. So does a direct engine call the gufunc checks would refuse (0-d operands, unequal core lengths, loop axes that do not broadcast), which keeps the composition's answer or error.
Exceptions
- IncorrectShapeException
Through the base composition only: loop axes that do not broadcast (a direct call np.vecdot's checks did not validate).
Vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char)
NumPy's np.vecdot(x1, x2, out, axes, axis, keepdims, dtype, casting, order) — the gufunc (n),(n)->(),
x1 conjugated — the whole call: the argument checks, the core axis (axes= or
axis=, both operands' moved last), the core sizes, the loop dtype selects, the
product (Vecdot(NDArray, NDArray)), the kept axis under keepdims, and the
delivery into out.
public override NDArray Vecdot(NDArray x1, NDArray x2, NDArray @out, int[][] axes, int? axis, bool keepdims, DType dtype, string casting, char order)
Parameters
x1NDArrayThe first operand, at least 1-D; conjugated when complex.
x2NDArrayThe second operand, at least 1-D.
outNDArrayWhere the answer is delivered (its cast checked under
casting), or null.axesint[][]The core axis of each operand (
{x1, x2}, or{x1, x2, out}where the output entry is empty, or holds the kept axis underkeepdims), or null.axisint?The core axis of both operands, or null (the last).
keepdimsboolWhether the contracted axis stays in the result with length 1.
dtypeDTypeThe loop dtype, or null.
castingstringThe rule the input-to-loop and answer-to-out casts are checked under:
no,equiv,safe,same_kind(NumPy's default) orunsafe.ordercharThe layout of an allocated answer:
'K'(NumPy's default: the loop axes in the inputs' memory order),'C','F', or'A'(F when both inputs are F-contiguous, else C); ignored without. Lowercase letters are accepted.
Returns
- NDArray
The vector dot products, or
outitself holding them.
Remarks
New in 0.80.0 (the np-layer dtype plan, P2): the public np.vecdot calls this (the ufunc
mechanism answers for a subclass operand).
Exceptions
- TypeError
axiswithaxes; adtypewith details beyond its class; text operands or a textdtype(no vecdot loop).- ValueError
A 0-d operand; core axes of different lengths; an
axes=list of the wrong length; a read-onlyout, or one the answer does not broadcast into.- AxisError
An
axes=entry of the wrong length, or an axis out of range.- TypeError
An input cannot be cast to the loop, or the answer into
out, undercasting(NumPy's UFuncTypeError text).- ValueError
A
castingorordername NumPy refuses (casting must be one of 'no', 'equiv', 'safe', 'same_kind', 'unsafe' (got '…'),order must be one of 'C', 'F', 'A', or 'K' (got '…')), checked casting first.- TypeError
A null
casting(casting must be str, not NoneType).- IncorrectShapeException
Loop axes that do not broadcast.
- NotSupportedException
dtypeis a class without storage yet.- NullReferenceException
x2is null.
Vecmat(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char)
NumPy's np.vecmat(x1, x2, out, axes, axis, keepdims, dtype, casting, order) — the gufunc (n),(n,m)->(m),
x1 conjugated — the whole call: the argument checks, the core axes axes= names,
the core sizes, the loop dtype selects, the product
(Vecmat(NDArray, NDArray)), the result's core axis placed, and the delivery into
out.
public override NDArray Vecmat(NDArray x1, NDArray x2, NDArray @out, int[][] axes, int? axis, bool keepdims, DType dtype, string casting, char order)
Parameters
x1NDArrayThe vector operand, at least 1-D; conjugated when complex.
x2NDArrayThe matrix operand, at least 2-D.
outNDArrayWhere the answer is delivered (its cast checked under
casting), or null.axesint[][]The core axes per operand (
{(n), (n,m), (m)}, all three entries), or null.axisint?Refused for any value (the two core dimensions are distinct), or null.
keepdimsboolRefused when true.
dtypeDTypeThe loop dtype, or null.
castingstringThe rule the input-to-loop and answer-to-out casts are checked under:
no,equiv,safe,same_kind(NumPy's default) orunsafe.ordercharThe layout of an allocated answer:
'K'(NumPy's default: the loop axes in the inputs' memory order),'C','F', or'A'(F when both inputs are F-contiguous, else C); ignored without. Lowercase letters are accepted.
Returns
- NDArray
The vector-matrix products, or
outitself holding them.
Remarks
New in 0.80.0 (the np-layer dtype plan, P2): the public np.vecmat calls this (the ufunc
mechanism answers for a subclass operand).
Exceptions
- TypeError
axiswithaxes, or either given; adtypewith details beyond its class; text operands or a textdtype;keepdims.- ValueError
An operand with too few dimensions; core axes of different lengths; an
axes=list without three entries; a read-onlyout, or one the answer does not broadcast into.- AxisError
An
axes=entry of the wrong length, or an axis out of range.- TypeError
An input cannot be cast to the loop, or the answer into
out, undercasting(NumPy's UFuncTypeError text).- ValueError
A
castingorordername NumPy refuses (casting must be one of 'no', 'equiv', 'safe', 'same_kind', 'unsafe' (got '…'),order must be one of 'C', 'F', 'A', or 'K' (got '…')), checked casting first.- TypeError
A null
casting(casting must be str, not NoneType).- IncorrectShapeException
Loop axes that do not broadcast (the product's text).
- NotSupportedException
dtypeis a class without storage yet.- NullReferenceException
x2is null.
argmax_elementwise_il(NDArray)
Execute element-wise argmax reduction using IL kernels. Returns the index of the maximum value. All types including Boolean, Single, Double now use unified IL kernel path.
protected long argmax_elementwise_il(NDArray arr)
Parameters
arrNDArray
Returns
argmin_elementwise_il(NDArray)
Execute element-wise argmin reduction using IL kernels. Returns the index of the minimum value. All types including Boolean, Single, Double now use unified IL kernel path.
protected long argmin_elementwise_il(NDArray arr)
Parameters
arrNDArray
Returns
check_and_adjust_axis(NDArray, int)
NumPy's normalize_axis_index(axis, nd.ndim): axis wrapped into
[0, nd.ndim), or NumPy's AxisError naming the axis as given. Forwards to
check_and_adjust_axis(int, int, string).
public static int check_and_adjust_axis(NDArray nd, int axis)
Parameters
ndNDArrayThe array whose rank the axis addresses.
axisintThe axis; negative values count from the end.
Returns
- int
The non-negative axis.
Exceptions
- AxisError
axisis outside[-ndim, ndim).
check_and_adjust_axis(int, int)
NumPy's normalize_axis_index(axis, ndim) (C: check_and_adjust_axis): axis
wrapped into [0, ndims), or NumPy's AxisError naming the axis as given. Forwards to
check_and_adjust_axis(int, int, string).
public static int check_and_adjust_axis(int ndims, int axis)
Parameters
Returns
- int
The non-negative axis.
Exceptions
- AxisError
axisis outside[-ndims, ndims): "axis {axis} is out of bounds for array of dimension {ndims}".
check_and_adjust_axis(int, int, string)
NumPy's normalize_axis_index(axis, ndim, msg_prefix) (C: check_and_adjust_axis_msg):
axis wrapped into [0, ndims), or NumPy's AxisError with the argument
name in front of its text. Forwards to check_and_adjust_axis(int, int, string), the ONE
axis check every axis-taking function routes through.
public static int check_and_adjust_axis(int ndims, int axis, string msgPrefix)
Parameters
ndimsintThe rank the axis addresses. A 0-d operand is rank 0, so no axis fits it — the functions that treat a 0-d operand as 1-D (NumPy's
PyArray_CheckAxis: argmax, cumsum, take, compress, …) pass 1 here themselves.axisintThe axis; negative values count from the end.
msgPrefixstringThe argument name NumPy prints before the text (
"source","axis1","axisa"), ornullfor none.
Returns
- int
The non-negative axis.
Remarks
The range is tested on the value as given, BEFORE any wrap. A wrap-then-test spelling
(while (axis < 0) axis += ndim) wraps -ndim - 1 to -1 and then to ndim - 1, so
an out-of-range axis silently reduces the last axis, and on a 0-d operand (ndim == 0) it never
terminates.
Exceptions
- AxisError
axisis outside[-ndims, ndims).
cumprod_elementwise(NDArray, NPTypeCode?)
protected NDArray cumprod_elementwise(NDArray arr, NPTypeCode? typeCode)
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
cumsum_elementwise(NDArray, NPTypeCode?)
protected NDArray cumsum_elementwise(NDArray arr, NPTypeCode? typeCode)
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
max_elementwise_il(NDArray, NPTypeCode?)
Execute element-wise max reduction using IL kernels.
protected object max_elementwise_il(NDArray arr, NPTypeCode? typeCode)
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
mean_elementwise_il(NDArray, NPTypeCode?)
Execute element-wise mean using IL kernels for sum. Mean = Sum / count
protected object mean_elementwise_il(NDArray arr, NPTypeCode? typeCode)
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
min_elementwise_il(NDArray, NPTypeCode?)
Execute element-wise min reduction using IL kernels.
protected object min_elementwise_il(NDArray arr, NPTypeCode? typeCode)
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
normalize_axis_tuple(int, int, object, bool)
NumPy's normalize_axis_tuple for one integer axis: the one-element tuple of the normalized axis.
Forwards to normalize_axis_tuple(int, int, object, bool).
public static int[] normalize_axis_tuple(int axis, int ndim, object argname = null, bool allow_duplicate = false)
Parameters
axisintThe un-normalized axis.
ndimintThe rank the axis addresses.
argnameobjectThe argument name for the AxisError's prefix, or
null.allow_duplicateboolUnused for one axis (a single axis cannot repeat); kept for NumPy's signature.
Returns
- int[]
The normalized axis as a one-element array.
Exceptions
- AxisError
axisis out of range.
normalize_axis_tuple(int[], int, object, bool)
NumPy's numpy.lib.array_utils.normalize_axis_tuple: every axis of axis wrapped
into [0, ndim) (an AxisError naming the argument when one is out of range), then — unless
allow_duplicate — NumPy's "repeated axis" ValueError when two name the same axis.
Forwards to normalize_axis_tuple(int[], int, object, bool).
public static int[] normalize_axis_tuple(int[] axis, int ndim, object argname = null, bool allow_duplicate = false)
Parameters
axisint[]The un-normalized axes. Never modified: the result is a new array.
ndimintThe rank the axes address.
argnameobjectThe argument name: the AxisError's prefix, and the repeat text's
"repeated axis in.{argname}argument"null(or an empty name, for the repeat text) gives the plain texts.allow_duplicateboolWhen false (NumPy's default) a repeated axis raises; when true the repeats are kept in order.
Returns
- int[]
The normalized axes, one per input entry, in input order.
Exceptions
- AxisError
An axis is out of range (checked for every axis before any repeat).
- ValueError
Two axes are the same after normalization and duplicates are not allowed.
prod_elementwise_il(NDArray, NPTypeCode?)
Execute element-wise product reduction using IL kernels.
protected object prod_elementwise_il(NDArray arr, NPTypeCode? typeCode)
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
std_elementwise(NDArray, NPTypeCode?, int?)
The flat standard deviation as a boxed scalar of the result dtype (ReduceStd(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?) over every element).
protected object std_elementwise(NDArray arr, NPTypeCode? typeCode, int? ddof)
Parameters
arrNDArrayThe operand.
typeCodeNPTypeCode?NumPy's
dtype=, or null.ddofint?Delta degrees of freedom (null is 0).
Returns
- object
The standard deviation, boxed in its result dtype's C# type.
sum_elementwise_il(NDArray, NPTypeCode?)
Execute element-wise sum reduction using IL kernels.
protected object sum_elementwise_il(NDArray arr, NPTypeCode? typeCode)
Parameters
arrNDArraytypeCodeNPTypeCode?
Returns
var_elementwise(NDArray, NPTypeCode?, int?)
The flat variance as a boxed scalar of the result dtype (ReduceVar(NDArray, int?, bool, int?, DType, NDArray, NDArray, NDArray, int?) over every element).
protected object var_elementwise(NDArray arr, NPTypeCode? typeCode, int? ddof)
Parameters
arrNDArrayThe operand.
typeCodeNPTypeCode?NumPy's
dtype=, or null.ddofint?Delta degrees of freedom (null is 0).
Returns
- object
The variance, boxed in its result dtype's C# type (a float for a float32 input, a double for an integer, bool or complex128 input).