Skip to content

deepbox/ndarray

Math & Reductions

Element-wise arithmetic, math and logic, comparisons, sorting and reductions, with NumPy broadcasting and PyTorch-style dtype rules.

  • Math
  • Reductions

Overview

  • Binary operations broadcast like NumPy. Operands of different dtypes promote like PyTorch (int32 with float32 gives float32) instead of throwing, and a JavaScript number never changes a tensor's dtype: float32 + 1.5 stays float32, and int32 + 1.5 gives float32.
  • Float operations keep the input float dtype. Integer input to an operation with a fractional result (mean, div, exp, sqrt) gives float32, while integer reductions such as sum keep the integer dtype. argmax, argsort and nonzero return int32.
  • The function form takes tensors (add(a, b)), and the methods also accept numbers (a.add(1)). There is no matmul function: use dot, which broadcasts batch dimensions like numpy.matmul, or the matmul method.
  • std and variance use ddof = 0 as NumPy does, so pass ddof = 1 for the sample estimate. round rounds halves to even, mod and floorDiv follow the sign of the divisor, sort places NaN last, and clip throws InvalidParameterError when min is greater than max.
  • Reductions accept several axes and keepdims. The NaN-aware versions (nansum, nanmean, nanmax and others) are listed under Sparse, FFT & Advanced Ops.

Functions

88

corrcoef

function corrcoef(x: Tensor, rowvar?: boolean): Tensor;

Compute the Pearson correlation coefficient matrix.

Details

Given a 1D or 2D tensor, returns the correlation matrix. With the default rowvar = true, each row of a 2D input of shape (m, n) is a variable and each column is an observation (like NumPy); with rowvar = false the roles are swapped.

A variable with zero variance has no defined correlation, so its row and column are NaN (as in NumPy). Off-diagonal values are clipped to [-1, 1] to remove rounding noise, and the diagonal is exactly 1 for every non-constant variable.

Note that deepbox/stats corrcoef treats columns as variables.

Parameters

x
Tensor
Input tensor (1D or 2D)
rowvaroptional
boolean
Whether rows are variables (default: true)

Returns

TensorCorrelation matrix of shape (m, m) with float64 dtype

Throws

  • ShapeErrorIf input has more than 2 dimensions
  • DTypeErrorIf input has string dtype
  • InvalidParameterErrorIf there are fewer than 2 observations
  • DeviceErrorIf the tensor lives on a device; call await t.cpu() first
Example
corrcoef(tensor([[1, 2, 3, 4], [4, 3, 2, 1]]));// [[1, -1], [-1, 1]]

cov

function cov(x: Tensor, ddof?: number, rowvar?: boolean): Tensor;

Compute the covariance matrix.

Details

Given a 1D or 2D tensor, returns the covariance matrix. With the default rowvar = true, each row of a 2D input of shape (m, n) is a variable and each column is an observation (like NumPy); with rowvar = false the roles are swapped.

Uses Bessel's correction (ddof=1) by default. Entries are sum / (n - ddof) over the n observations, computed from mean-centered values.

Note that deepbox/stats cov treats columns as variables.

Parameters

x
Tensor
Input tensor (1D or 2D)
ddofoptional
number
Delta degrees of freedom (default: 1)
rowvaroptional
boolean
Whether rows are variables (default: true)

Returns

TensorCovariance matrix of shape (m, m) with float64 dtype

Throws

  • ShapeErrorIf input has more than 2 dimensions
  • DTypeErrorIf input has string dtype
  • InvalidParameterErrorIf ddof is negative or not finite, or the number of observations is not larger than ddof
  • DeviceErrorIf the tensor lives on a device; call await t.cpu() first
Example
cov(tensor([[1, 2, 3], [4, 5, 6]])); // [[1, 1], [1, 1]]cov(tensor([2, 4, 6]), 0);           // [[8 / 3]]

tensordot

function tensordot(a: Tensor, b: Tensor, axes?: TensordotAxes): Tensor;

Tensor dot product along specified axes.

Details

Contracts a and b over the given axes, generalizing matmul and dot.

If axes is a number N, contracts the last N axes of a with the first N axes of b. If axes is a pair, axes[0] lists the axes of a and axes[1] the matching axes of b; each entry may be a single axis or an array, and negative axes count from the end. The output shape is the remaining axes of a followed by the remaining axes of b.

Result dtype: equal dtypes are kept (float32 stays float32, int64 stays int64 and is computed exactly), bool, uint8 and int32 mixed together give the wider one, a float16, bfloat16 or float32 operand with bool or uint8 keeps its float dtype, and any other combination (including int64 with another dtype) gives float64. Floats are accumulated in float64.

Parameters

a
Tensor
First tensor
b
Tensor
Second tensor
axesoptional
TensordotAxes
Number of axes to contract, or [axesA, axesB] (default: 2)

Returns

TensorContracted tensor

Throws

  • InvalidParameterErrorIf axes holds non-integer, out-of-range or repeated axes
  • ShapeErrorIf contracted axes have mismatched sizes
  • DTypeErrorIf tensors have string dtype
  • DeviceErrorIf a tensor lives on a device; call await t.cpu() first
  • DataValidationErrorIf an int64 result overflows
Example
const a = tensor([[1, 2, 3], [4, 5, 6]]);const b = tensor([[1, 4], [2, 5], [3, 6]]);tensordot(a, b, 1);           // same as matmul: [[14, 32], [32, 77]]tensordot(a, b, [[1], [0]]);  // same resulttensordot(a, b, 0);           // outer product, shape [2, 3, 3, 2]

dot

function dot(a: Tensor, b: Tensor): Tensor;

Compute dot product or matrix multiplication.

Details

Supported cases: - Both 1-D (vector, vector): inner product, returns a 0-d tensor - Both 2-D (matrix, matrix): standard matrix multiplication (m,k) x (k,n) -> (m,n) - 2-D x 1-D (matrix, vector): matrix-vector product (m,k) x (k,) -> (m,) - 1-D x 2-D (vector, matrix): vector-matrix product (k,) x (k,n) -> (n,) - 3-D and higher: batched matrix multiplication with numpy.matmul rules. The last two axes are the matrices and the leading axes are batch dimensions, aligned from the right and broadcast: two batch dimensions are compatible when they are equal or one of them is 1, and a missing batch dimension counts as 1. For example (b,m,k) x (b,k,n) -> (b,m,n), (1,m,k) x (3,k,n) -> (3,m,n), (2,1,m,k) x (3,k,n) -> (2,3,m,n), and (b,m,k) x (k,n) -> (b,m,n). - 1-D with 3-D or higher: the vector is promoted like numpy.matmul, so (b,m,k) x (k,) -> (b,m) and (k,) x (b,k,n) -> (b,n).

Both operands must have the same dtype. The only mixed case allowed is float32 with float64, which gives float64. Float products are accumulated in float64. int32 results wrap around like NumPy, bool results are the logical product (OR of ANDs), and int64 results throw if they leave the int64 range. 0 * Infinity and 0 * NaN give NaN as usual.

Unlike numpy.dot, 0-d operands are rejected (use mul), and N-D operands are multiplied as broadcast batches (the numpy.matmul rule) rather than summed over every leading axis of the left operand and the second-to-last axis of the right.

Parameters

a
Tensor
First tensor
b
Tensor
Second tensor

Returns

TensorDot product result

Throws

  • DTypeErrorIf a dtype is string or the dtypes are incompatible
  • ShapeErrorIf an operand is 0-d, the inner dimensions differ, or the batch dimensions cannot be broadcast
  • DataValidationErrorIf an int64 result overflows
Example
import { dot, ones, tensor } from "deepbox/ndarray"; dot(tensor([1, 2, 3]), tensor([4, 5, 6])); // 32 (0-d tensor)dot(tensor([[1, 2], [3, 4]]), tensor([[5, 6], [7, 8]])); // [[19, 22], [43, 50]] // Batch dimensions broadcast: (1, 2, 2) x (3, 2, 2) -> (3, 2, 2)dot(ones([1, 2, 2]), ones([3, 2, 2])).shape; // [3, 2, 2]

abs

function abs(t: Tensor): Tensor;

Element-wise absolute value.

Returns |x| for each element. The most negative int32/int64 value has no positive counterpart and wraps to itself, as in NumPy.

Parameters

t
Tensor
Input tensor

Returns

TensorTensor of the same dtype and shape

Throws

  • DTypeErrorFor string tensors
Example
import { abs, tensor } from 'deepbox/ndarray'; const x = tensor([-1, 2, -3]);const result = abs(x);  // [1, 2, 3]

acos

function acos(t: Tensor): Tensor;

Element-wise inverse cosine, returning angles in [0, pi].

Inputs outside [-1, 1] give NaN.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, acos } from "deepbox/ndarray"; acos(tensor([1, 0])).toArray(); // [0, 1.5707963267948966]

acosh

function acosh(t: Tensor): Tensor;

Element-wise inverse hyperbolic cosine, returning values in [0, Infinity).

Inputs below 1 give NaN.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, acosh } from "deepbox/ndarray"; acosh(tensor([1, 2])).toArray(); // [0, 1.3169578969248166]

add

function add(a: Tensor, b: Tensor): Tensor;

Element-wise addition.

The operands are promoted to a common dtype (see the module notes). Shapes follow NumPy broadcasting (a 0-d tensor broadcasts against anything). For two bool tensors the result is the logical OR, as in NumPy. Integer dtypes wrap on overflow.

Parameters

a
Tensor
First tensor
b
Tensor
Second tensor

Returns

TensorTensor containing the element-wise sum, of the promoted dtype

Throws

  • DTypeErrorIf either tensor has string dtype
  • ShapeErrorIf the shapes do not broadcast
Example
import { add, tensor } from 'deepbox/ndarray'; add(tensor([1, 2, 3]), tensor([10, 20, 30]));  // [11, 22, 33]

addScalar

function addScalar(t: Tensor, s: number): Tensor;

Add a scalar value to all elements of a tensor.

Float tensors keep their dtype. Integer tensors keep theirs for integer scalars (wrapping on overflow); a fractional scalar gives a float32 result, as in PyTorch. bool tensors produce int32 (or float32).

Parameters

t
Tensor
Input tensor
s
number
Scalar value to add

Returns

TensorNew tensor with scalar added to all elements

Throws

  • DTypeErrorFor string tensors
Example
import { addScalar, tensor } from 'deepbox/ndarray'; const x = tensor([1, 2, 3]);const result = addScalar(x, 10);  // [11, 12, 13]

all

function all(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Test whether all elements are true (non-zero) over the given axes.

NaN counts as true. The result is a bool tensor, and all of an empty reduction is true.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, tests all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorBool tensor

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
all(tensor([1, 2, 3]));  // trueall(tensor([1, 0, 3]));  // false

allclose

function allclose(a: Tensor, b: Tensor, rtol?: number, atol?: number, equalNan?: boolean): boolean;

Test whether all corresponding elements are close within tolerance.

Returns a single boolean (not a tensor) indicating if ALL elements pass the closeness test of isclose. Stops at the first mismatch. Tensors whose shapes cannot broadcast are never close, so the result is false instead of an error. Empty broadcast results are vacuously close.

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor
rtoloptional
number
Relative tolerance (default: 1e-5)
atoloptional
number
Absolute tolerance (default: 1e-8)
equalNanoptional
boolean
Treat NaN as close to NaN (default: false)

Returns

booleanTrue if all elements are close, false otherwise

Throws

  • InvalidParameterErrorIf rtol or atol is negative or NaN
  • DTypeErrorFor string tensors

any

function any(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Test whether any element is true (non-zero) over the given axes.

NaN counts as true. The result is a bool tensor, and any of an empty reduction is false.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, tests all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorBool tensor

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
any(tensor([0, 0, 1, 0]));  // trueany(tensor([0, 0, 0]));     // false

argmax

function argmax(t: Tensor, axis?: Axis, keepdims?: boolean): Tensor;

Index of the maximum value along an axis (NumPy argmax).

The first occurrence wins on ties. NaN propagates: the result is the index of the first NaN in the slice. Without axis the tensor is flattened and the index refers to the flattened (row-major) order. The result is always int32. int64 values are compared exactly.

Parameters

t
Tensor
Input tensor
axisoptional
Axis
Axis to search along; omit to search the flattened tensor
keepdimsoptional
boolean
If true, the reduced axis stays as a size-1 dimension (all axes when axis is omitted)

Returns

Tensorint32 tensor of indices

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf the searched slice is empty or axis is out of range
Example
import { argmax, tensor } from 'deepbox/ndarray'; const x = tensor([[1, 9, 3], [7, 2, 8]]);argmax(x);     // 1 (flattened index)argmax(x, 1);  // [1, 2]argmax(x, 0);  // [1, 0, 1]

argmin

function argmin(t: Tensor, axis?: Axis, keepdims?: boolean): Tensor;

Index of the minimum value along an axis (NumPy argmin).

The first occurrence wins on ties. NaN propagates: the result is the index of the first NaN in the slice. Without axis the tensor is flattened and the index refers to the flattened (row-major) order. The result is always int32. int64 values are compared exactly.

Parameters

t
Tensor
Input tensor
axisoptional
Axis
Axis to search along; omit to search the flattened tensor
keepdimsoptional
boolean
If true, the reduced axis stays as a size-1 dimension (all axes when axis is omitted)

Returns

Tensorint32 tensor of indices

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf the searched slice is empty or axis is out of range
Example
import { argmin, tensor } from 'deepbox/ndarray'; const x = tensor([[4, 9, 3], [7, 2, 8]]);argmin(x);     // 4 (flattened index)argmin(x, 1);  // [2, 1]

argsort

function argsort(t: Tensor, axis?: Axis | undefined, descending?: boolean): Tensor;

Return the indices that would sort the tensor along a given axis.

The sort is stable: equal values keep their original relative order, also for descending = true (ties are not reversed). NaNs are treated as larger than every other value, so they are last for ascending and first for descending order. The result has dtype int32 and the same shape as t.

Parameters

t
Tensor
Input tensor (any numeric dtype, including int64)
axisoptional
Axis | undefined
Axis to sort along (default: -1, the last axis)
descendingoptional
boolean
Order from largest to smallest (default: false)

Returns

Tensor

Throws

  • DTypeErrorIf the tensor has string dtype
  • InvalidParameterErrorIf axis is out of range
Example
import { tensor, argsort } from "deepbox/ndarray"; argsort(tensor([3, 1, 2])).toArray(); // [1, 2, 0]argsort(tensor([1, 2, 2, 3]), -1, true).toArray(); // [3, 1, 2, 0]

arrayEqual

function arrayEqual(a: Tensor, b: Tensor, equalNan?: boolean): boolean;

Test for exact array equality (shape, dtype, and all values).

Returns a single boolean indicating if tensors are identical. Unlike NumPy's array_equal, differing dtypes are never equal. NaN is unequal to itself unless equalNan is true.

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor
equalNanoptional
boolean
Treat NaN elements at the same position as equal (default: false)

Returns

booleanTrue if all elements are equal, false otherwise

asin

function asin(t: Tensor): Tensor;

Element-wise inverse sine, returning angles in [-pi/2, pi/2].

Inputs outside [-1, 1] give NaN.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, asin } from "deepbox/ndarray"; asin(tensor([0, 1])).toArray(); // [0, 1.5707963267948966]

asinh

function asinh(t: Tensor): Tensor;

Element-wise inverse hyperbolic sine.

Defined for all real inputs.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, asinh } from "deepbox/ndarray"; asinh(tensor([0, 1])).toArray(); // [0, 0.881373587019543]

atan

function atan(t: Tensor): Tensor;

Element-wise inverse tangent, returning angles in (-pi/2, pi/2).

Defined for all real inputs; atan(±Infinity) is ±pi/2.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, atan } from "deepbox/ndarray"; atan(tensor([0, 1])).toArray(); // [0, 0.7853981633974483]

atan2

function atan2(y: Tensor, x: Tensor): Tensor;

Element-wise arctangent of y / x, using the signs of both arguments to pick the quadrant. Results lie in [-pi, pi]; atan2(0, 0) is 0.

y and x are broadcast against each other (NumPy rules) and may have different dtypes. The result has the promoted float dtype of the two (integer and bool operands give float32) and lives on the device of y.

Parameters

y
Tensor
Numerator (ordinate) tensor
x
Tensor
Denominator (abscissa) tensor

Returns

TensorNew float tensor with the broadcast shape

Throws

  • DTypeErrorIf either tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
  • ShapeErrorIf the shapes are not broadcast-compatible
Example
import { tensor, atan2 } from "deepbox/ndarray"; atan2(tensor([1, -1]), tensor([-1, -1])).toArray(); // [2.356194490192345, -2.356194490192345]

atanh

function atanh(t: Tensor): Tensor;

Element-wise inverse hyperbolic tangent.

atanh(±1) is ±Infinity; inputs outside [-1, 1] give NaN.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, atanh } from "deepbox/ndarray"; atanh(tensor([0, 0.5])).toArray(); // [0, 0.5493061443340548]

cbrt

function cbrt(t: Tensor): Tensor;

Element-wise cube root.

Parameters

t
Tensor

Returns

Tensor

Example
import { cbrt, tensor } from 'deepbox/ndarray'; const x = tensor([8, 27, 64]);const result = cbrt(x);  // [2, 3, 4]

ceil

function ceil(t: Tensor): Tensor;

Element-wise ceil (round up).

Float input keeps its dtype, integer input is returned unchanged as the same integer dtype, and bool input gives float32.

Parameters

t
Tensor

Returns

Tensor

clip

function clip(t: Tensor, min?: number, max?: number): Tensor;

Clip (limit) values in tensor.

Details

Given an interval, values outside the interval are clipped to interval edges. Either bound may be omitted. NaN elements stay NaN, and a NaN bound turns every element into NaN (NumPy semantics).

Integer tensors keep their dtype when the bounds are integers inside the dtype's range. An integer bound outside the range widens the result (to int32 for uint8 and bool tensors when the bounds fit it, otherwise to int64); a fractional or NaN bound gives float32 (a number scalar never upcasts a tensor to float64). Infinite bounds are treated as no bound.

Parameters

t
Tensor
Input tensor
minoptional
number
Lower bound. If undefined, no lower clipping
maxoptional
number
Upper bound. If undefined, no upper clipping

Returns

TensorNew tensor of the same shape

Throws

  • InvalidParameterErrorIf min > max
  • DTypeErrorFor string tensors
Example
import { clip, tensor } from 'deepbox/ndarray'; const x = tensor([1, 2, 3, 4, 5]);const result = clip(x, 2, 4);  // [2, 2, 3, 4, 4]

cos

function cos(t: Tensor): Tensor;

Element-wise cosine of angles in radians.

Defined for all finite inputs; cos(±Infinity) and cos(NaN) are NaN.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, cos } from "deepbox/ndarray"; cos(tensor([0, Math.PI], { dtype: "float64" })).toArray(); // [1, -1]

cosh

function cosh(t: Tensor): Tensor;

Element-wise hyperbolic cosine.

Overflows to Infinity for magnitudes above about 710.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, cosh } from "deepbox/ndarray"; cosh(tensor([0, 1])).toArray(); // [1, 1.5430806348152437]

cumprod

function cumprod(t: Tensor, axis?: Axis): Tensor;

Cumulative product along an axis.

Each output element is the product of all elements up to and including it along the axis. If axis is omitted the input is flattened first, so the result is 1-D (NumPy semantics). int64 stays int64 and int32, uint8 and bool give int32, both throwing on overflow; float dtypes are kept (accumulated in float64, rounded once per element).

Parameters

t
Tensor
Input tensor
axisoptional
Axis
Axis to accumulate along; omit to accumulate over the flattened tensor

Returns

TensorTensor of cumulative products; same shape as t when axis is given, shape [t.size] otherwise

Throws

  • DTypeErrorIf t has string dtype
  • DataValidationErrorIf an integer product overflows
  • InvalidParameterErrorIf axis is out of range
Example
import { tensor, cumprod } from 'deepbox/ndarray'; cumprod(tensor([1, 2, 3, 4]));  // [1, 2, 6, 24]

cumsum

function cumsum(t: Tensor, axis?: Axis): Tensor;

Cumulative sum along an axis.

Each output element is the sum of all elements up to and including it along the axis. If axis is omitted the input is flattened first, so the result is 1-D (NumPy semantics). int64 stays int64 and int32, uint8 and bool give int32, both throwing on overflow; float dtypes are kept (accumulated in float64, rounded once per element).

Parameters

t
Tensor
Input tensor
axisoptional
Axis
Axis to accumulate along; omit to accumulate over the flattened tensor

Returns

TensorTensor of cumulative sums; same shape as t when axis is given, shape [t.size] otherwise

Throws

  • DTypeErrorIf t has string dtype
  • DataValidationErrorIf an integer sum overflows
  • InvalidParameterErrorIf axis is out of range
Example
import { tensor, cumsum } from 'deepbox/ndarray'; cumsum(tensor([1, 2, 3, 4]));  // [1, 3, 6, 10]cumsum(tensor([[1, 2], [3, 4]]), 0);  // [[1, 2], [4, 6]]cumsum(tensor([[1, 2], [3, 4]]));     // [1, 3, 6, 10]

diff

function diff(t: Tensor, n?: number, axis?: Axis): Tensor;

n-th discrete difference along an axis.

The first difference is out[i] = a[i + 1] - a[i] along axis; higher orders apply it repeatedly. The axis shrinks by n (down to length 0). int64 stays int64 and int32, uint8 and bool give int32, both throwing on overflow; float dtypes are kept.

Parameters

t
Tensor
Input tensor
noptional
number
Number of times to difference; a non-negative integer (default 1)
axisoptional
Axis
Axis to difference along (default: last axis)

Returns

TensorTensor of differences; with n = 0 the input itself

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf n is not a non-negative integer or axis is out of range
Example
import { tensor, diff } from 'deepbox/ndarray'; diff(tensor([1, 3, 6, 10]));     // [2, 3, 4]diff(tensor([1, 3, 6, 10]), 2);  // [1, 1]

div

function div(a: Tensor, b: Tensor): Tensor;

Element-wise true division.

Computes a / b element by element. The operands are promoted to a common dtype first. Float dtypes keep their dtype; integer and bool operands produce float32, as in PyTorch. Division by zero follows IEEE 754 (Infinity, -Infinity or NaN).

Parameters

a
Tensor
Numerator tensor
b
Tensor
Denominator tensor

Returns

TensorTensor containing element-wise quotient

Throws

  • DTypeErrorIf either tensor has string dtype
  • ShapeErrorIf the shapes do not broadcast
Example
import { div, tensor } from 'deepbox/ndarray'; const a = tensor([10, 20, 30]);const b = tensor([2, 4, 5]);const result = div(a, b);  // [5, 5, 6]

equal

function equal(a: Tensor, b: Tensor): Tensor;

Element-wise equality.

NaN is not equal to anything, including itself. int64 tensors compare exactly against any numeric dtype.

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

Tensorbool tensor with the broadcast shape

Throws

  • DTypeErrorFor string tensors
  • ShapeErrorIf the shapes do not broadcast

exp

function exp(t: Tensor): Tensor;

Element-wise exponential.

Output dtype: the input's float dtype; integer and bool input gives float32. Tensors on a device with a kernel backend are computed on the device and keep their device dtype.

Parameters

t
Tensor
Input tensor

Returns

TensorTensor with exp(x) for each element

Throws

  • DTypeErrorIf t has string dtype
Example
import { exp, tensor } from 'deepbox/ndarray'; exp(tensor([0, 1]));  // [1, 2.718281828459045]

exp2

function exp2(t: Tensor): Tensor;

Element-wise base-2 exponential.

Parameters

t
Tensor

Returns

Tensor

expm1

function expm1(t: Tensor): Tensor;

Element-wise exp(x) - 1.

More accurate than exp(x) - 1 for small x.

Parameters

t
Tensor

Returns

Tensor

floor

function floor(t: Tensor): Tensor;

Element-wise floor (round down).

Float input keeps its dtype, integer input is returned unchanged as the same integer dtype, and bool input gives float32.

Parameters

t
Tensor

Returns

Tensor

floorDiv

function floorDiv(a: Tensor, b: Tensor): Tensor;

Element-wise floor division.

Computes the largest integer less than or equal to the quotient, the same as NumPy's floor_divide (Python //): floorDiv(1, 0.1) is 9 because 0.1 is slightly larger than one tenth. Integer division by zero yields 0. The operands are promoted to a common dtype.

Parameters

a
Tensor
Dividend
b
Tensor
Divisor

Returns

TensorTensor of the promoted dtype

Throws

  • DTypeErrorIf either tensor has string dtype
  • ShapeErrorIf the shapes do not broadcast
Example
import { floorDiv, tensor } from 'deepbox/ndarray'; const a = tensor([7, 8, 9]);const b = tensor([3, 3, 3]);const result = floorDiv(a, b);  // [2, 2, 3]

greater

function greater(a: Tensor, b: Tensor): Tensor;

Element-wise greater than comparison (a > b).

Returns a boolean tensor where each element is true (1) if the corresponding element in a is greater than the element in b. Comparisons with NaN are false.

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

Tensorbool tensor with the broadcast shape

Throws

  • DTypeErrorFor string tensors
  • ShapeErrorIf the shapes do not broadcast

greaterEqual

function greaterEqual(a: Tensor, b: Tensor): Tensor;

Element-wise greater than or equal comparison (a >= b).

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

Tensorbool tensor with the broadcast shape

Throws

  • DTypeErrorFor string tensors
  • ShapeErrorIf the shapes do not broadcast

isclose

function isclose(a: Tensor, b: Tensor, rtol?: number, atol?: number, equalNan?: boolean): Tensor;

Element-wise test for approximate equality within tolerance.

Returns true where: |a - b| <= (atol + rtol * |b|)

The formula is not symmetric: rtol scales with b. NaN is never close (unless equalNan is true and both are NaN), and an infinity is only close to the same infinity. int64 values are compared after conversion to double.

Useful for floating-point comparisons where exact equality is unreliable.

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor
rtoloptional
number
Relative tolerance (default: 1e-5)
atoloptional
number
Absolute tolerance (default: 1e-8)
equalNanoptional
boolean
Treat NaN as close to NaN (default: false)

Returns

Tensorbool tensor with the broadcast shape

Throws

  • InvalidParameterErrorIf rtol or atol is negative or NaN
  • DTypeErrorFor string tensors
  • ShapeErrorIf the shapes do not broadcast

isfinite

function isfinite(t: Tensor): Tensor;

Element-wise test for finite values (not NaN, not Inf).

Returns true (1) for finite elements, false (0) for NaN or Inf. Integer and bool tensors are always finite.

Parameters

t
Tensor
Input tensor

Returns

Tensorbool tensor with the same shape

Throws

  • DTypeErrorFor string tensors

isinf

function isinf(t: Tensor): Tensor;

Element-wise test for infinity (+Inf or -Inf).

Returns true (1) for infinite elements, false (0) otherwise. Note: NaN is NOT considered infinite.

Parameters

t
Tensor
Input tensor

Returns

Tensorbool tensor with the same shape

Throws

  • DTypeErrorFor string tensors

isnan

function isnan(t: Tensor): Tensor;

Element-wise test for NaN (Not a Number) values.

Returns true (1) for NaN elements, false (0) otherwise. Integer and bool tensors never contain NaN.

Parameters

t
Tensor
Input tensor

Returns

Tensorbool tensor with the same shape

Throws

  • DTypeErrorFor string tensors

less

function less(a: Tensor, b: Tensor): Tensor;

Element-wise less than comparison (a < b).

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

Tensorbool tensor with the broadcast shape

Throws

  • DTypeErrorFor string tensors
  • ShapeErrorIf the shapes do not broadcast

lessEqual

function lessEqual(a: Tensor, b: Tensor): Tensor;

Element-wise less than or equal comparison (a <= b).

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

Tensorbool tensor with the broadcast shape

Throws

  • DTypeErrorFor string tensors
  • ShapeErrorIf the shapes do not broadcast

log

function log(t: Tensor): Tensor;

Element-wise natural logarithm.

Output dtype: the input's float dtype; integer and bool input gives float32. log(0) is -Infinity and the log of a negative number is NaN.

Parameters

t
Tensor
Input tensor

Returns

TensorTensor with log(x) for each element

Throws

  • DTypeErrorIf t has string dtype
Example
import { log, tensor } from 'deepbox/ndarray'; const x = tensor([1, 2.71828, 7.389]);const result = log(x);  // [0, 1, 2]

log1p

function log1p(t: Tensor): Tensor;

Element-wise log(1 + x).

More accurate than log(1 + x) for small x.

Parameters

t
Tensor

Returns

Tensor

log2

function log2(t: Tensor): Tensor;

Element-wise base-2 logarithm.

Parameters

t
Tensor

Returns

Tensor

log10

function log10(t: Tensor): Tensor;

Element-wise base-10 logarithm.

Parameters

t
Tensor

Returns

Tensor

logicalAnd

function logicalAnd(a: Tensor, b: Tensor): Tensor;

Element-wise logical AND.

Returns true (1) where both inputs are non-zero (truthy), false (0) otherwise. Inputs broadcast against each other (NumPy rules).

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

TensorBoolean tensor with AND results

Throws

  • DTypeErrorIf an input has string dtype
  • ShapeErrorIf the shapes cannot be broadcast
Example
const a = tensor([1, 0, 1]);const b = tensor([1, 1, 0]);logicalAnd(a, b);  // tensor([1, 0, 0])

logicalNot

function logicalNot(t: Tensor): Tensor;

Element-wise logical NOT.

Returns true (1) for zero elements, false (0) for non-zero elements. Inverts the truthiness of each element.

Parameters

t
Tensor
Input tensor

Returns

TensorBoolean tensor with NOT results

Example
const t = tensor([1, 0, 5, 0]);logicalNot(t);  // tensor([0, 1, 0, 1])

logicalOr

function logicalOr(a: Tensor, b: Tensor): Tensor;

Element-wise logical OR.

Returns true (1) where at least one input is non-zero (truthy). Inputs broadcast against each other (NumPy rules).

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

TensorBoolean tensor with OR results

Throws

  • DTypeErrorIf an input has string dtype
  • ShapeErrorIf the shapes cannot be broadcast
Example
const a = tensor([1, 0, 0]);const b = tensor([1, 1, 0]);logicalOr(a, b);  // tensor([1, 1, 0])

logicalXor

function logicalXor(a: Tensor, b: Tensor): Tensor;

Element-wise logical XOR (exclusive OR).

Returns true (1) where exactly one input is non-zero (true but not both). Inputs broadcast against each other (NumPy rules).

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

TensorBoolean tensor with XOR results

Throws

  • DTypeErrorIf an input has string dtype
  • ShapeErrorIf the shapes cannot be broadcast
Example
const a = tensor([1, 0, 1, 0]);const b = tensor([1, 1, 0, 0]);logicalXor(a, b);  // tensor([0, 1, 1, 0])

max

function max(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Maximum value over the given axes.

NaN propagates: the maximum of any slice containing NaN is NaN. The output keeps the input dtype.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, the maximum of all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of maximum values

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf the reduction has no elements, or an axis is invalid
Example
import { tensor, max } from 'deepbox/ndarray'; max(tensor([3, 1, 4, 1, 5]));  // 5max(tensor([[1, 5], [3, 2]]), 1);  // [5, 3]

maximum

function maximum(a0: Tensor, b0: Tensor): Tensor;

Element-wise maximum of two tensors.

NaN propagates: if either element is NaN the result is NaN, as in NumPy's maximum (not fmax).

Parameters

a0
Tensor
b0
Tensor

Returns

TensorTensor of the promoted dtype with the broadcast shape

Throws

  • DTypeErrorIf either tensor has string dtype
  • ShapeErrorIf the shapes do not broadcast
Example
import { maximum, tensor } from 'deepbox/ndarray'; const a = tensor([1, 5, 3]);const b = tensor([4, 2, 6]);const result = maximum(a, b);  // [4, 5, 6]

mean

function mean(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Arithmetic mean over the given axes.

Float input keeps its dtype and integer or bool input gives float32. Sums are accumulated in float64, so integer inputs cannot overflow, and the result is rounded once. The mean of an empty reduction is NaN.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, the mean of all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of means; NaN where the reduction is empty

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
import { mean, tensor } from 'deepbox/ndarray'; const x = tensor([[1, 2], [3, 4]]);mean(x);     // 2.5mean(x, 0);  // [2, 3]mean(x, 1);  // [1.5, 3.5]

median

function median(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Median over the given axes.

For an even number of elements this is the mean of the two middle values. NaN propagates: the median of any slice containing NaN is NaN. Float input keeps its dtype and integer or bool input gives float32. Uses quickselect, so it takes O(n) average time per slice.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, the median of all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of medians

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf the reduction has no elements, or an axis is invalid
Example
import { tensor, median } from 'deepbox/ndarray'; median(tensor([1, 3, 5, 7, 9]));  // 5median(tensor([1, 2, 3, 4]));     // 2.5 const t3 = tensor([[1, 3], [2, 4]]);median(t3, 0);  // [1.5, 3.5]median(t3, 1);  // [2, 3]

min

function min(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Minimum value over the given axes.

NaN propagates: the minimum of any slice containing NaN is NaN. The output keeps the input dtype.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, the minimum of all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of minimum values

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf the reduction has no elements, or an axis is invalid
Example
import { tensor, min } from 'deepbox/ndarray'; min(tensor([3, 1, 4, 1, 5]));  // 1min(tensor([[1, 5], [3, 2]]), 0);  // [1, 2]

minimum

function minimum(a0: Tensor, b0: Tensor): Tensor;

Element-wise minimum of two tensors.

NaN propagates: if either element is NaN the result is NaN (NumPy's minimum).

Parameters

a0
Tensor
b0
Tensor

Returns

TensorTensor of the promoted dtype with the broadcast shape

Throws

  • DTypeErrorIf either tensor has string dtype
  • ShapeErrorIf the shapes do not broadcast
Example
import { minimum, tensor } from 'deepbox/ndarray'; const a = tensor([1, 5, 3]);const b = tensor([4, 2, 6]);const result = minimum(a, b);  // [1, 2, 3]

mod

function mod(a: Tensor, b: Tensor): Tensor;

Element-wise modulo (remainder).

The result takes the sign of the divisor, as in NumPy's mod and Python's %, and satisfies a == floorDiv(a, b) * b + mod(a, b). Integer x % 0 yields 0; float x % 0 yields NaN. The operands are promoted to a common dtype.

Parameters

a
Tensor
Dividend
b
Tensor
Divisor

Returns

TensorTensor of the promoted dtype

Throws

  • DTypeErrorIf either tensor has string dtype
  • ShapeErrorIf the shapes do not broadcast
Example
import { mod, tensor } from 'deepbox/ndarray'; const a = tensor([7, -8, 9]);const b = tensor([3, 3, 3]);const result = mod(a, b);  // [1, 1, 0]

mul

function mul(a: Tensor, b: Tensor): Tensor;

Element-wise multiplication.

Computes a * b element by element. The operands are promoted to a common dtype and their shapes must broadcast. Integer dtypes wrap on overflow (int32 products are computed exactly modulo 2^32).

Parameters

a
Tensor
First tensor
b
Tensor
Second tensor

Returns

TensorTensor containing element-wise product, of the promoted dtype

Throws

  • DTypeErrorIf either tensor has string dtype
  • ShapeErrorIf the shapes do not broadcast
Example
import { mul, tensor } from 'deepbox/ndarray'; const a = tensor([2, 3, 4]);const b = tensor([5, 6, 7]);const result = mul(a, b);  // [10, 18, 28]

mulScalar

function mulScalar(t: Tensor, s: number): Tensor;

Multiply all elements of a tensor by a scalar value.

Dtype rules match addScalar.

Parameters

t
Tensor
Input tensor
s
number
Scalar multiplier

Returns

TensorNew tensor with all elements multiplied by scalar

Throws

  • DTypeErrorFor string tensors
Example
import { mulScalar, tensor } from 'deepbox/ndarray'; const x = tensor([1, 2, 3]);const result = mulScalar(x, 10);  // [10, 20, 30]

nanargmax

function nanargmax(t: Tensor, axis?: Axis, keepdims?: boolean): Tensor;

Index of the maximum value along an axis, ignoring NaN (NumPy nanargmax).

The first occurrence wins on ties. The result is always int32.

Parameters

t
Tensor
Input tensor
axisoptional
Axis
Axis to search along; omit to search the flattened tensor
keepdimsoptional
boolean
If true, the reduced axis stays as a size-1 dimension

Returns

Tensorint32 tensor of indices

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf the searched slice is empty or axis is out of range
  • DataValidationErrorIf a slice contains only NaN (NumPy raises here too)
Example
import { nanargmax, tensor } from 'deepbox/ndarray'; nanargmax(tensor([NaN, 3, 7, NaN]));  // 2

nanargmin

function nanargmin(t: Tensor, axis?: Axis, keepdims?: boolean): Tensor;

Index of the minimum value along an axis, ignoring NaN (NumPy nanargmin).

The first occurrence wins on ties. The result is always int32.

Parameters

t
Tensor
Input tensor
axisoptional
Axis
Axis to search along; omit to search the flattened tensor
keepdimsoptional
boolean
If true, the reduced axis stays as a size-1 dimension

Returns

Tensorint32 tensor of indices

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf the searched slice is empty or axis is out of range
  • DataValidationErrorIf a slice contains only NaN (NumPy raises here too)
Example
import { nanargmin, tensor } from 'deepbox/ndarray'; nanargmin(tensor([NaN, 3, 1, NaN]));  // 2

nancumsum

function nancumsum(t: Tensor, axis?: Axis): Tensor;

Cumulative sum treating NaN as zero (NumPy nancumsum).

Without axis the tensor is flattened first. The dtype follows cumsum: float dtypes are kept, int32 and int64 stay, uint8 and bool give int32.

Parameters

t
Tensor
Input tensor
axisoptional
Axis
Axis to accumulate along; omit to accumulate over the flattened tensor

Returns

TensorTensor of cumulative sums

Throws

  • DTypeErrorIf t has string dtype
  • DataValidationErrorIf an integer sum overflows
  • InvalidParameterErrorIf axis is out of range
Example
import { nancumsum, tensor } from 'deepbox/ndarray'; nancumsum(tensor([1, NaN, 3]));  // [1, 1, 4]

nanmedian

function nanmedian(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Median ignoring NaN (NumPy nanmedian).

Each slice uses only its non-NaN values; a slice without any (including an empty slice) gives NaN. Float input keeps its dtype and integer or bool input gives float32.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of medians

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
import { nanmedian, tensor } from 'deepbox/ndarray'; nanmedian(tensor([1, NaN, 3, 10]));  // 3nanmedian(tensor([[1, NaN], [3, 5]]), 1);  // [1, 4]

nanprod

function nanprod(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Product treating NaN as one (NumPy nanprod).

The product of an empty or all-NaN slice is 1. The dtype follows prod: float dtypes are kept, int32 and int64 stay, uint8 and bool give int32.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of products

Throws

  • DTypeErrorIf t has string dtype
  • DataValidationErrorIf an integer product overflows
  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
import { nanprod, tensor } from 'deepbox/ndarray'; nanprod(tensor([2, NaN, 4]));  // 8nanprod(tensor([[2, NaN], [3, 5]]), 0);  // [6, 5]

nanquantile

function nanquantile(t: Tensor, q: number | readonly number[], axis?: AxisArg, keepdims?: boolean): Tensor;

Quantiles ignoring NaN, with linear interpolation (NumPy nanquantile, method="linear").

Details

Each slice uses only its non-NaN values; a slice without any (including an empty slice) gives NaN. With a scalar q the result has the reduced shape; with an array q a leading axis of length q.length is added, as in NumPy. Float input keeps its dtype and integer or bool input gives float32. An infinite value interpolates to that infinity where NumPy would return NaN from inf - inf (the same rule as quantile in the stats module).

Parameters

t
Tensor
Input tensor
q
number | readonly number[]
Quantile or list of quantiles in [0, 1]
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of quantiles

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf a quantile is outside [0, 1] or not finite, or an axis is invalid
Example
import { nanquantile, tensor } from 'deepbox/ndarray'; nanquantile(tensor([1, NaN, 3, 5]), 0.5);        // 3nanquantile(tensor([1, NaN, 3, 5]), [0.25, 1]);  // [2, 5]

nanvar

function nanvar(t: Tensor, axis?: AxisArg, keepdims?: boolean, ddof?: number): Tensor;

Variance ignoring NaN (NumPy nanvar).

Computes sum((x - mean(x))^2) / (count - ddof) over the non-NaN values of each slice, in float64. A slice with count - ddof <= 0 non-NaN values (including an empty or all-NaN slice) gives NaN. Float input keeps its dtype and integer or bool input gives float32.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions
ddofoptional
number
Delta degrees of freedom (default: 0, population variance)

Returns

TensorTensor of variances

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf ddof is negative or not finite, or an axis is invalid
Example
import { nanvar, tensor } from 'deepbox/ndarray'; nanvar(tensor([1, NaN, 3]));  // 1nanvar(tensor([[1, NaN], [3, 5]]), 1);  // [0, 1]

neg

function neg(t: Tensor): Tensor;

Element-wise negation.

Returns -x for each element. uint8 values wrap modulo 256. bool tensors are rejected (NumPy does too); use logicalNot instead.

Parameters

t
Tensor
Input tensor

Returns

TensorTensor of the same dtype and shape

Throws

  • DTypeErrorFor bool and string tensors
Example
import { neg, tensor } from 'deepbox/ndarray'; const x = tensor([1, -2, 3]);const result = neg(x);  // [-1, 2, -3]

notEqual

function notEqual(a: Tensor, b: Tensor): Tensor;

Element-wise inequality (not equal) comparison.

Returns a boolean tensor where each element is true (1) if the corresponding elements in a and b are not equal, false (0) otherwise. NaN is unequal to everything, including itself.

Parameters

a
Tensor
First input tensor
b
Tensor
Second input tensor

Returns

Tensorbool tensor with the broadcast shape

Throws

  • DTypeErrorFor string tensors
  • ShapeErrorIf the shapes do not broadcast

pow

function pow(a: Tensor, b: Tensor): Tensor;

Element-wise power.

Raises elements of the first tensor to powers from the second tensor, with IEEE-754 special cases (pow(1, NaN) is 1, pow(x, 0) is 1). The operands are promoted to a common dtype. Integer powers are computed exactly and wrap on overflow; if any int32/int64 exponent is negative the whole result is float32 (NumPy and PyTorch would raise an error there).

Parameters

a
Tensor
Base
b
Tensor
Exponent

Returns

TensorTensor of the promoted dtype (float32 for negative integer exponents)

Throws

  • DTypeErrorIf either tensor has string dtype
  • ShapeErrorIf the shapes do not broadcast
Example
import { pow, tensor } from 'deepbox/ndarray'; const a = tensor([2, 3, 4]);const b = tensor([2, 3, 2]);const result = pow(a, b);  // [4, 27, 16]

prod

function prod(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Product of array elements over the given axes.

Output dtype: - int64 stays int64 - int32, uint8 and bool produce int32 - float16, bfloat16, float32 and float64 keep their dtype

Integer products that leave the output range throw instead of wrapping around. The product of an empty reduction is 1.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, all elements are multiplied
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of products

Throws

  • DTypeErrorIf t has string dtype
  • DataValidationErrorIf an int32 or int64 product overflows
  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
import { tensor, prod } from 'deepbox/ndarray'; prod(tensor([1, 2, 3, 4]));  // 24prod(tensor([[1, 2], [3, 4]]), 0);  // [3, 8]

reciprocal

function reciprocal(t: Tensor): Tensor;

Element-wise reciprocal.

Returns 1/x for each element. Float dtypes are kept; integer and bool inputs produce float32 (NumPy would truncate to integers); 1/0 is Infinity.

Parameters

t
Tensor
Input tensor

Returns

TensorTensor of the float dtype matching the input

Throws

  • DTypeErrorFor string tensors
Example
import { reciprocal, tensor } from 'deepbox/ndarray'; const x = tensor([2, 4, 8]);const result = reciprocal(x);  // [0.5, 0.25, 0.125]

round

function round(t: Tensor, decimals?: number): Tensor;

Element-wise rounding, halves to even (like numpy.round).

round(0.5) is 0, round(1.5) and round(2.5) are 2. With decimals the value is scaled by 10 ** decimals, rounded, and scaled back, so a negative decimals rounds to tens, hundreds, and so on. Binary floating point makes some decimal halves inexact (round(2.675, 2) is 2.68 because 2.675 * 100 evaluates to exactly 267.5).

Parameters

t
Tensor
Input tensor
decimalsoptional
number
Number of decimal places, may be negative (default: 0)

Returns

TensorTensor of rounded values: the input's float dtype, integer dtypes unchanged (rounding to tens with a negative decimals included), float32 for bool input

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf decimals is not an integer
Example
import { round, tensor } from 'deepbox/ndarray'; round(tensor([0.5, 1.5, 2.5]));              // [0, 2, 2]round(tensor([1.234, 5.678]), 1);            // [1.2, 5.7]round(tensor([1234.5678]), -2);              // [1200]

rsqrt

function rsqrt(t: Tensor): Tensor;

Element-wise reciprocal square root.

Returns 1/sqrt(x) for each element.

Parameters

t
Tensor

Returns

Tensor

Example
import { rsqrt, tensor } from 'deepbox/ndarray'; const x = tensor([4, 9, 16]);const result = rsqrt(x);  // [0.5, 0.333..., 0.25]

sign

function sign(t: Tensor): Tensor;

Element-wise sign function.

Returns -1, 0, or 1 depending on the sign of each element. Zeros (including -0) map to 0 and NaN stays NaN.

Parameters

t
Tensor
Input tensor

Returns

TensorTensor of the same dtype and shape

Throws

  • DTypeErrorFor string tensors
Example
import { sign, tensor } from 'deepbox/ndarray'; const x = tensor([-5, 0, 3]);const result = sign(x);  // [-1, 0, 1]

sin

function sin(t: Tensor): Tensor;

Element-wise sine of angles in radians.

Defined for all finite inputs; sin(±Infinity) and sin(NaN) are NaN.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, sin } from "deepbox/ndarray"; sin(tensor([0, Math.PI / 2], { dtype: "float64" })).toArray(); // [0, 1]

sinh

function sinh(t: Tensor): Tensor;

Element-wise hyperbolic sine.

Overflows to ±Infinity for magnitudes above about 710.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, sinh } from "deepbox/ndarray"; sinh(tensor([0, 1])).toArray(); // [0, 1.1752011936438014]

sort

function sort(t: Tensor, axis?: Axis | undefined, descending?: boolean): Tensor;

Sort values along a given axis, returning a new tensor of the same shape and dtype.

Details

NaNs are treated as larger than every other value: they end up last for ascending order and first for descending order (NumPy / PyTorch behavior). -0 and +0 compare equal. The input is never modified. A 0-d tensor is treated as a single element (axis 0 or -1), as in PyTorch.

Complexity is O(L log L) per lane of length L, with a linear-time radix sort for long float lanes.

Parameters

t
Tensor
Input tensor (any numeric dtype, including int64)
axisoptional
Axis | undefined
Axis to sort along (default: -1, the last axis)
descendingoptional
boolean
Sort from largest to smallest (default: false)

Returns

Tensor

Throws

  • DTypeErrorIf the tensor has string dtype
  • InvalidParameterErrorIf axis is out of range
Example
import { tensor, sort } from "deepbox/ndarray"; sort(tensor([3, 1, 2])).toArray(); // [1, 2, 3]sort(tensor([[3, 1], [2, 5]]), 0).toArray(); // [[2, 1], [3, 5]]

sqrt

function sqrt(t: Tensor): Tensor;

Element-wise square root.

Output dtype: the input's float dtype; integer and bool input gives float32.

Parameters

t
Tensor
Input tensor

Returns

TensorTensor with sqrt(x) for each element

Example
import { sqrt, tensor } from 'deepbox/ndarray'; const x = tensor([4, 9, 16]);const result = sqrt(x);  // [2, 3, 4]

square

function square(t: Tensor): Tensor;

Element-wise square.

Float input keeps its dtype. Integer input keeps its dtype and wraps on overflow (bool gives int32), as in NumPy.

Parameters

t
Tensor

Returns

Tensor

Example
import { square, tensor } from 'deepbox/ndarray'; const x = tensor([1, 2, 3]);const result = square(x);  // [1, 4, 9]

std

function std(t: Tensor, axis?: AxisArg, keepdims?: boolean, ddof?: number): Tensor;

Standard deviation over the given axes: the square root of variance.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, the standard deviation of all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions
ddofoptional
number
Delta degrees of freedom; 0 for population (default), 1 for sample standard deviation

Returns

TensorTensor of standard deviations (float dtypes are kept, integer and bool input gives float32)

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf t is empty, ddof is negative or not finite, ddof >= N, or an axis is invalid
Example
import { tensor, std } from 'deepbox/ndarray'; const t = tensor([1, 2, 3, 4, 5]);std(t);                       // 1.414...std(t, undefined, false, 1);  // 1.581... const t2 = tensor([[1, 2], [3, 4]]);std(t2, 0);  // [1, 1]std(t2, 1);  // [0.5, 0.5]

sub

function sub(a: Tensor, b: Tensor): Tensor;

Element-wise subtraction.

Computes a - b element by element. The operands are promoted to a common dtype and their shapes must broadcast. Integer dtypes wrap on overflow.

Parameters

a
Tensor
First tensor
b
Tensor
Second tensor

Returns

TensorTensor containing element-wise difference, of the promoted dtype

Throws

  • DTypeErrorIf the promoted dtype is bool, or either tensor is string
  • ShapeErrorIf the shapes do not broadcast
Example
import { sub, tensor } from 'deepbox/ndarray'; const a = tensor([5, 6, 7]);const b = tensor([1, 2, 3]);const result = sub(a, b);  // [4, 4, 4]

sum

function sum(t: Tensor, axis?: AxisArg, keepdims?: boolean): Tensor;

Sum of array elements over the given axes.

Details

Output dtype: - int64 stays int64 - float16, bfloat16, float32 and float64 keep their dtype - int32 stays int32; uint8 and bool promote to int32

Integer sums that leave the output range throw instead of wrapping around. The sum of an empty reduction is 0. Floating-point sums use pairwise accumulation in float64 and round once to the output dtype, so the result can differ from a left-to-right sum in the last bits.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, all elements are summed
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions

Returns

TensorTensor of sums

Throws

  • DTypeErrorIf t has string dtype
  • DataValidationErrorIf an int32 or int64 sum overflows
  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
import { sum, tensor } from 'deepbox/ndarray'; const x = tensor([[1, 2], [3, 4]]);sum(x);          // 10sum(x, 0);       // [4, 6]sum(x, [0, 1]);  // 10

tan

function tan(t: Tensor): Tensor;

Element-wise tangent of angles in radians.

Odd multiples of pi/2 give very large finite values, not Infinity, because pi/2 is not exactly representable.

The result has the input's float dtype; bool, uint8, int32 and int64 input gives float32. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew float tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, tan } from "deepbox/ndarray"; tan(tensor([0, Math.PI / 4], { dtype: "float64" })).toArray(); // [0, 0.9999999999999999]

tanh

function tanh(t: Tensor): Tensor;

Element-wise hyperbolic tangent.

Saturates to ±1 for large magnitudes. The result has the input's float dtype (bool, uint8, int32 and int64 input gives float32); a tensor on a kernel backend stays on that device and keeps its floating dtype. int64 values beyond 2^53 - 1 throw instead of being rounded silently.

Parameters

t
Tensor
Input tensor of any numeric dtype

Returns

TensorNew tensor with the same shape and device

Throws

  • DTypeErrorIf the tensor has string dtype
  • DataValidationErrorIf an int64 value exceeds 2^53 - 1
Example
import { tensor, tanh } from "deepbox/ndarray"; tanh(tensor([0, 1])).toArray(); // [0, 0.7615941559557649]

trunc

function trunc(t: Tensor): Tensor;

Element-wise truncate (round toward zero).

Float input keeps its dtype, integer input is returned unchanged as the same integer dtype, and bool input gives float32.

Parameters

t
Tensor

Returns

Tensor

variance

function variance(t: Tensor, axis?: AxisArg, keepdims?: boolean, ddof?: number): Tensor;

Variance over the given axes.

Computes sum((x - mean(x))^2) / (N - ddof) with a two-pass algorithm in float64. Float input keeps its dtype and integer or bool input gives float32. This throws when the reduction has no elements or when ddof >= N, rather than returning NaN or Infinity.

Parameters

t
Tensor
Input tensor
axisoptional
AxisArg
Axis or list of axes to reduce. If omitted, the variance of all elements
keepdimsoptional
boolean
If true, reduced axes stay as size-1 dimensions
ddofoptional
number
Delta degrees of freedom; 0 for population variance (default), 1 for the sample variance

Returns

TensorTensor of variances

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf t is empty, ddof is negative or not finite, ddof >= N, or an axis is invalid
Example
import { tensor, variance } from 'deepbox/ndarray'; const t = tensor([1, 2, 3, 4, 5]);variance(t);                       // 2variance(t, undefined, false, 1);  // 2.5 const t2 = tensor([[1, 2], [3, 4]]);variance(t2, 0);  // [1, 1]variance(t2, 1);  // [0.25, 0.25]
ndarray-ops.ts
import {  add,  dot,  exp,  greater,  logicalAnd,  mean,  sort,  std,  sum,  tensor,  where,} from "deepbox/ndarray"; const x = tensor([[1, 2], [3, 4]]);const y = tensor([[10, 20], [30, 40]]); console.log(add(x, y).toString());console.log(x.mul(y).add(1).toString()); // methods chain and accept numbersconsole.log(exp(x).toString());console.log(sum(x, 0).toString(), mean(y).toString());console.log(std(y).toString()); // population standard deviation, ddof = 0console.log(sort(tensor([3, 1, 2])).toString());console.log(logicalAnd(tensor([1, 0, 1]), tensor([1, 1, 0])).toString());console.log(where(greater(x, tensor(2)), x, y).toString());console.log(dot(x, y).toString());